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 2.22.0: backlog fixes, managed-download restores, dashboard create recovery, authoring offers (#813)
Akshay Maloo9a3cf2e61277
diff --git a/evals/model-apps/app-builder/EVAL_GUIDE.md b/evals/model-apps/app-builder/EVAL_GUIDE.mdindex b96ce24ca..2e0be9d4c 100644--- a/evals/model-apps/app-builder/EVAL_GUIDE.md+++ b/evals/model-apps/app-builder/EVAL_GUIDE.md@@ -12,9 +12,10 @@| Stage | Oracle | Plugin primitive ||---|---|---|| **author** | `validateAppSpec(plan profile)` passes · no lint errors · artifact names are table/type-scoped · ASCII page-quote warnings stay visible without changing approved names. Other advisories remain non-fatal. | `app-spec.js`, `spec-lint.js` |+| **author** (optional capabilities) | Off unless the prompt asks for them, on every fixture: `app.theme`, a configuration item (`environmentVariables`, `connectionReferences`, `customApis`, `duplicateDetectionRules`, `solution.version`) and a declared form, dashboard, business rule or process flow (`reconcile: "declared"`) are present only when `expect` says the prompt asked. What it asked for must be there, graded by kind and table only (`expect.declared`: names, stage labels, tile order and scope are not compared, and nothing in this check grades an artifact's shape), so removing the only declared artifact of an asked kind on a table, dropping its `reconcile`, a wrong table or an extra kind fails; with several declared artifacts of one kind on a table, only the count the prompt states is checked. A prompt that declines rules and flows (`expect.noBusinessLogic`) gets no plain rule or flow either. See "Optional capabilities". | `app-spec.js`, `assertions.js` || **plan** | Every planned item targets a known engine phase | `sdk-build.js` `planFor` + `PHASES` || **data** | Normalized data-model facts match the `expect.tables/relationships` block | `schema-facts.js` `schemaFacts` |-| **ui** | View/chart names match `expect.views/charts` · explicit tab/section names, topology, percentage widths, display flags, field state and spans match authored input · enriched **default views** keep parent lookups (#2) and drop `createdon` (#7) · each **sub-grid** is a full-width 1-column section titled by the child display name (#5) | `sdk-build.js` `viewDef` / `chartDef` / `compileFormIntent` / `defaultViewColumns` / `subgridLabel` · `artifact-intent.js` `subgridSectionIntent` |+| **ui** | View/chart names match `expect.views/charts` · a filter the prompt names (`expect.viewFilters`, `{ entity, view, attr, op, value }`, written from the prompt) is among the view's compiled conditions, so a spelling the build ignores (`filter`, `column`, `operator`) fails · explicit tab/section names, topology, percentage widths, display flags, field state and spans match authored input · enriched **default views** keep parent lookups (#2) and drop `createdon` (#7) · each **sub-grid** is a full-width 1-column section titled by the child display name (#5) | `sdk-build.js` `viewDef` / `chartDef` / `compileFormIntent` / `defaultViewColumns` / `subgridLabel` · `artifact-intent.js` `subgridSectionIntent` || **app** | Every sitemap subarea resolves to a concrete target · no dangling `navigatesTo` keys | `sdk-build.js` `appDef` || **security** | Each declared persona maps to exactly one role · the role **injects** `appmodule` read for app-access personas (and only those) · every persona privilege on an **app-owned** table (the app's own publisher prefix) resolves to a provisioned entity (JTBD coverage) · the role grants **exactly** its jobs' declared privileges — no extra entity, access token, or inflated scope beyond the declared union + the documented `appmodule` injection (least privilege) | `sdk-build.js` `personaRoleSpecFor` || **verify** | Required verification succeeds, reports no missing artifacts, and actually runs each applicable check kind. Fixture 7 supplies independent deployed XML and served Main form order instead of compiler-rendered XML. | `verify-spec.js` `verifySpec` |@@ -37,9 +38,38 @@ does nothing. A business rule with a mis-shaped condition tree deploys, activateBPF step with no bound field is refused only at push time, on a live environment. Counting artifactswould stay green through both, so the assertions grade the **bindings** the pure def builders emit.+### Optional capabilities++`/app-builder` offers branding, configuration items, declared rules and flows, and declared form and dashboard layouts+as questions (`references/authoring-flow.md`, Levels (a0) and (b)), and writes none of them by default. What these evals+grade is the **spec**, in both directions, on every fixture:++- A capability nobody asked for fails. With no expectation, a spec that carries `app.theme`, a configuration item or a+ declared form, dashboard, rule or flow fails, so adding one to an ordinary fixture is caught.+- A capability the prompt asked for must be there (`appTheme`, `configuration`, `declared` in `expect`). The check is+ presence and absence by capability kind and table, nothing finer: the theme is present iff asked; each configuration+ field is non-empty iff asked; for each declared kind (form, dashboard, business rule, process flow) the set of tables+ carrying a `reconcile: "declared"` artifact equals the asked set, with at least `minCount` artifacts where the prompt+ states a count. Removing the only declared artifact of an asked kind on a table, dropping its `reconcile: "declared"`,+ putting it on another table, or adding an artifact of a kind or table nobody asked for fails; when a table carries several+ declared artifacts of one kind, only the count the prompt states is checked. Names, stage labels, tile order and scope are+ never compared here.+- What grades a declared artifact's shape, and what does not. On every fixture the common assertions check that each+ business rule binds only columns the spec creates and compiles at least one condition and one action, that each+ process-flow step binds a field on the flow's table and each stage is scoped to that table, and that each declared+ dashboard, rule and flow has a teardown step. Beyond that, among the fixtures 21-24 only fixture 21 has its own shape assertions (the authored+ tab, form-column and section topology, and column and row spans). The shape of the declared dashboard (tiles) in+ fixture 22, of the declared rules in fixture 23 (scope, conditions) and of the declared flow (stages) in fixture 24 is+ **not graded yet**: removing a tile or a stage still passes. Grading those shapes is a follow-up.+- A prompt that declines rules and flows (`expect.noBusinessLogic: true`) fails on any rule or flow, declared or not.++Whether the agent makes the offer is **not** graded. That is a property of a conversation, and no offline harness records+one; a hand-written record of an offer would only certify itself. Grading the offer needs a harness that captures a+transcript of a real `/app-builder` run. That is a follow-up.+## Fixtures-Each fixture lives in `fixtures/<id>-<slug>/` and contains `app-spec.json`.+Each fixture lives in `fixtures/<id>-<slug>/` and contains `app-spec.json`.Naming is numeric-prefix; `fixture-loader.js` matches `^(\d+)(?:-(.+))?$`.Optional `evidence.json` selects fixture evidence, `baseline-app-spec.json` supplies the prior spec,and `entity-edit-app-spec.json` supplies fixture 9's schema-only edit. FormXML file references are@@ -71,6 +101,7 @@ confined to the fixture directory, including when the fixtures root is a junctio| 22 | `22-declared-dashboard` | A "keep this dashboard's tiles the way the spec says" ask declares a global Standard dashboard with `reconcile: "declared"`, a `key` on it and on each tile (a two-column list, a chart, a tall iframe), and the app shell places it. The runner checks the plan, the sitemap target and its teardown; the declared-dashboard unit tests check that a keyed tile edit writes only that tile, an added tile goes after the last row, a tile made in Maker is kept, and a rebuild sends no write. || 23 | `23-declared-business-rule` | A "keep these business rules the way the spec says" ask declares two business rules with `reconcile: "declared"`, a `key` on each rule, condition and action: one on the table (a required resolution and a locked field when closed), one on every form (`scope: "AllForms"`, an error message from a two-condition test). The runner checks that each compiles and binds only the spec's columns, and its teardown; the declared-rule unit tests check the Draft-first create, the conditional activation, that a rebuild sends no write, the typed adoption, verify and the managed download. || 24 | `24-declared-bpf` | A "keep this process flow the way the spec says" ask declares one linear business process flow with `reconcile: "declared"`, a `key` on each stage and step (three stages, required and optional steps), a description, an order and an Active status. The runner checks that it compiles on its own table and binds only the spec's columns, and its teardown; the declared-flow unit tests check that every stage and step id is fixed before the Draft-first create, the conditional activation, that a rebuild sends no write, that an edit, omission or reorder is refused with no write, the typed adoption, verify and the managed download.+| 25 | `25-no-optional-extras` | A new-app ask that says no to branding, outside services, per-environment settings, business rules, process flows and fixed layouts gets none of them: no `app.theme`, no configuration item, no declared form, dashboard, rule or flow, and no plain business rule or process flow either (`expect.noBusinessLogic`). |> **Fixture 2 note:** `appShell.subAreas[].page` references use the page's **key** (e.g. `"overview"`), not its display name (`"Overview"`). The v2 validator requires keys, and the linter accepts valid key references; `key === name` is neither required nor used by this fixture.## `evals.json`@@ -78,7 +109,7 @@ confined to the fixture directory, including when the fixtures root is a junctio- `skill_name` — identifies this suite.- `eval_instructions` — description used by eval runners.- `common_stage_assertions` — run for every fixture; registered in `lib/assertions.js`.-- `evals[].expect` — independent per-eval counts/names plus form-edit, rejected-model, changed-only, name-scope, option-value, date-behaviour, field-security, app-membership and stable-identity contracts.+- `evals[].expect` — independent per-eval counts/names plus form-edit, rejected-model, changed-only, name-scope, option-value, view-filter, date-behaviour, field-security, app-membership and stable-identity contracts.- `evals[].expectations` — additional per-eval assertion texts (can be empty).- `evals[].tier` — `smoke` (fast subset) or `full`.diff --git a/evals/model-apps/app-builder/evals.json b/evals/model-apps/app-builder/evals.jsonindex 75534c4a0..194f87a51 100644--- a/evals/model-apps/app-builder/evals.json+++ b/evals/model-apps/app-builder/evals.json@@ -42,7 +42,8 @@"ui: every compiled form places each field exactly once","ui: every compiled form places exactly the fields it intends to carry","round-trip: a lookup's shadow columns are never recovered as spec columns (#574)",- "round-trip: a download recovers no column the spec never authored"+ "round-trip: a download recovers no column the spec never authored",+ "author: an optional capability is in the spec only when the prompt asks for it, and each one it asks for is authored as expected"],"evals": [{@@ -297,9 +298,11 @@"spec": "app-spec.json","prompt": "Shipments carry a Region from a shared choice whose numbers an integration depends on (North 1, South 2, Export 10), a bilingual Priority whose numbers must not change between environments (Low 1, High 5), and a Stage whose Held option must stay 100000005. The High Priority view filters on Priority 5.","expect": { "tables": ["cnt_shipment"], "relationships": [], "views": ["High Priority"], "charts": [], "pages": [],+ "viewFilters": [{ "entity": "cnt_shipment", "view": "High Priority", "attr": "cnt_priority", "op": "eq", "value": 5 }],"optionValues": { "cnt_region": { "1": "North", "2": "South", "10": "Export" }, "cnt_shipment.cnt_priority": { "1": "Low", "5": "High" }, "cnt_shipment.cnt_stage": { "100000005": "Held" } } },"expectations": [- "author: option values the maker depends on are written as { value, label } and the spec asks for 2.21.0"+ "author: option values the maker depends on are written as { value, label } and the spec asks for 2.21.0",+ "ui: a view filter the prompt names is built from filters[] attr/op/value"]},{@@ -520,7 +523,10 @@"Sites by Region"],"charts": [],- "pages": []+ "pages": [],+ "declared": {+ "forms": { "tables": ["cnt_site"] }+ }},"expectations": ["ui: an explicit layout compiles to the authored tab, form-column and section topology (it is not flattened)",@@ -543,7 +549,10 @@"charts": ["Work Orders by Status"],- "pages": []+ "pages": [],+ "declared": {+ "dashboards": { "minCount": 1 }+ }},"expectations": []},@@ -561,7 +570,10 @@"Open Requests"],"charts": [],- "pages": []+ "pages": [],+ "declared": {+ "businessRules": { "tables": ["cnt_request"], "minCount": 2 }+ }},"expectations": []},@@ -579,9 +591,36 @@"Open Claims"],"charts": [],- "pages": []+ "pages": [],+ "declared": {+ "businessProcessFlows": { "tables": ["cnt_claim"] }+ }},"expectations": []+ },+ {+ "id": 25,+ "tier": "full",+ "spec": "app-spec.json",+ "prompt": "A new Parts Counter app: parts with a stock level and a price, and a list of all parts. No branding, no outside services or per-environment settings, no business rules or process flows, and no fixed form or dashboard layouts.",+ "expect": {+ "tables": [+ "cnt_part"+ ],+ "relationships": [],+ "views": [+ "All Parts"+ ],+ "charts": [],+ "pages": [],+ "configuration": {},+ "noBusinessLogic": true+ },+ "expectations": [+ "author: each configuration item the prompt needs is declared, and no value that differs per environment is in the spec",+ "author: a theme is declared only on an explicit branding ask, with the asked colours, no unasked font, and a declared image web resource as the logo, never a URL",+ "author: a maker who declines business rules and process flows gets no rule and no flow of any kind"+ ]}]}diff --git a/evals/model-apps/app-builder/fixtures/1-support-desk/app-spec.json b/evals/model-apps/app-builder/fixtures/1-support-desk/app-spec.jsonindex b7fd598d7..2c65a72d4 100644--- a/evals/model-apps/app-builder/fixtures/1-support-desk/app-spec.json+++ b/evals/model-apps/app-builder/fixtures/1-support-desk/app-spec.json@@ -169,7 +169,6 @@"views": [{"entity": "new_customer",- "type": "main","name": "Active Customers","columns": ["new_name",@@ -186,7 +185,6 @@},{"entity": "new_ticket",- "type": "main","name": "Active Tickets","columns": ["new_name",@@ -204,7 +202,6 @@},{"entity": "new_comment",- "type": "main","name": "Active Comments","columns": ["new_name",diff --git a/evals/model-apps/app-builder/fixtures/17-declared-web-resource/app-spec.json b/evals/model-apps/app-builder/fixtures/17-declared-web-resource/app-spec.jsonindex 5b76d944f..d750fc779 100644--- a/evals/model-apps/app-builder/fixtures/17-declared-web-resource/app-spec.json+++ b/evals/model-apps/app-builder/fixtures/17-declared-web-resource/app-spec.json@@ -207,7 +207,6 @@"views": [{"entity": "new_case",- "type": "main","name": "Open Cases","description": "Cases that have not been resolved.","columns": [diff --git a/evals/model-apps/app-builder/fixtures/2-orders-multipage/app-spec.json b/evals/model-apps/app-builder/fixtures/2-orders-multipage/app-spec.jsonindex af363c84a..048cb7920 100644--- a/evals/model-apps/app-builder/fixtures/2-orders-multipage/app-spec.json+++ b/evals/model-apps/app-builder/fixtures/2-orders-multipage/app-spec.json@@ -82,7 +82,6 @@"views": [{"entity": "new_order",- "type": "main","name": "Active Orders","columns": ["new_name",diff --git a/evals/model-apps/app-builder/fixtures/25-no-optional-extras/app-spec.json b/evals/model-apps/app-builder/fixtures/25-no-optional-extras/app-spec.jsonnew file mode 100644index 000000000..76375388c--- /dev/null+++ b/evals/model-apps/app-builder/fixtures/25-no-optional-extras/app-spec.json@@ -0,0 +1,20 @@+{+ "schemaVersion": 2,+ "minimumPluginVersion": "2.21.0",+ "solution": { "uniqueName": "ContosoPartsCounter", "publisherPrefix": "cnt" },+ "app": {+ "name": "Parts Counter",+ "description": "Parts and their stock level"+ },+ "entities": [+ { "schemaName": "cnt_part", "displayName": "Part", "pluralName": "Parts",+ "primaryAttribute": { "schemaName": "cnt_name", "displayName": "Name" },+ "columns": [+ { "schemaName": "cnt_stock", "displayName": "Stock", "type": "Integer" },+ { "schemaName": "cnt_price", "displayName": "Price", "type": "Money" }+ ] }+ ],+ "forms": [{ "entity": "cnt_part", "name": "Information", "layout": "auto" }],+ "views": [{ "entity": "cnt_part", "name": "All Parts", "columns": ["cnt_name", "cnt_stock", "cnt_price"] }],+ "appShell": { "areas": [{ "label": "Parts", "groups": [{ "label": "Stock", "subAreas": [{ "entity": "cnt_part", "title": "Parts" }] }] }] }+}diff --git a/evals/model-apps/app-builder/fixtures/3-assets-dashboard/app-spec.json b/evals/model-apps/app-builder/fixtures/3-assets-dashboard/app-spec.jsonindex 52444f7ca..728c4b53c 100644--- a/evals/model-apps/app-builder/fixtures/3-assets-dashboard/app-spec.json+++ b/evals/model-apps/app-builder/fixtures/3-assets-dashboard/app-spec.json@@ -20,7 +20,7 @@{ "entity": "new_asset", "label": "Retire", "location": "MainTab", "library": "new_asset.js", "function": "Asset.retire" }],"views": [- { "entity": "new_asset", "type": "main", "name": "Active Assets", "columns": ["new_name", "new_status", "new_value"], "activeOnly": true }+ { "entity": "new_asset", "name": "Active Assets", "columns": ["new_name", "new_status", "new_value"], "activeOnly": true }],"charts": [{ "entity": "new_asset", "name": "Assets by Status", "groupBy": "new_status", "measure": "count", "chartType": "Column" }diff --git a/evals/model-apps/app-builder/fixtures/4-hardening/app-spec.json b/evals/model-apps/app-builder/fixtures/4-hardening/app-spec.jsonindex 2758c5012..8fc495457 100644--- a/evals/model-apps/app-builder/fixtures/4-hardening/app-spec.json+++ b/evals/model-apps/app-builder/fixtures/4-hardening/app-spec.json@@ -43,7 +43,7 @@],"views": [{- "entity": "new_ticket", "type": "main", "name": "Open Tickets",+ "entity": "new_ticket", "name": "Open Tickets","columns": ["new_subject", "new_status"], "sort": [{ "attr": "new_subject", "dir": "asc" }], "activeOnly": true}],diff --git a/evals/model-apps/app-builder/fixtures/5-process-logic/app-spec.json b/evals/model-apps/app-builder/fixtures/5-process-logic/app-spec.jsonindex 7de1eda1b..88ed83437 100644--- a/evals/model-apps/app-builder/fixtures/5-process-logic/app-spec.json+++ b/evals/model-apps/app-builder/fixtures/5-process-logic/app-spec.json@@ -104,7 +104,6 @@"views": [{"entity": "new_case",- "type": "main","name": "Open Cases","description": "Cases that have not been resolved.","columns": ["new_subject", "new_status", "new_owner"],diff --git a/evals/model-apps/app-builder/fixtures/6-form-layout/app-spec.json b/evals/model-apps/app-builder/fixtures/6-form-layout/app-spec.jsonindex 9d76a13c2..3a0b614df 100644--- a/evals/model-apps/app-builder/fixtures/6-form-layout/app-spec.json+++ b/evals/model-apps/app-builder/fixtures/6-form-layout/app-spec.json@@ -71,9 +71,9 @@] }],"views": [- { "entity": "new_project", "type": "main", "name": "Active Projects",+ { "entity": "new_project", "name": "Active Projects","columns": ["new_name", "new_stage", "new_startdate", "new_budget"], "activeOnly": true },- { "entity": "new_workitem", "type": "main", "name": "Open Work Items",+ { "entity": "new_workitem", "name": "Open Work Items","columns": ["new_title", "new_status", "new_priority", "new_projectid", "new_duedate"], "activeOnly": true }],"charts": [diff --git a/evals/model-apps/app-builder/lib/assertions.js b/evals/model-apps/app-builder/lib/assertions.jsindex 0d21585e3..2550d1d8e 100644--- a/evals/model-apps/app-builder/lib/assertions.js+++ b/evals/model-apps/app-builder/lib/assertions.js@@ -218,6 +218,24 @@ ASSERTIONS.set('ui: wire-facts build exactly the expected views and charts', ({return PASS;});+// expect.viewFilters = [{ entity, view, attr, op, value? }]: a filter the PROMPT names for a view (written here from the prompt, never+// read off the fixture being graded). It must appear among the view's compiled conditions, which are what the build reads from the+// supported filters[] { attr, op, value } shape; the active-records condition is not part of the comparison. A misspelled key+// (`filter`, `column`, `operator`) is ignored by the build, leaves no condition, and so fails here — as a missing filter does. The prompt+// names a filter on the view's own table, so a condition scoped to a joined table (a declared view's `relatedEntity`) does not satisfy it.+ASSERTIONS.set('ui: a view filter the prompt names is built from filters[] attr/op/value', ({ facts, eval: ev }) => {+ const expected = ev.expect && ev.expect.viewFilters;+ if (!Array.isArray(expected) || !expected.length) return fail('no independent view-filter expectations');+ for (const want of expected) {+ const view = facts.ui.views.find((v) => String(v.entity).toLowerCase() === String(want.entity).toLowerCase() && v.name === want.view);+ if (!view) return fail(`view '${want.view}' on ${want.entity} is not built`);+ const hit = view.conditions.some((c) => !c.scope && c.attribute === String(want.attr).toLowerCase() && c.operator === (want.op || 'eq')+ && (want.value === undefined ? c.value === undefined : c.value === String(want.value)));+ if (!hit) return fail(`view '${want.view}': no condition ${want.attr} ${want.op || 'eq'} ${want.value === undefined ? '' : JSON.stringify(want.value)}; got ${JSON.stringify(view.conditions)}`);+ }+ return PASS;+});+// #2 (default-view lookups not truncated) + #7 (enriched default views drop createdon).ASSERTIONS.set('ui: enriched default views keep parent lookups and drop createdon', ({ facts }) => {const dv = (facts.ui && facts.ui.defaultViews) || {};@@ -1152,4 +1170,69 @@ ASSERTIONS.set('author: the skill tells the maker that an unsent local edit stopreturn missing.length ? fail(`the createIdentity guidance does not say ${missing.join(', ')}`) : PASS;});+// Optional capabilities are OFF unless the maker asks for them (or says yes when /app-builder offers one; references/authoring-flow.md,+// Level (a0) and (b)). This suite grades the spec, not the conversation, so what it pins is the spec-level opt-in, in both directions,+// on EVERY fixture: the spec carries an app theme, a configuration item, or a declared form, dashboard, business rule or process flow+// only when the prompt asks for it (no expectation = none is allowed). Whether the offer itself is made needs a transcript of a+// conversation (EVAL_GUIDE.md, "Optional capabilities").+// It grades presence and absence by capability kind and table, and nothing else: a name, a stage label, a tile order or a scope is the+// maker's to choose, so none of them is compared here, and this check grades no shape at all. Shape is graded elsewhere only in part:+// the common process assertions check well-formedness, fixture 21 has its own layout assertions, and the declared dashboard,+// rules and flow of fixtures 22-24 have no shape assertion yet (EVAL_GUIDE.md, "Optional capabilities").+// expect.appTheme as the theme assertion reads it (set = a theme is asked for)+// expect.configuration as the configuration assertion reads it (a non-empty list, or solutionVersion, is an ask)+// expect.declared { forms|dashboards|businessRules|businessProcessFlows: { tables: [table...], minCount: n } }+// for each kind the prompt asks to keep declared. The tables that carry a `reconcile: "declared"` artifact of+// that kind must be exactly `tables` (a dashboard has no table, so it states none), and there must be at least+// `minCount` of them (default 1) where the prompt states a count. A kind it does not list allows none.+const lc = (v) => String(v === undefined ? '' : v).toLowerCase();+const DECLARED_KINDS = ['forms', 'dashboards', 'businessRules', 'businessProcessFlows'];const CONFIGURATION_LISTS = ['environmentVariables', 'connectionReferences', 'customApis', 'duplicateDetectionRules'];+const nonEmptyList = (list) => Array.isArray(list) && list.length > 0;+ASSERTIONS.set('author: an optional capability is in the spec only when the prompt asks for it, and each one it asks for is authored as expected', ({ spec, eval: ev }) => {+ const expect = (ev && ev.expect) || {};+ const theme = spec.app && spec.app.theme;+ if (theme !== undefined && !expect.appTheme) return fail('app.theme is declared, but the prompt asks for no branding');+ if (theme === undefined && expect.appTheme) return fail('the prompt asks for branding, but app.theme is not declared');+ const config = expect.configuration && typeof expect.configuration === 'object' ? expect.configuration : {};+ for (const field of CONFIGURATION_LISTS) {+ const have = nonEmptyList(spec[field]);+ const want = nonEmptyList(config[field]);+ if (have && !want) return fail(`${field} is declared, but the prompt asks for no such configuration item`);+ if (!have && want) return fail(`the prompt asks for ${field} [${config[field]}], but the spec declares none`);+ }+ const version = spec.solution && spec.solution.version;+ if (version !== undefined && !config.solutionVersion) return fail(`solution.version ${version} is declared, but the prompt asks for no version`);+ if (version === undefined && config.solutionVersion) return fail(`the prompt asks for solution.version ${config.solutionVersion}, but the spec omits it`);+ const declaredExpect = expect.declared && typeof expect.declared === 'object' ? expect.declared : {};+ for (const kind of Object.keys(declaredExpect)) if (!DECLARED_KINDS.includes(kind)) return fail(`expect.declared names the unknown kind '${kind}'`);+ let anyDeclared = false;+ for (const kind of DECLARED_KINDS) {+ const got = (Array.isArray(spec[kind]) ? spec[kind] : []).filter((x) => x && typeof x === 'object' && x.reconcile === 'declared');+ const want = declaredExpect[kind];+ if (!want) {+ if (got.length) return fail(`${kind} declared on [${got.map((x) => x.entity || '(no table)')}], but the prompt asks to keep no ${kind} declared`);+ continue;+ }+ if (got.length < (want.minCount || 1)) return fail(`${kind}: ${got.length} declared, but the prompt asks for ${want.minCount || 1}; missing (deleted, or without reconcile "declared")`);+ if (Array.isArray(want.tables)) {+ const have = [...new Set(got.map((x) => lc(x.entity)))].sort();+ const asked = [...new Set(want.tables.map(lc))].sort();+ if (!eq(have, asked)) return fail(`${kind} declared on [${have}], the prompt asks for [${asked}]; unasked: [${have.filter((t) => !asked.includes(t))}], missing: [${asked.filter((t) => !have.includes(t))}]`);+ }+ anyDeclared = true;+ }+ if (anyDeclared && !versionAtLeast(spec.minimumPluginVersion, '2.21.0')) return fail(`minimumPluginVersion ${spec.minimumPluginVersion || '(none)'} is below 2.21.0`);+ return PASS;+});++// A maker who says no to business rules and process flows gets none of ANY kind: the declared-capability check above sees only+// `reconcile: "declared"`, and a plain rule or flow is authored without it. expect.noBusinessLogic is written from the prompt.+ASSERTIONS.set('author: a maker who declines business rules and process flows gets no rule and no flow of any kind', ({ spec, eval: ev }) => {+ if (!ev.expect || ev.expect.noBusinessLogic !== true) return fail('no independent expectation that the prompt declines business rules and process flows');+ for (const kind of ['businessRules', 'businessProcessFlows']) {+ if (nonEmptyList(spec[kind])) return fail(`${kind} is declared (${spec[kind].map((x) => (x && x.name) || '?').join(', ')}), but the prompt declines them`);+ }+ return PASS;+});+module.exports = { ASSERTIONS };\ No newline at end of filediff --git a/evals/model-apps/app-builder/lib/facts.js b/evals/model-apps/app-builder/lib/facts.jsindex 45ea4fdb3..e3ccbe650 100644--- a/evals/model-apps/app-builder/lib/facts.js+++ b/evals/model-apps/app-builder/lib/facts.js@@ -12,6 +12,7 @@ function pluginLib2(name) { return require(path.join(__dirname, '..', '..', '..'const { migrateAppSpec, validateAppSpec, lookupColumnsFor, normalizePageSource, SDK_ROLE_MARKER, FORM_TYPE_CODE, formLayoutNames, subgridRelationshipName } = pluginLib('app-spec.js');const { lintAppSpec } = pluginLib('spec-lint.js');+const { isDeclaredView, compileViewIntent } = pluginLib('view-reconcile.js');const { planFor, PHASES, appDef, viewDef, chartDef, compileFormIntent, formFieldLogicals, defaultViewColumns, enrichesDefaultViews, subgridLabel, personaRoleSpecFor, businessRuleDef, bpfDef } = pluginLib('sdk-build.js');const { subgridSectionIntent, isNonFieldControl } = pluginLib('artifact-intent.js');const { SUBGRID_CLASS_ID, splitSubgrids, columnItems } = pluginLib('form-subgrid-placement.js');@@ -112,11 +113,46 @@ function planFacts(spec) {return { byPhase, phases: Object.keys(byPhase), labels: items.map((i) => `${i.phase}\t${i.label}`) };}+// compileViewIntent reads filters, linkEntities (and each join's filters), columns and sort as arrays and throws a TypeError on any other+// shape (`linkEntities: {}` -> "(v.linkEntities || []).forEach is not a function"). The author gate (validateAppSpec) already reports each+// of those precisely (`views[0].linkEntities must be an array`), and the build refuses such a spec, so a view the compiler cannot read has+// no conditions. Letting the TypeError escape would replace that diagnostic and every other grade of the fixture with one generic failure.+// Only a TypeError is treated this way; any other failure of the compiler is a real fault and still surfaces.+function compileDeclaredView(v, resolveValue) {+ try { return compileViewIntent(v, { resolveValue }); }+ catch (e) {+ if (e instanceof TypeError) return { intent: null };+ throw e;+ }+}++// The conditions the build gives a view from its filters[], each `{ attribute, operator, value }` plus `scope` (the join alias) on one that+// constrains a joined table. The build compiles a view one of two ways and the facts must follow it: a declared view (`reconcile:+// "declared"`) goes through compileViewIntent, which scopes a condition to its join (`relatedEntity`); every other view goes through viewDef,+// which reads no scope at all. Reading a declared view through viewDef would grade a filter on a joined table as one on the view's own table.+function viewConditions(spec, v, d) {+ // The leading active-records condition (statecode eq 0, when activeOnly is not false) is the build's own, not the author's filter.+ const authored = (list) => (v.activeOnly !== false ? list.slice(1) : list);+ if (!isDeclaredView(v)) return authored(d.filters.conditions).map((c) => ({ attribute: c.attribute, operator: c.operator, value: c.value }));+ // The build resolves a choice label to its value with resolveFilterValue, which sdk-build does not export; a one-condition view built by+ // viewDef on the condition's own table runs exactly that rule.+ const resolveValue = (table, attr, value) => viewDef(spec, { entity: table, name: 'x', activeOnly: false, filters: [{ attr, op: 'eq', value }] }).filters.conditions[0].value;+ const { intent } = compileDeclaredView(v, resolveValue);+ // A declared view that does not compile is refused by the build: no view, so no filter.+ if (!intent) return [];+ return authored(intent.filters.conditions).map((c) => ({ attribute: c.attribute, operator: c.operator, value: c.value, ...(c.entityname ? { scope: c.entityname } : {}) }));+}+// ui: normalized view/chart/form facts from the pure def builders — the pre-serialization equivalents// of wire-facts.js (viewFacts/chartFacts/formFacts), deterministic with no live env or bundle round-trip.function wireFacts(spec) {return {- views: (spec.views || []).map((v) => { const d = viewDef(spec, v); return { entity: d.entityLogicalName, name: d.name, columns: d.columns.map((c) => c.name) }; }),+ views: (spec.views || []).map((v) => {+ const d = viewDef(spec, v);+ // What viewConditions returns is what the author's filters[] compiled to, so a filter the build ignored (a misspelled key) leaves+ // nothing here.+ return { entity: d.entityLogicalName, name: d.name, columns: d.columns.map((c) => c.name), conditions: viewConditions(spec, v, d) };+ }),charts: (spec.charts || []).map((c) => { const d = chartDef(spec, c); return { entity: d.entityLogicalName, name: d.name, measure: d.series[0].aggregate, groupBy: d.categories[0].attribute }; }),forms: (spec.forms || []).map((f) => {const authoredShape = authoredFormShape(f);diff --git a/evals/model-apps/app-builder/run-app-builder.js b/evals/model-apps/app-builder/run-app-builder.jsindex d1d25c776..964749f86 100644--- a/evals/model-apps/app-builder/run-app-builder.js+++ b/evals/model-apps/app-builder/run-app-builder.js@@ -87,7 +87,10 @@ async function main() {}reporter.end();- process.exit(reporter.exitCode);+ // Set the exit code instead of calling process.exit(): on macOS and Linux a piped stdout is+ // written asynchronously, so exiting at once can cut off the end of this (over 100 KB) TAP output+ // when the reader is slower than the writer; Node exits on its own once the writes drain.+ process.exitCode = reporter.exitCode;}if (require.main === module) main();diff --git a/evals/model-apps/app-builder/tests/facts.test.js b/evals/model-apps/app-builder/tests/facts.test.jsindex b36c1bbb8..27d4796d6 100644--- a/evals/model-apps/app-builder/tests/facts.test.js+++ b/evals/model-apps/app-builder/tests/facts.test.js@@ -871,6 +871,90 @@ test('fixture 11 filters its High Priority view on Priority 5 in the shape the vassert.strictEqual(mutated((v) => { delete v.filters; }), false, 'no filter');});+// The runner grades the same thing on a generated spec: fixture 11's expectation names the filter the prompt asks for, and the check reads+// the conditions the view builder compiled, so a spelling it ignores grades as a missing filter.+const FILTER_ASSERTION = 'ui: a view filter the prompt names is built from filters[] attr/op/value';+async function gradeViewFilter(mutate, mutateEval) {+ const fixture = fixtureFor(11);+ const spec = structuredClone(fixture.spec);+ if (mutate) mutate(spec.views.find((v) => v.name === 'High Priority'), spec);+ const ev = structuredClone(evalsManifest.evals.find((e) => e.id === 11));+ if (mutateEval) mutateEval(ev);+ const facts = await stageFacts(spec, { fixture });+ return ASSERTIONS.get(FILTER_ASSERTION)({ facts, spec, eval: ev });+}++test('the view-filter expectation of fixture 11 is written from the prompt and graded in its own assertion', () => {+ const ev = evalsManifest.evals.find((e) => e.id === 11);+ assert.deepStrictEqual(ev.expect.viewFilters, [{ entity: 'cnt_shipment', view: 'High Priority', attr: 'cnt_priority', op: 'eq', value: 5 }]);+ assert.ok(ev.expectations.includes(FILTER_ASSERTION), 'the assertion is listed in the eval expectations');+ assert.ok(/Priority 5/.test(ev.prompt), 'the prompt names the filter the expectation checks');+});++test('view-filter grading: the right filter passes; a missing filter, the old spelling, a wrong value, op or column fail', async () => {+ assert.strictEqual((await gradeViewFilter()).status, 'pass');+ const missing = await gradeViewFilter((v) => { delete v.filters; });+ assert.strictEqual(missing.status, 'fail', 'no filter');+ assert.match(missing.reason, /no condition cnt_priority eq 5/);+ assert.strictEqual((await gradeViewFilter((v) => { v.filter = [{ column: 'cnt_priority', operator: 'eq', value: 5 }]; delete v.filters; })).status, 'fail', 'old filter[].column/operator spelling');+ assert.strictEqual((await gradeViewFilter((v) => { v.filters = [{ column: 'cnt_priority', operator: 'eq', value: 5 }]; })).status, 'fail', 'old column/operator inside filters[]');+ assert.strictEqual((await gradeViewFilter((v) => { v.filters[0].value = 1; })).status, 'fail', 'wrong value');+ assert.strictEqual((await gradeViewFilter((v) => { v.filters[0].op = 'ne'; })).status, 'fail', 'wrong operator');+ assert.strictEqual((await gradeViewFilter((v) => { v.filters[0].attr = 'cnt_stage'; })).status, 'fail', 'wrong column');+ assert.strictEqual((await gradeViewFilter((v) => { v.name = 'Urgent'; })).status, 'fail', 'the filter on a view with another name');+});++test('view-filter grading: the active-records condition is neither the filter nor in the way of it', async () => {+ assert.strictEqual((await gradeViewFilter((v) => { v.activeOnly = false; })).status, 'pass', 'activeOnly false leaves the filter');+ assert.strictEqual((await gradeViewFilter((v) => { v.filters = []; v.activeOnly = true; })).status, 'fail', 'statecode alone is not a Priority filter');+ assert.strictEqual((await gradeViewFilter(null, (ev) => { ev.expect.viewFilters = [{ entity: 'cnt_shipment', view: 'High Priority', attr: 'statecode', op: 'eq', value: 0 }]; })).status, 'fail', 'the auto condition is not matchable as a filter');+ assert.strictEqual((await gradeViewFilter(null, (ev) => { delete ev.expect.viewFilters; })).status, 'fail', 'no independent expectation grades nothing');+});++test('view-filter grading: a declared view is graded as the declared compiler builds it, so a filter on a joined table is not one on the view\'s own table', async () => {+ const join = (v) => { v.reconcile = 'declared'; v.linkEntities = [{ name: 'contact', from: 'contactid', to: 'ownerid', alias: 'c' }]; };+ assert.strictEqual((await gradeViewFilter((v) => { v.reconcile = 'declared'; })).status, 'pass', 'declared, no join');+ assert.strictEqual((await gradeViewFilter((v) => { v.reconcile = 'declared'; v.filters[0].value = 'High'; })).status, 'pass', 'a choice label resolves to its value as the build resolves it');+ assert.strictEqual((await gradeViewFilter(join)).status, 'pass', 'a join the filter does not use leaves the filter on the view\'s own table');+ const scoped = await gradeViewFilter((v) => { join(v); v.filters[0].relatedEntity = 'c'; });+ assert.strictEqual(scoped.status, 'fail', 'the same condition scoped to the joined table constrains another table');+ assert.match(scoped.reason, /no condition cnt_priority eq 5/);+ assert.strictEqual((await gradeViewFilter((v) => { join(v); v.filters.push({ ...v.filters[0] }); v.filters[0].relatedEntity = 'c'; })).status, 'pass', 'an unscoped condition beside a scoped one still counts');+ assert.strictEqual((await gradeViewFilter((v) => { join(v); v.filters[0].relatedEntity = 'nope'; })).status, 'fail', 'a declared view that does not compile builds no filter');+});++test('a declared view with a malformed join collection is graded invalid by the validator, with every other grade kept, and never throws in the facts', async () => {+ const { gradeFixture } = require('../run-app-builder.js');+ const base = fixtureFor(11);+ const cases = [+ ['linkEntities is an object', (v) => { v.reconcile = 'declared'; v.linkEntities = {}; }, /views\[0\]\.linkEntities must be an array/],+ ['a join\'s filters is an object', (v) => { v.reconcile = 'declared'; v.linkEntities = [{ name: 'contact', from: 'contactid', to: 'ownerid', alias: 'c', filters: {} }]; }, /views\[0\]\.linkEntities\[0\]\.filters must be an array/],+ ];+ for (const [name, mutate, diagnostic] of cases) {+ const spec = structuredClone(base.spec);+ mutate(spec.views.find((v) => v.name === 'High Priority'));+ const { results } = await gradeFixture({ ...base, spec }, evalsManifest.evals.find((e) => e.id === 11), evalsManifest);+ assert.ok(!results.some((r) => r.text === 'stage facts computed without error'), `${name}: the facts are computed`);+ assert.ok(results.length > 20, `${name}: the other assertions still run (${results.length})`);+ const gate = results.find((r) => r.text === 'author: validateAppSpec(plan profile) passes with no errors');+ assert.strictEqual(gate.result.status, 'fail', name);+ assert.match(gate.result.reason, diagnostic, `${name}: the validator's own diagnostic is the reason`);+ assert.strictEqual(results.find((r) => r.text === 'data: schema-facts provision exactly the expected tables').result.status, 'pass', `${name}: an unrelated grade is unchanged`);+ }+});++test('view grading by name and the other stage assertions are unchanged by the view-filter facts', async () => {+ const fixture = fixtureFor(11);+ const facts = await stageFacts(fixture.spec, { fixture });+ const ev = evalsManifest.evals.find((e) => e.id === 11);+ const named = 'ui: wire-facts build exactly the expected views and charts';+ assert.strictEqual(score(named, facts, fixture).status, 'pass');+ const other = structuredClone(fixture.spec);+ other.views[0].name = 'Urgent';+ assert.strictEqual(ASSERTIONS.get(named)({ facts: await stageFacts(other, { fixture }), spec: other, eval: ev }).status, 'fail', 'a renamed view still fails the name check');+ assert.deepStrictEqual(Object.keys(facts.ui.views[0]).sort(), ['columns', 'conditions', 'entity', 'name']);+});+const grade2210 = (id, mutate) => {const ev = evalsManifest.evals.find((e) => e.id === id);const spec = structuredClone(loadFixtures(path.join(__dirname, '..', 'fixtures')).find((f) => f.id === id).spec);@@ -1074,4 +1158,130 @@ test('stable-identity expectations pass on their fixture, a download prompt mustassert.strictEqual(teach(real.replace('does not merge', 'merges')), 'fail', 'the stop described as a merge');assert.strictEqual(teach(real.replace(/create-completion-required/g, 'a refusal')), 'fail', 'the stop not named');assert.strictEqual(teach(real.replace(/createIdentity/g, 'stableIds')), 'fail', 'no createIdentity guidance');+});++// Optional capabilities: the spec-level opt-in, in both directions, on every fixture. What the evals grade for the offer flow+// (#804) is this: a capability is in the spec only when the prompt asks for it, and one it asks for is authored. Whether the+// flow makes the offer needs a transcript of a conversation, which no offline fixture records (EVAL_GUIDE.md).+const OPTIONAL = 'author: an optional capability is in the spec only when the prompt asks for it, and each one it asks for is authored as expected';+const NO_LOGIC = 'author: a maker who declines business rules and process flows gets no rule and no flow of any kind';+function gradeOptional(id, mutate, mutateEval, text = OPTIONAL) {+ const fixture = fixtureFor(id);+ const ev = structuredClone(evalsManifest.evals.find((e) => e.id === id));+ const spec = structuredClone(fixture.spec);+ if (mutate) mutate(spec);+ if (mutateEval) mutateEval(ev);+ return ASSERTIONS.get(text)({ spec, eval: ev, facts: {} });+}+const reasonOf = (result) => result.reason || '';++test('the opt-in check is a common assertion, so every fixture is graded by it, and every shipped fixture passes', () => {+ assert.ok(evalsManifest.common_stage_assertions.includes(OPTIONAL));+ const fixtures = loadFixtures(path.join(__dirname, '..', 'fixtures'));+ assert.ok(fixtures.length >= 25);+ for (const f of fixtures) assert.deepStrictEqual(gradeOptional(f.id), { status: 'pass' }, `fixture ${f.id}`);+});++test('an optional capability nobody asked for fails on any fixture, an older one included', () => {+ const unasked = {+ 'an app theme': (s) => { s.app = { ...s.app, theme: { basePaletteColor: '#123456' } }; s.minimumPluginVersion = '2.21.0'; },+ 'an environment variable': (s) => { s.environmentVariables = [{ schemaName: 'new_Base', displayName: 'Base', type: 'string' }]; },+ 'a connection reference': (s) => { s.connectionReferences = [{ logicalName: 'new_sp', connectorId: 'shared_sharepointonline' }]; },+ 'a Custom API': (s) => { s.customApis = [{ uniqueName: 'new_Api' }]; },+ 'a duplicate-detection rule': (s) => { s.duplicateDetectionRules = [{ entity: 'new_customer' }]; },+ 'a solution version': (s) => { s.solution = { ...s.solution, version: '1.0.0.0' }; },+ 'a declared form': (s) => { s.forms = [...(s.forms || []), { entity: 'new_customer', formType: 'Main', name: 'Layout', reconcile: 'declared' }]; },+ 'a declared dashboard': (s) => { s.dashboards = [...(s.dashboards || []), { name: 'Board', key: 'board', reconcile: 'declared', tiles: [] }]; },+ 'a declared business rule': (s) => { s.businessRules = [...(s.businessRules || []), { entity: 'new_customer', name: 'Rule', key: 'rule', reconcile: 'declared', scope: 'Entity' }]; },+ 'a declared process flow': (s) => { s.businessProcessFlows = [...(s.businessProcessFlows || []), { entity: 'new_customer', name: 'Flow', reconcile: 'declared', stages: [] }]; },+ };+ const ordinary = [1, 2, 3, 4, 5, 6, 10, 11, 20];+ for (const id of ordinary) {+ for (const [name, mutate] of Object.entries(unasked)) {+ assert.strictEqual(gradeOptional(id, mutate).status, 'fail', `fixture ${id}: ${name}`);+ }+ }+ assert.match(reasonOf(gradeOptional(1, unasked['an app theme'])), /app\.theme is declared, but the prompt asks for no branding/);+ assert.match(reasonOf(gradeOptional(1, unasked['a declared business rule'])), /businessRules declared on \[new_customer\], but the prompt asks to keep no businessRules declared/);+});++test('a capability the prompt asks for must be authored: deleting it, or dropping its reconcile, fails on each positive fixture', () => {+ // Theme (19) and configuration (18).+ assert.strictEqual(gradeOptional(19, (s) => { delete s.app.theme; }).status, 'fail', 'a branding ask with no theme');+ for (const field of ['environmentVariables', 'connectionReferences', 'customApis', 'duplicateDetectionRules']) {+ assert.strictEqual(gradeOptional(18, (s) => { delete s[field]; }).status, 'fail', `18: ${field} deleted`);+ }+ assert.strictEqual(gradeOptional(18, (s) => { delete s.solution.version; }).status, 'fail', '18: the solution version deleted');+ // Declared forms (21), dashboards (22), rules (23), flows (24): graded by kind and table, nothing finer.+ const positives = [+ [21, 'forms', (x) => x.name === 'Site Layout'],+ [22, 'dashboards', (x) => x.name === 'Field Operations'],+ [23, 'businessRules', (x) => x.name === 'Close out a request'],+ [24, 'businessProcessFlows', (x) => x.name === 'Claim handling'],+ ];+ for (const [id, kind, isIt] of positives) {+ assert.strictEqual(gradeOptional(id, (s) => { s[kind] = s[kind].filter((x) => !isIt(x)); }).status, 'fail', `${id}: ${kind} entry deleted`);+ assert.strictEqual(gradeOptional(id, (s) => { delete s[kind].find(isIt).reconcile; }).status, 'fail', `${id}: reconcile removed`);+ assert.strictEqual(gradeOptional(id, (s) => { s[kind].find(isIt).reconcile = 'adopt'; }).status, 'fail', `${id}: reconcile is not "declared"`);+ assert.match(reasonOf(gradeOptional(id, (s) => { delete s[kind].find(isIt).reconcile; })), /missing \(deleted, or without reconcile "declared"\)|missing: \[/);+ // A name is the maker's to choose, whether or not the prompt gives one.+ assert.strictEqual(gradeOptional(id, (s) => { s[kind].find(isIt).name = 'Another name'; }).status, 'pass', `${id}: ${kind} renamed`);+ }+ assert.strictEqual(gradeOptional(23, (s) => { s.businessRules.pop(); }).status, 'fail', 'one of the two rules the prompt asks for is missing');+ // The table is graded: the artifact on another table is a different capability.+ assert.strictEqual(gradeOptional(21, (s) => { s.forms.find((x) => x.name === 'Site Layout').entity = 'cnt_issue'; }).status, 'fail', 'a form on another table');+ assert.strictEqual(gradeOptional(23, (s) => { s.businessRules.forEach((r) => { r.entity = 'cnt_other'; }); }).status, 'fail', 'rules on another table');+ assert.strictEqual(gradeOptional(24, (s) => { s.businessProcessFlows[0].entity = 'cnt_other'; }).status, 'fail', 'a flow on another table');+ // A kind the prompt did not ask for fails even on a positive fixture.+ assert.strictEqual(gradeOptional(23, (s) => { s.businessProcessFlows = [{ entity: 'cnt_request', name: 'Extra', reconcile: 'declared', stages: [] }]; }).status, 'fail', 'a flow nobody asked for beside the rules');+ assert.strictEqual(gradeOptional(21, (s) => { s.dashboards = [{ name: 'Board', key: 'board', reconcile: 'declared', tiles: [] }]; }).status, 'fail', 'a dashboard nobody asked for beside the form');+ // Shape and wording are not this check's business, and fixtures 22-24 have no shape assertion of their own yet: another stage+ // word, a reversed tile order, a rule scope swapped between two rules, or a changed tile kind still pass here.+ assert.strictEqual(gradeOptional(24, (s) => { const st = s.businessProcessFlows[0].stages; st[1].name = 'Appraisal'; st[2].name = 'Outcome'; }).status, 'pass', 'other stage labels');+ assert.strictEqual(gradeOptional(22, (s) => { s.dashboards[0].tiles.reverse(); }).status, 'pass', 'tiles in another order');+ assert.strictEqual(gradeOptional(23, (s) => { const [r1, r2] = s.businessRules; [r1.scope, r2.scope] = [r2.scope, r1.scope]; }).status, 'pass', 'swapped scopes');+ // The version floor still applies to a declared artifact.+ assert.strictEqual(gradeOptional(24, (s) => { s.minimumPluginVersion = '2.20.6'; }).status, 'fail'); assert.strictEqual(gradeOptional(24, (s) => { s.minimumPluginVersion = '2.20.6'; }).status, 'fail');+});++test('the expectation side is checked too: a declared kind it does not know fails, and an ask it does not state is not allowed', () => {+ assert.strictEqual(gradeOptional(21, null, (ev) => { ev.expect.declared.dashboard = []; }).status, 'fail', 'an unknown kind');+ assert.strictEqual(gradeOptional(21, null, (ev) => { delete ev.expect.declared; }).status, 'fail', 'a declared form the prompt never asked for');+ assert.strictEqual(gradeOptional(19, null, (ev) => { delete ev.expect.appTheme; }).status, 'fail', 'a theme with no branding ask');+ assert.strictEqual(gradeOptional(18, null, (ev) => { ev.expect.configuration.customApis = []; }).status, 'fail', 'a Custom API with no ask');+});++test('what must NOT change: plain forms, dashboards, rules and flows are not optional capabilities, and a capability needs no offer record', () => {+ // Not declared, so not the capability: ordinary authoring keeps passing.+ assert.strictEqual(gradeOptional(1, (s) => { s.businessRules = [...(s.businessRules || []), { entity: 'new_customer', name: 'Plain rule' }]; }).status, 'pass');+ assert.strictEqual(gradeOptional(1, (s) => { s.dashboards = [...(s.dashboards || []), { name: 'Plain board', tiles: [] }]; }).status, 'pass');+ assert.strictEqual(gradeOptional(1, (s) => { s.environmentVariables = []; s.customApis = []; }).status, 'pass', 'an empty list is no capability');+ // No fixture carries offer evidence and no assertion grades an offer: the evals grade the spec only.+ for (const f of loadFixtures(path.join(__dirname, '..', 'fixtures'))) assert.strictEqual(f.evidence.offers, undefined, `fixture ${f.id}`);+ assert.ok(![...ASSERTIONS.keys()].some((t) => /^offers:/.test(t)));+});++test('a maker who declines business rules and process flows gets none of ANY kind, graded independently of the declared-capability check', async () => {+ const { gradeFixture } = require('../run-app-builder.js');+ assert.ok(evalsManifest.evals.find((e) => e.id === 25).expectations.includes(NO_LOGIC));+ assert.deepStrictEqual(gradeOptional(25, null, null, NO_LOGIC), { status: 'pass' });+ const plainRule = (s) => { s.businessRules = [{ entity: 'cnt_part', name: 'Stock rule', conditions: [{ field: 'cnt_stock', operator: 'Equals', value: '0' }], actions: [{ type: 'SetBusinessRequired', field: 'cnt_price' }] }]; };+ const plainFlow = (s) => { s.businessProcessFlows = [{ entity: 'cnt_part', name: 'Stock flow', stages: [{ name: 'One', steps: [{ name: 'Price', field: 'cnt_price' }] }] }]; };+ for (const [name, mutate] of [['a plain business rule', plainRule], ['a plain process flow', plainFlow]]) {+ assert.strictEqual(gradeOptional(25, mutate, null, NO_LOGIC).status, 'fail', name);+ // The declared-capability check cannot see it (no reconcile), so this is not a duplicate of it.+ assert.strictEqual(gradeOptional(25, mutate).status, 'pass', `${name}: invisible to the declared check`);+ const base = fixtureFor(25);+ const spec = structuredClone(base.spec);+ mutate(spec);+ const { results } = await gradeFixture({ ...base, spec }, evalsManifest.evals.find((e) => e.id === 25), evalsManifest);+ assert.strictEqual(results.find((r) => r.text === NO_LOGIC).result.status, 'fail', `${name}: the runner reports it`);+ }+ // A declared one is caught by both.+ assert.strictEqual(gradeOptional(25, (s) => { plainRule(s); s.businessRules[0].reconcile = 'declared'; }).status, 'fail');+ // The check needs its expectation from the prompt: an eval that does not state it cannot use it.+ assert.strictEqual(gradeOptional(25, null, (ev) => { delete ev.expect.noBusinessLogic; }, NO_LOGIC).status, 'fail');+ // The same fixture still declines the theme and the configuration items through their own assertions.+ assert.deepStrictEqual(evalsManifest.evals.find((e) => e.id === 25).expect.configuration, {});+ assert.strictEqual(gradeOptional(25, (s) => { s.app.theme = { basePaletteColor: '#123456' }; s.minimumPluginVersion = '2.21.0'; }).status, 'fail');});\ No newline at end of filediff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex c5439e595..8b382e514 100644--- a/plugins/model-apps/.claude-plugin/plugin.json+++ b/plugins/model-apps/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.21.0",+ "version": "2.22.0","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.jsonindex c5439e595..8b382e514 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.21.0",+ "version": "2.22.0","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.mdindex 7a172fd5f..f83349ea7 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -153,7 +153,7 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo- **`scripts/lint-app-spec.js`** — the CLI surface for both gates, for a headless author or a CIjob (#560). Runs `migrateAppSpec` → `validateAppSpec` (what the build runs on load) → `lintAppSpec`(guardrails the builder does **not** run), and exits non-zero on errors (`--strict` also fails on- warnings). Prefer it over calling the library through `node -e`: linting the file **as written**+ warnings, including the one for an unknown key on a `views[]` entry or its filters). Prefer it over calling the library through `node -e`: linting the file **as written**rather than the migrated shape is what let a spec pass the lint and then fail the build (#545).`--profile` defaults to **`plan`**, not `deploy`, because the authoring flow runs this while pagesare still intents — a deploy default rejects a normal work-in-progress spec. `plan` relaxes only@@ -2901,6 +2901,16 @@ charts phases. A spec that uses none of them takes the legacy paths unchanged. Wform wire (`tests/helpers/managed-wire.js`) answers a version that moves with the saved layer, whichthe service does not do: a test through it proves the SDK's re-read and refusal path, and a test whosedouble answers a version conflict proves the build's handling of that refusal, never a service guard.+ **Caption diagnostic** (`lib/form-caption-diagnostics.js`): when an ADOPTED form's two layers differ,+ `readSystemFormLayers` (`lib/systemform-published.js`) also offers both form XMLs to `cellCaptionDifferences`,+ AFTER computing the two hashes and inside its own guard. A cell is compared only when its id, tab, section and+ direct controls match on both sides, and a language only when it has exactly one label on each side; anything+ ambiguous or unread answers nothing. A usable answer (at most 8 cell/language pairs, copied field by field) is+ appended to the unconfirmed-publication stop (`publishManagedScope`, `confirmUncertainPublication`) as cell ids+ and language codes, never caption text. It is a diagnostic, not a proof: it changes no hash, no decision and no+ store record, and a helper that throws, is missing or answers anything else leaves the stop exactly as before.+ It cannot tell an unpublished edit from the platform's read projection (the saved layer has no version), so the+ stop still needs the printed `publication-risk` approval. Created forms and dashboards get no diagnostic.**Verify and download** (`lib/declared-form-io.js`): verify reads each bound declared form fresh by itsrecorded id through the isolated reader (`readerFor(...).declaredForm`, never `readGroup`) and runs`verifyDeclaredForm` against the declaration and the store's recorded children (`managed-form` check);@@ -2911,9 +2921,30 @@ charts phases. A spec that uses none of them takes the legacy paths unchanged. Wone leaves the host out as unverified, and the oracle has no wildcard. A quick view's target is looked up byname (ambiguous → unverified). `download-model-app.js --include-managed --managed-manifest <store file>`(both or neither) restores each proved form with `hydrateDeclaredForm`, validating incrementally; a- pending, unreadable or invalid one is left out and named. A form with `events` is always invalid there:- the download writes only icon and logo web resources, so its handler library is undeclared and the form- is named in `managedForms.stale`; forms without a handler are restored. The restored form is the group's+ pending, unreadable or invalid one is left out and named. A form with `events` brings each handler library+ the spec does not declare (`librariesNotIn`), read by name through the download's SDK (`libraryEntry`, cached+ per run) and added as `{ name, displayName?, type: 'js', contentBase64, external: true }` together with the+ form, all or none (`managedForms.libraries: [{ name, forms }]`, only when one was added, and a NOTE line).+ The gates: exactly one row on a complete answer (a lookup the server says continues is refused), `ismanaged === false` (absent is unknown), `webresourcetype === 3`, content,+ and a name under the publisher prefix `runDownload` answers as `publisher: { prefix, resolved }` (internal,+ not printed; `resolved` false refuses). `external` is what keeps a rebuild from writing or comparing the+ library's content (`sdk-build.js` web-resources reuse) and a teardown from deleting it. A refused library+ leaves the form in `managedForms.stale` ("handler library '<name>' was not downloaded: <why>"). A form left+ out only for its+ handler libraries (the spec validates with the form and a stub `js` entry per missing library) is written+ to a fragments file (`lib/managed-fragments.js`, `managedFragments: { file, keys }` in the result), with+ `needs: [{ webResource }]` and a `paste` entry; a flow left out only for its personas likewise (a stub+ persona per name). The stubs are never written. Each download that has items writes ONE new file,+ `<out>/.maker-workspace/managed-fragments-<UTC yyyymmddThhmmssZ>-<6 hex>.json`, made by an exclusive create+ (`wx`) under a name nothing holds; it never replaces, renames over, removes or links any file, so a taken+ name (a file, a folder, a link: Windows `CREATE_NEW` follows a dangling link, so an `lstat` passes over any+ entry first and an inode check after the open refuses a link that raced in, before a byte is written) is kept+ and another name tried. Files from earlier downloads stay. With nothing due nothing is written or removed. A+ link, junction or file at `.maker-workspace`, or no name free after 8 tries, is `managed-fragments-unwritable`.+ It is settled after the restore and the validation and before anything is published: `main` passes+ `runDownload` `stagePages`, which writes the page tree to a hidden staging folder inside `<out>`, reads it+ back and answers `stagedPages` (`check`, `publish`); the tree, the spec and the baseline are written only+ after the fragments file, so a failure there leaves every output as it was. The restored form is the group's`consumerState.declaration` (`DECLARATION_KEYS`, `autoSubgrids` included). A plain download reads no form.The download writes no store and transfers no binding authority: the first binding of a form from thedownloaded folder needs `adopt:form:<key>`, and an identical unbound no-op may leave it unbound.@@ -3007,6 +3038,45 @@ charts phases. A spec that uses none of them takes the legacy paths unchanged. Wapplies unchanged: a GET answers the PUBLISHED row's ETag and `If-Match` does not protect the savedlayer. The SDK re-reads the saved layer just before its PATCH; an edit landing between that read andthe write cannot be detected, and nothing here claims a stale saved-layer write is rejected.+ **An acknowledged create** (`lib/create-request-body.js`, `lib/dashboard-recovery-workspace.js`): when the+ run's send observer is installed and the barrier gates the transport, a new dashboard's create is receipted+ before it is sent; without them no receipt is made and recovery stays manual as before. `intendedDashboard`+ keeps the complete build-owned **create draft** (the reseeded bag, tiles and captions). After `applyDashboard`+ assembles the local copy, the copy must equal that draft (whole-artifact canonical hash), else+ `create-local-draft-changed` and nothing is sent. `expectedCreateBody` serializes the draft through a fresh+ throwaway SDK (`workspace.writeArtifact`, then a dry `pushArtifact` whose sink never transmits); real-bundle+ tests pin that this body equals the wire POST for one and two languages. The store records the receipt on the+ attempt (`noteDashboardCreateDraft`: root, send epoch, draft and body SHA-256) before the POST. The observer's+ `withDashboardCreateReceipt` scope wraps only the create `pushChecked`; for the exact `systemforms` POST of+ that root and body it persists a dispatch token before the bytes leave (`noteDashboardCreateDispatch`) and,+ for a 200/201/204 with no error and no contradicting id, the acknowledgement before the SDK sees the answer+ (`noteDashboardCreateAnswer`). A store failure keeps its own code and is thrown after `pushChecked` returns: a+ failed dispatch record answers a synthetic, non-retried 409 and sends nothing; a failed answer record returns+ the real response, so the SDK never replays the POST, and the receipt stays unacknowledged. A receipt proves+ the row was created, not its content or its publication: fresh proof, `noteSaved`, consent, membership and the+ whole-group commit still run. The commit turns an acknowledged receipt into `localCreateDraft` on the created+ root (minted by the store only, kept for later generations of that root, dropped by a retirement; a caller+ cannot add or change one). An epoch advance keeps the receipt's root and hashes and clears its dispatch and+ acknowledgement; an acknowledged receipt never takes the proven-unsent `continue` claim. The empty seed cell+ gets a fixed id (UUIDv5 under the section's catalog id, as `settleControlIds` derives BPF control ids):+ the SDK's `createDefault` mints a random one on every call, and the draft hash must not change between runs.+ The SDK copy of an acknowledged create is dirty (the SDK never recorded the answer). Preflight lets it through+ only when it is the pending root with an acknowledged receipt, or the committed created root with+ `localCreateDraft`, and its complete local artifact hashes to the recorded `draftSha256`; every other id keeps+ the unsent-edit check, and another root, an unreadable copy or any changed value is+ `workspace-copy-unsent-edits`. The build never refreshes or deletes that copy: `withDashboardWorkspaceScope`+ (around the dashboard settle and publish in `sdk-build.js`) moves the dashboard's reads and writes to an+ isolated SDK in a throwaway folder (same client, URL, language and solution header), checks the source copy+ still hashes to the draft before membership and before the commit, and leaves it byte for byte as it was. So+ the recovering build sends no second POST and needs no `adopt:` approval: it proves the row, commits it as+ created and publishes it. A receipted create read absent in both layers (two `0x80040217` 404s) is sent again+ under the same root only through the fenced branch of `recoverManagedAttempt` (`observeDashboardCreateResume`,+ then `markSending` `claim: "resume"` with that observation; a stale observation refuses). What stays manual:+ a stop inside the raw response handler before the acknowledgement is written (the receipt is not acknowledged:+ the old `create-completion-required` and adoption path), a retained copy changed since the send, and a run+ without the observer or gated transport. The pending declaration is kept as before. Tests: "dashboard create+ receipt" and "created dashboard root" in `tests/managed-bindings.test.js`; the receipt and recovery tests in+ `tests/dashboard-settlement-real-bundle.test.js`.**Verify and download** (`lib/declared-dashboard-io.js`): verify reads each bound declared dashboard freshby its recorded id through the isolated reader (`readerFor(...).declaredDashboard`, which answers theartifact and the reading SDK's language) and runs `verifyDeclaredDashboard` (`managed-dashboard` check):@@ -3139,10 +3209,25 @@ charts phases. A spec that uses none of them takes the legacy paths unchanged. Wattempt, below, included). A declaration that changesnothing of the workflow but differs from the group's `originalDeclaration` (its `securityRoles`, say) is theplan's `declaration` mode: no workflow request, and a commit that records it, so the store keeps the current- intent; an identical one is a no-op with no store write. Nothing is published. The managed download still- leaves a flow with `securityRoles` out (`personasNotIn`): a download writes no `personas[]`, and a persona- owns its role and is converged onto exactly what it declares, so one is never reconstructed from the- environment, and the flow is never restored without its roles; the stale reason names the missing personas.+ intent; an identical one is a no-op with no store write. Nothing is published. The managed download restores+ a flow with `securityRoles` only when every persona it names is in the downloaded spec or is PROVED from its+ role (`lib/persona-restore.js` `createPersonaProver`, read-only, memoised per run). A persona owns its role+ and is converged onto exactly what it declares (ReplacePrivilegesRole), so a persona is written only when a+ rebuild provably leaves the role as it is, all gates fail closed: exactly one role of the name in the ROOT+ business unit (`resolveRoleBusinessUnit` + `roleBuClause`; a lookup cut short — `hasMore` — refuses), carrying `SDK_ROLE_MARKER` with+ `ismanaged === false` (any unmarked or managed row of the name refuses, as the SDK's own lookup does); a+ member of the app's solution (component type 20); `appAccess` from the app association+ (`appRoleIdsComplete`: every page through `collectionRows`, each row naming a role by GUID; a malformed,+ refused or incomplete answer refuses, because a role missing from it would be written as `appAccess: false`+ and a build would dissociate it — `appRoleIdsFor` stays verify's lenient reader); every held privilege (`roleprivileges`, paged, `depthFromMask`) mapped to a table and an+ access through one `EntityDefinitions?$select=LogicalName,Privileges` read (a privilege no table carries is+ refused); the candidate (one job, `JOB_NAME`, grouped by table and scope) put through+ `personaRoleSpecFor` and `compileRolePrivileges` (`lib/role-privileges.js`, the SDK's compile) equals the+ held set both ways; and the role already holds `BPF_ROLE_ACCESS` at Global on the flow's backing table+ (`flowGrantsMissing`, also checked for a persona written for an earlier flow). A persona that fails leaves+ the flow out, its reason naming each persona and why; the flow goes to the fragments file+ (`noteBpfFragment`) when it validates with a stub persona per missing name. A written persona is in+ `managedBpfs.personas: [{ name, flows }]` and a NOTE says a build owns its role from then on.**Verify and download** (`lib/declared-bpf-io.js`): verify reads each bound declared flow fresh by itsrecorded id through the isolated reader (`readerFor(...).declaredBpf`) and runs `verifyDeclaredBpf`(`managed-bpf` check): the helper's one read-only `projectBpf`, certified only when it is a shape the@@ -3217,7 +3302,9 @@ made before any number of retirements is refused. Adoption of a different id isstill wins over the catalog id, adoption by name or by the `adopt:` approval is unchanged, and a lostcreate keeps the incarnation in its pending attempt; in a retained SDK workspace the dirty-copy fencestops with `create-completion-required` and sends nothing until the owned local copy is discarded, after-which the create resumes (or, when it landed, is adopted with approval) under the same id. A direct store+which the create resumes (or, when it landed, is adopted with approval) under the same id. A dashboard+whose create has an acknowledged receipt and an exactly matching retained draft is the one exception: it is+recovered without approval through an isolated workspace (see **Dashboard** above). A direct storecaller that passes no token is fenced by its handle's read and by key only. Views and charts are neverretired, so they have no incarnation. Tests: `tests/managed-bindings.test.js` ("incarnation"),`tests/creates-composite-catalog.test.js` ("incarnations"), and "declared again after" / "after@@ -3230,7 +3317,8 @@ and sends the same requests as before). For a declared view or chart, `lib/creatthe id (`lib/creates-identity.js`), `lib/creates-port.js` creates or finds the row at that id, and`lib/managed-bindings.js` records the binding in the workspace (`managed-bindings.<hash>.json`, openedby `openBuildBindingGroups` for an apply with an app, a solution and an https environment). Every other-kind keeps its current ids. A local copy at the id with an unsent edit, or a local create never+kind keeps its current ids (a declared dashboard already has its catalog id; its create receipt adds no+`createIdentity` value and does not make an id into consent). A local copy at the id with an unsent edit, or a local create neveracknowledged, is refused before any read-back, reapply or send (`create-completion-required`, via`lib/creates-local.js`); there is no `overwrite:` approval for it, and no exception for the build's owndraft: a diff cannot tell it from one a maker edited since (a name or description outside thediff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex 78582c75e..fd3ec7657 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -5,6 +5,23 @@ All notable changes to the **model-apps** plugin.Entries are deliberately short: what changed and why it matters to you. The reasoning,evidence and trade-offs behind a change live in its PR, in `docs/`, or in the linked issue.+## [2.22.0]++- **Teardown:** a table's only Main form, refused with `0x8004F661`, settles with its table: one run removes the solution (#806).+- **First builds:** reads about a just-created table retry the metadata-cache lag in place within the budget; a failed form lookup never creates a duplicate; exhausted retries quote the service (#796).+- **Localized tables:** preflights skip the broad label-bearing read, stopping before writes if existence stays unknown (#796); unprovisioned label languages halt before the publisher or solution exist (#809).+- **Tables found after "already exists"** reuse existing columns, applying declared column security and authorized Date and Time repairs at once (#796).+- **Validation:** unknown `views[]` and filter keys warn with the likely key and fail `--strict` lint; an ignored view `type` stays silent (#799).+- **Managed downloads:** a form's handler library returns as an external resource (never updated; teardown keeps it); a flow's personas return when proved from roles that later builds own (#800).+- **Managed-download output** is replaced only after restoration, validation and fragments succeed; items blocked only by a missing library or persona go to a new `.maker-workspace/managed-fragments-*.json` (#800).+- **Declared dashboards:** a durably acknowledged, still-present create is recovered after a stop without a second create or adoption when the retained draft is unchanged; creates send a fixed seed-cell id (#798).+- **Adopted forms:** publication stops can name differing caption cells and language codes (#797).+- **Authoring:** `/app-builder` offers optional capabilities, never by default; evals grade view filters and opt-in (#802, #804).++### Limits++- Adopted-form caption differences still need `publication-risk` approval (#797). Stops before a dashboard acknowledgement is recorded stay manual; older versions refuse these bindings: never reset or edit the store (#798).+- Page-tree replacement is non-atomic (#814). Retry-stable configuration rows, owed rule publication and keyed command bars come later (#807, #808, #812).## [2.21.0]- **`reconcile: "declared"`**: views/charts/web resources/forms/Global Standard dashboards; rules/flows create/adopt-only; adoption: `adopt:<family>:<key>`. Forms/dashboards/rules/flows `--verify`/download (`--include-managed --managed-manifest <store>`); removed, Maker-deleted roots can retire; re-declarations get fresh ids. New-app `createIdentity: "stable-v1"`: retry-stable view/chart ids. `quickFind.findColumns`, `app.mainFormsOnUpdate: "exact"`, `app.pinDeclaredArtifacts` (lost pin-add recovery).diff --git a/plugins/model-apps/references/app-spec-schema-advanced.md b/plugins/model-apps/references/app-spec-schema-advanced.mdindex 46d4f9fd4..a93513424 100644--- a/plugins/model-apps/references/app-spec-schema-advanced.md+++ b/plugins/model-apps/references/app-spec-schema-advanced.md@@ -707,7 +707,11 @@ saved layer and another way in the published layer (seen on an adopted form whosbase language did). No read can then confirm a publish of that form's table: the stop says that the savedlayer is still the one the publish shipped, yet the published layer reads differently. Compare what ispublished with the spec in Maker; if it matches, pass the `publication-risk` key the build prints. A later-publish of that table can stop the same way, and each needs its own key.+publish of that table can stop the same way, and each needs its own key. For a form the build adopted, the+stop can also name the cells and languages whose caption reads differently in the two layers (for example+"Caption difference at cell <id> (language 1033)"), never the caption text. Start the comparison in Maker+there. This does not show whether the difference is an unpublished edit or how the platform reads the layer,+so the stop and its key stay the same. A form the build created and a dashboard get no such list.**How a publish is confirmed.** After a declared form's table or a declared dashboard is published, thebuild reads the published layer and compares it with what it saved. The platform changes some captions by@@ -809,13 +813,34 @@ are only added.build's `.maker-workspace` for that environment and app. Each form the store proves comes back with`reconcile: "declared"` and as it was declared (`autoSubgrids` and stated `false` flags included); a formthat is pending, gone or not valid is left out and named. A declared form with an event handler- (`events`) is not valid in the downloaded spec, because a download brings back only icon and logo web- resources, not the handler's library: it is left out and named in `managedForms.stale` ("onload handler- references undeclared web resource"), while the forms without a handler are restored. To keep it, add- the library to `webResources[]` and the form's declaration to `forms[]` by hand. The download transfers no binding: the+ (`events`) comes back with each handler library the spec does not declare, added to `webResources[]` as+ `external: true` and named in `managedForms.libraries` (`[{ name, forms }]`) and in a note. A library is+ downloaded only when it is this app's own: exactly one web resource of that name (on a lookup that read+ every row; one cut short proves nothing), unmanaged, a script,+ with content, and named under the solution publisher's prefix, read and verified by the download. A+ rebuild reuses an `external` library where it exists without writing or comparing its content, creates+ it from the downloaded content where it is missing, and a teardown never deletes it. When a library+ fails any of those checks the form is left out and named in `managedForms.stale` ("handler library+ '<name>' was not downloaded: <why>"), and its declaration is written ready to paste in the build+ folder's `.maker-workspace` (see below), with the library it needs: add both to+ the spec. The download transfers no binding: thedownloaded folder has no store, so the first build that binds a form there needs`--authorize "adopt:form:<key>"`. A rebuild that finds the form already as declared writes nothing andmay leave it unbound.+- **The fragments file.** A managed download writes each declared form or process flow it proved but left+ out only for what it could not bring (a handler library, a persona) to+ a new file, `<out>/.maker-workspace/managed-fragments-<UTC time>-<random>.json`, and names that file in a+ warning and in the result+ (`managedFragments: { file, keys }`). Each item has the store `key`, the `reason` it was left out, what it+ `needs` (`{ "webResource": "<name>" }` or `{ "persona": "<name>" }`) and a `paste` object+ (`{ "forms": [ ... ] }` or `{ "businessProcessFlows": [ ... ] }`): add the entry to the same array in+ `app-spec.json` with what it needs, from the spec it was built from. An item left out for anything else+ (pending, changed, not valid) is not written there, because nothing proved it. The download only ever+ creates a file under a name nothing holds: it never replaces, moves or removes a file in `.maker-workspace`,+ so files from earlier downloads (and any of the maker's) stay as they are; delete old ones when you no longer+ need them. With nothing left out it writes no file. When `.maker-workspace` is a link, a junction or a file,+ or the file cannot be written, the download stops (`code: "managed-fragments-unwritable"`) before it writes+ anything else: the pages, the spec and the baseline are written only after this file.- **A removed form that was deleted.** When the spec no longer declares a form and the form was deleted inthe environment, the next build reads it by its id in both its saved and its published layer. When bothsay it does not exist, the build stops managing it, including a publish of its table it still owed: it@@ -875,21 +900,44 @@ existing one is reused and its tiles are never edited.new tile that cannot be added without moving rows the dashboard already has, a part changed elsewheresince the last build, and a dashboard of the same name that an earlier build created and did notfinish: that one is not taken over and not deleted. The dashboard is left as it is and the stop names- the cause.+ the cause. A new dashboard is also not sent when the local copy the build assembled is not exactly the+ draft it planned (`create-local-draft-changed`).+- **A create whose answer was lost.** Before it sends a new dashboard, the build writes a receipt for it in+ the binding store (its id, and a hash of the draft and of the exact request), and it writes the+ acknowledgement there when the service answers that the dashboard was created, before anything else+ runs. When the build stops after that (a crash, a lost connection, a failed later step), the next build+ recovers it by itself: it does not send the create again, needs no `adopt:` approval, reads the+ dashboard fresh to prove what it holds, binds it as created and publishes it. It does this only when the+ local copy the SDK kept is still exactly the draft the receipt names. It does not refresh or delete that+ copy: it works in a separate throwaway folder, and leaves the copy as it was. These cases still stop and+ need you:+ - The build stopped after the dashboard was sent but before the acknowledgement was written (or that+ write failed). The stop names the cause; this is the earlier behavior. Settle it as described for a+ lost create under `createIdentity` (**Local copy**): keep the declaration as it was, discard only the+ local copy, and build again with `--authorize adopt:dashboard:<key>` if it asks for it.+ - The local copy was changed since the send: the build stops with `workspace-copy-unsent-edits` and keeps+ it. Keep the change you want apart, discard only the local copy, build again, then put your change into+ the spec.+ - A dashboard acknowledged and then deleted by hand is created again under the same id only when a fresh+ read of both the saved and the published dashboard answers that it does not exist.- **Approvals.** The key is `dashboard:<key>`. A dashboard that already exists and that this build didnot create is bound only with `--authorize adopt:dashboard:<key>`; the first binding needs it, laterbuilds do not. `--authorize overwrite:dashboard:<key>` approves replacing a description changedelsewhere, and `overwrite:dashboard:<key>/<tile>` one tile changed elsewhere. A local copy that differs- from the server's stops the build (`workspace-copy-unsent-edits`).+ from the server's stops the build (`workspace-copy-unsent-edits`), except the exact copy of an+ acknowledged create (see **A create whose answer was lost**), which needs no approval.- **Publishing.** The dashboards step publishes the dashboard by itself, once, after its write, and onlywhen the write is proved, with or without `--publish` (with it, the app's publish later in the build canpublish it again). A dashboard this build cannot finish is not published, not even by the app's publish: an- app that would hold it is not written in that run.+ app that would hold it is not written in that run. A recovered create is published by the build that+ recovers it.- **Concurrent edits.** Dataverse does not version a dashboard's saved layer: a dashboard is a form row,and a plain read answers the published row's version, so a conditional write cannot reject a staleedit of it. The build re-reads the saved dashboard just before it writes and stops when it changedsince the build read it. An edit made in Maker in the instant between that check and the write cannot- be detected: do not edit a declared dashboard while a build runs.+ be detected: do not edit a declared dashboard while a build runs. Do not edit the local copy of a new+ dashboard while its build runs, or before the next build after a stop: a changed copy is never recovered+ over.- **Verify.** `--verify` reads each bound declared dashboard again by its id and holds it to what its lastbuild proved: the managed tiles (each exactly once, with the target, name and size the build wrote), thedescription, and everything the spec does not declare (other tiles, tabs, sections and a tile's other@@ -909,7 +957,13 @@ existing one is reused and its tiles are never edited.attempt, then by its `dashboardId`, and only then by its name. A `dashboardId` that is not the bounddashboard stops the build. `--verify` uses the same bound dashboard for every dashboard check, the sitemap's included. Before its first binding, `--verify` holds a declared dashboard to its `dashboardId`: if- that id names no dashboard, the check fails, even when another dashboard has the same name.+ that id names no dashboard, the check fails, even when another dashboard has the same name. A new+ dashboard's id stays the same for the spec, and a recovered create keeps it.+- **The binding store.** The receipt and its acknowledgement are new, optional fields in the binding store+ file; a store without them reads as before, and opening a store does not rewrite it. An older plugin+ refuses the dashboard whose binding holds them (`managed-binding-group-invalid`): build with this version+ or later. Do not reset, delete or edit the file to let an older plugin read it, and never put back an+ older copy.- **A removed declaration.** When the spec no longer declares a dashboard whose last change is notsettled, the build reads it before it builds any other dashboard:- A publish that is not confirmed is confirmed when a fresh read proves it live. It is never published@@ -1060,10 +1114,13 @@ Requires `minimumPluginVersion: "2.21.0"`. A flow without `reconcile` builds exa- **The backing table.** `securityRoles` are granted on the table name Dataverse stored for the flow,as the build read it, never on a name derived from the display name. A change of a managed flow's`securityRoles` alone (or of any setting the flow already holds) sends no workflow write; the build- records the flow's new declaration. A managed download does not restore a flow with `securityRoles`:- a download writes no `personas[]` (a persona's role is converged onto exactly what it declares, so one- is never guessed from the environment), and the flow is never restored without its roles. It is left- out with a warning naming the personas; copy the flow and those personas from the spec it was built from.+ records the flow's new declaration. A managed download restores a flow with `securityRoles` only with+ its roles. A persona the downloaded spec lacks is written into `personas[]` from its role only when a+ rebuild provably leaves that role exactly as it is (a persona's role is converged onto exactly what it+ declares, so one is never guessed): see "A persona written by a managed download" under `personas[]`+ in app-spec-schema.md. Otherwise the flow is left out with a warning naming each persona and why, and+ its declaration is written ready to paste in a new `.maker-workspace/managed-fragments-*.json` file (see the+ declared forms' Download note); copy those personas from the spec it was built from.- **Removing one.** A declared flow taken out of the spec leaves management and is kept. When a changean earlier build sent to it is still waiting to be proved, the build ends incomplete(`managed-not-settled`) and does not touch that flow: put its entry back and build again. Until then@@ -1102,6 +1159,8 @@ downloaded spec. The only value is `"stable-v1"`; any other value is a validatio"views": [{ "entity": "new_ticket", "name": "Open Tickets", "reconcile": "declared", "columns": ["new_name"] }] }```+- **Dashboards.** A declared dashboard already has an id fixed by the spec, without this field; there is+ no dashboard value for `createIdentity`. A fixed id finds a row, but is never an approval to bind it.- **What gets a stable id.** A declared view or chart (`reconcile: "declared"`) is created with an idthe spec fixes (from the solution, the table and the name). A build that lost the answer to itscreate, run again from the same or a fresh workspace, finds the row at that id and binds it insteaddiff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.mdindex 906e82e44..5f56ddb87 100644--- a/plugins/model-apps/references/app-spec-schema.md+++ b/plugins/model-apps/references/app-spec-schema.md@@ -375,6 +375,7 @@ An `entities[].localizedLabels` key is therefore **not** a supported shape.- Labels for all languages are written in **one** create call. That matters: a later single-language`PUT` can overwrite the base label even with merge semantics.- **Every LCID you name must be provisioned in the organization, and the build halts if one is not.**+ It halts before it writes anything: the publisher and the solution are not created either.This is the guard the feature depends on, not a nicety. Live-measured against a 1033-only org:`createTable` carrying `{ "1033": …, "3082": … }` returns **success** and stores **only** the 1033label — Dataverse does not warn, error, or report the drop anywhere. Without the halt you would get@@ -962,6 +963,13 @@ why they need naming here at all.build then failed at the platform, mid-run, and left behind a view row that could not be read ordeleted, so every later build failed the same way. It is now rejected upfront, naming the view and the offending entry.+- **A view takes only these keys:** `entity`, `name`, `description`, `columns`, `sort`, `filters`, `activeOnly`, and — on a view+ with `"reconcile": "declared"` — `key`, `viewId`, `linkEntities`. A filter item takes `attr`, `op`, `value`, `values` and+ `relatedEntity`. Any other key is **ignored by the build**, so validation warns about it and names the key it most likely meant+ (`filter` → `filters`, `column` → `attr`, `operator` → `op`); a view written with `filter` would otherwise be built without its+ filter. A view has no `type` (it is always a public view of its table, so leave it out); a `type` an older doc showed is still+ accepted without a warning. These are warnings, never errors — but `lint-app-spec.js --strict` fails on them, so a view with a+ misspelled key stops a `--strict` pipeline instead of building without its filter.- `activeOnly` (default `true`) adds `statecode eq 0`. `filters[]` add conditions: `op` is anyFetchXML operator — `eq`/`ne`/`lt`/`le`/`gt`/`ge`/`like`, no-value ops (`eq-userid`, `null`,`not-null`, `this-week`/`this-month`/`today`/…), and multi-value `in`/`not-in` (use `values[]`).@@ -2269,7 +2277,7 @@ Administrator role only, so without a persona role users who have no maker-level`personas[]` produces a working access model so the app opens for real users.An app that **already exists** keeps the roles associated with it: a spec with no `personas[]` leaves-them as they are, which is how an extension of such an app is written (a download carries none). Do+them as they are, which is how an extension of such an app is written (a plain download carries none). Donot list an existing role as a persona to silence the lint — a persona's role is converged to exactlythe privileges declared, and a role the build did not author is refused. Give an existing role accessto a table the spec adds with `roleGrants[]` (below). Opening the app and using a table are two@@ -2285,6 +2293,21 @@ privileges from a job's text. It **unions** every job's declared access into the(max scope wins per entity+access) and applies it with replace semantics (a rebuild that drops aprivilege removes it — the role converges to the spec).+**A persona written by a managed download.** A download with `--include-managed --managed-manifest+<store file>` that restores a declared business process flow whose `securityRoles` name a persona the+downloaded spec lacks writes that persona from its role, but only when a rebuild provably leaves the+role exactly as it is: one role of that name in the root business unit, made by a build and unmanaged,+in the app's solution, holding only table privileges that compile back to exactly what it holds, the+flow's grants included. The persona has one job, `Privileges read from the environment`, and+`appAccess: false` when the app is not associated with the role — read from every page of the app's+role associations; an association answer that is incomplete, malformed or refused proves nothing, so+no persona is written (a role it missed would otherwise be written as not associated, and a build+would remove its access to the app). A role lookup the server cuts short proves nothing either. From then on the spec **owns** that+role like any other persona: a privilege someone adds to the role outside the spec is removed by the+next build, and the download says so in a `NOTE`. When any of this cannot be proved, no persona is+written and the flow is left out instead, with the reason (see the business process flows' notes in+`app-spec-schema-advanced.md`).+```jsonc"personas": [{diff --git a/plugins/model-apps/references/authoring-flow.md b/plugins/model-apps/references/authoring-flow.mdindex ec611b827..44a1b3ca0 100644--- a/plugins/model-apps/references/authoring-flow.md+++ b/plugins/model-apps/references/authoring-flow.md@@ -323,6 +323,28 @@ That mapping is what the design document renders as a traceability table, and anflagged by the lint gate — so a job with no surface is a **visible** design gap rather than asilent one.+**Offer each optional capability that applies — once, as a question, never as a default.** Ask even when+the maker has not mentioned it (they may not know it exists), and skip an offer only for a capability the+maker already asked for: an explicit request counts as acceptance. Each one stays off unless the maker says+yes or asks for it; a "no" or silence adds nothing to the spec:++- **Branding** — for every new app, ask whether it should be branded (brand colours, a header colour, a+ logo). If yes, add `app.theme` — Preview, published with the app, and an app publication publishes every+ pending change of the app.+- **Outside services and per-environment values** — when the app calls an outside service or a value+ differs per environment (a base URL, a key, a connector, an action a page calls), offer configuration+ items: environment variables and connection references; the values stay out of the spec.+- **Duplicate records** — when the jobs identify duplicate records (the same customer or contact entered+ twice, one record per email address), offer a duplicate-detection rule on that table, even when the app+ uses no outside service.+- **A reusable server-side operation** — when the app needs an operation that several surfaces, flows or+ pages call, or that must run on the server (a calculation, a multi-step change), offer a Custom API, even+ when nothing outside Dataverse is involved.+- **Rules and processes** — when the jobs include a validation or a guided process (a required field once a+ record closes, stages a record moves through), offer a declared business rule or business process flow:+ the build manages the whole rule or flow, creates it or adopts one that exists, and never edits one in+ place; binding an existing one needs an `--authorize adopt:` approval.+### Level (a) — Data modelPropose the `entities` block (including `columns` and `primaryAttribute`) and@@ -433,6 +455,13 @@ data alongside the forms they reference). **This level is design-only: do notauthor page `.tsx` here** — propose page intents and defer code generation toPhase 1.5.+**Offer declared layouts, once, as a question — never as a default.** Whenever you propose forms or+dashboards, ask whether the maker wants the layout of any of them to stay as the spec says on every+rebuild; if yes, write `reconcile: "declared"` on that one form or Global Standard dashboard. The parts the+spec does not declare stay the maker's, and binding one that already exists needs an `--authorize adopt:`+approval. Without a yes and without an explicit request, write nothing declared; forms stay+`layout: "auto"`. A maker who already asked for a fixed layout is not asked again: their request is the yes.+#### FormsPropose one `main` form per entity. Default `"layout": "auto"`. For any entity@@ -908,7 +937,7 @@ The spec shape follows `plugins/model-apps/samples/app-spec.support-desk.json`:"entities": [ { "schemaName", "displayName", "pluralName", "primaryAttribute", "columns" } ],"relationships": [ { "type", "referenced", "referencing", "lookup" } ],"forms": [ { "entity", "type", "name", "layout", "subgrids?" } ],- "views": [ { "entity", "type", "name", "columns", "sort", "activeOnly" } ],+ "views": [ { "entity", "name", "columns", "sort", "activeOnly" } ],"charts": [ { "entity", "name", "groupBy", "measure", "chartType" } ],"pages": [ { "key", "name", "purpose", "dataSources", "source": { "kind": "tsx", "codeFile": "..." } } ],"design?": { "accent", "density", "cornerRadius", "darkMode", "layout" },diff --git a/plugins/model-apps/samples/app-spec.project-tracker.json b/plugins/model-apps/samples/app-spec.project-tracker.jsonindex c8767ce4e..86f8ea694 100644--- a/plugins/model-apps/samples/app-spec.project-tracker.json+++ b/plugins/model-apps/samples/app-spec.project-tracker.json@@ -27,7 +27,6 @@"views": [{"entity": "new_project",- "type": "main","name": "Active Projects","columns": ["new_name", "new_budget", "new_status"],"sort": [{ "attr": "new_name", "dir": "asc" }],diff --git a/plugins/model-apps/samples/app-spec.support-desk.json b/plugins/model-apps/samples/app-spec.support-desk.jsonindex 1f6809e7e..e58fad07e 100644--- a/plugins/model-apps/samples/app-spec.support-desk.json+++ b/plugins/model-apps/samples/app-spec.support-desk.json@@ -72,7 +72,6 @@"views": [{"entity": "new_customer",- "type": "main","name": "Active Customers","columns": ["new_name", "new_segment", "new_accountmanager"],"sort": [{ "attr": "new_name", "dir": "asc" }],@@ -80,7 +79,6 @@},{"entity": "new_ticket",- "type": "main","name": "Active Tickets","columns": ["new_name", "new_priority", "new_status", "new_duedate"],"sort": [{ "attr": "new_duedate", "dir": "asc" }],@@ -88,7 +86,6 @@},{"entity": "new_comment",- "type": "main","name": "Active Comments","columns": ["new_name", "new_author", "new_postedon"],"sort": [{ "attr": "new_postedon", "dir": "desc" }],diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.jsindex c66edc2db..b3b4b7a41 100644--- a/plugins/model-apps/scripts/build-model-app.js+++ b/plugins/model-apps/scripts/build-model-app.js@@ -21,7 +21,7 @@ const { specTables } = require('./lib/table-publish.js');const { stagePhasesOrResolve, PHASES, STAGES } = require('./lib/stages.js');// #455: resolves the authoring LCID over the transport hatch, BEFORE constructing the SDK that// bakes it into the App/Form/Dashboard adapters.-const { resolveAuthoringLanguage, BuildHalt } = require('./lib/entity-provision.js');+const { resolveAuthoringLanguage, BuildHalt, findExistingTable, entityHasLocalizedLabels } = require('./lib/entity-provision.js');const { createAzHttpClient, SQL_DEADLOCK_VICTIM } = require('./lib/sdk-http-client.js');const { createPublicationBarrier, describeWithheld } = require('./lib/publication-barrier.js');const { RETRY, judgeFailure, retryPolicyFor, throttleAskOf } = require('./lib/retry-policy.js');@@ -300,7 +300,16 @@ async function discoverOpDiffState(spec, provision) {// Resolve by (entity, name, TYPE) — NOT name alone. A table routinely has same-named Main / Quick View// / Card forms, so a name-only lookup matched multiple rows and the SDK's AmbiguousArtifactError halted// this preflight (fail-closed), blocking the edit. Type-scoped resolution targets the requested form.- const id = await resolveExistingFormId(provision, def);+ // The lookup's MetadataCache answer is also the lag of a table created moments ago (#796), so it says "no form" only when the+ // table itself reads absent; a table that is there keeps the failure, and the gate stops rather than miss a form it would check.+ // The table is asked about exactly as the data-model step asks (lib/entity-provision.js findExistingTable): this read runs BEFORE+ // that step creates the table, so for a table whose labels are localized an inconclusive narrow read is read again and, if it stays+ // inconclusive, stops the gate — never settled by the broad, label-bearing table list, which ahead of a localized create makes+ // Dataverse keep only the base-language label. A table the spec does not declare is never created by the build, so it has no such hazard.+ const declared = (spec.entities || []).find((e) => String(e && e.schemaName).toLowerCase() === def.entityLogicalName);+ const hasLocalizedLabels = !!declared && entityHasLocalizedLabels(declared);+ const tableAbsent = async () => (await findExistingTable(provision, def.entityLogicalName, { hasLocalizedLabels })) === null;+ const id = await resolveExistingFormId(provision, def, { tableNotInCache: tableAbsent });if (!id) continue; // not deployed yet → nothing to pruneawait provision.fetchArtifact('form', id); // seed the workspace copy so getArtifact can read itforms.push({ formId: id, label: `form "${f.name || f.entity}" (${String(f.entity).toLowerCase()})`, deployedForm: await provision.getArtifact('form', id) || {}, def });@@ -883,6 +892,21 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {// metadata-cache lag on a table's default views is the lag of a table just created (retry-policy.js, markFreshTable): the server's answers, and the build's own stop before a default view whose copy// names no table is sent (sdk-build.js, guardDefaultViewCopies), which that lag causes when it reaches the view's read. The retry loop below bounds the invocation, so the set adds no retries of its own.const createdTables = new Set();+ // The ONE retry allowance of this invocation (`maxRetries`), spent by the whole-build retry below and by a read of a table this+ // invocation created that met the table's metadata-cache lag (#796). Such a read is read again where it failed (sdk-build.js+ // readFresh), not by running the whole build again: a whole-build retry resends every save and publish an earlier attempt already+ // made. Each wait takes one retry from the same count, with the same backoff, so a lag never earns retries of its own; once the count+ // is spent the read fails as it did, and the build stops with the service's answer.+ let retriesUsed = 0;+ const retryFreshRead = async (err, table) => {+ if (retriesUsed >= maxRetries) return false;+ retriesUsed += 1;+ const delay = opts.retryDelayMs != null ? opts.retryDelayMs : backoffMs(retriesUsed);+ if (journal) journal.record({ phase: err && err.phase, status: 'retry', label: `table ${table} not readable yet (retry ${retriesUsed}/${maxRetries}) — reading again in ${delay}ms`, detail: String((err && err.message) || err) });+ log(`\n⟳ table ${table} was created moments ago and is not readable yet — reading it again (retry ${retriesUsed}/${maxRetries}) after ${delay}ms…`);+ await sleep(delay);+ return true;+ };// The managed binding store (sdk-build.js openBuildBindingGroups: the one opener, read-only discovery), opened once for the whole// invocation on its first attempt and handed to every attempt as `bindingGroups`, so no attempt opens a second writer. Its debt is// installed on the barrier every attempt shares. Opened inside the attempt so that a store the build cannot trust halts like any@@ -925,6 +949,7 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {provisionSdk: deps.provisionSdk,owedLengths,createdTables,+ ...(opts.apply ? { retryFreshRead } : {}),apply: opts.apply,sampleData: opts.sampleData,publish: opts.publish,@@ -995,8 +1020,9 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {const refused = transient && ask.throttled && declinedCount() > declinedBefore ? throttle.declined() : null;if (refused) {halted = budgetHalt(Math.max(ask.askedMs, refused.askedMs), refused.waitMs);- } else if (attempt <= maxRetries && transient) {- const backoff = opts.retryDelayMs != null ? opts.retryDelayMs : backoffMs(attempt);+ } else if (retriesUsed < maxRetries && transient) {+ retriesUsed += 1;+ const backoff = opts.retryDelayMs != null ? opts.retryDelayMs : backoffMs(retriesUsed);// What the service asked of the next send, carried across the layers (retry-policy.js, throttleAskOf): when the page backend's sends ran out it handed over the moment before which nothing may be// sent. The wait is what is LEFT of it — the layers between did work — in whole seconds, the unit `Retry-After` counts in, and never less than the build's own backoff.const asked = ask.notBefore > 0 ? Math.ceil(Math.min(ask.askedMs || Infinity, Math.max(0, ask.notBefore - now())) / 1000) * 1000 : 0;@@ -1006,9 +1032,9 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {halted = budgetHalt(ask.askedMs || asked, delay);} else {if (ask.throttled) throttle.spend(delay);- if (journal) journal.record({ phase: err && err.phase, status: 'retry', label: `transient error (attempt ${attempt}/${maxRetries}) — retrying in ${delay}ms`, detail: String((err && err.message) || err) });+ if (journal) journal.record({ phase: err && err.phase, status: 'retry', label: `transient error (attempt ${retriesUsed}/${maxRetries}) — retrying in ${delay}ms`, detail: String((err && err.message) || err) });const askNote = asked > 0 ? ` (the service asked to wait ${Math.ceil((ask.askedMs || asked) / 1000)} s)` : '';- log(`\n⟳ transient error in ${err && err.phase} — retrying (attempt ${attempt}/${maxRetries}) after ${delay}ms${askNote}…`);+ log(`\n⟳ transient error in ${err && err.phase} — retrying (attempt ${retriesUsed}/${maxRetries}) after ${delay}ms${askNote}…`);await sleep(delay);continue;}diff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.jsindex 96fb13a83..1d69e6e56 100644--- a/plugins/model-apps/scripts/download-model-app.js+++ b/plugins/model-apps/scripts/download-model-app.js@@ -26,6 +26,16 @@// flows (businessProcessFlows[].reconcile "declared"), which it leaves out too, into businessProcessFlows[] (`managedBpfs`). The download writes// no binding store, so the downloaded folder holds no bindings: a rebuild from it finds each form by name and needs adopt:form:<key>// (each dashboard: adopt:dashboard:<key>; each business rule: adopt:rule:<table>/<name>; each flow: adopt:bpf:<table>/<name>).+// A declared form's handler library the spec does not declare is downloaded with the form, as an `external` web resource, when it is+// this publisher's own unmanaged script (lib/declared-form-io.js libraryEntry; `managedForms.libraries`).+// A persona a declared flow's securityRoles name that the downloaded spec lacks is read from its role and written into personas[] only+// when a rebuild provably leaves that role exactly as it is (lib/persona-restore.js; `managedBpfs.personas`).+// A declared form or flow that is proved but left out only for what the download cannot bring (the script library a form handler+// calls, the persona a flow's securityRoles name) is written ready to paste, with what it still needs, to+// a NEW file `<out>/.maker-workspace/managed-fragments-<UTC time>-<random>.json` (`managedFragments.file` in the result;+// lib/managed-fragments.js). It is created exclusively, so it never replaces, moves or removes a file, and with nothing to write+// nothing is written. So that a failure to write it leaves the folder as it was, the managed download writes the page tree to a+// staging folder inside <out> and publishes it only after the restore, the validation and the fragments file have succeeded.// Off by default, so a download without them makes the reads it always made.//// A page's key is its identity in a rebuild, so a download keeps the key each page already has: the one the app's page manifest binds to it, then the one an@@ -50,7 +60,8 @@const fs = require('node:fs');const path = require('node:path');-const { assertSafeOutputDir, assertPlainFileTarget, writeFileSafe } = require('./lib/safe-fs.js');+const crypto = require('node:crypto');+const { assertSafeOutputDir, assertPlainFileTarget, writeFileSafe, removeTreeWithRetry } = require('./lib/safe-fs.js');const { parseArgs, validateFlags, emitResult, preflightAuth, dataverseOrigin, requireDataverseOrigin, webApiUrl, readOrgLanguageCode, readLanguageCodeFlag } = require('./lib/dataverse-auth.js');const { writeBaseline } = require('./lib/deployed-baseline.js');const { createAzHttpClient } = require('./lib/sdk-http-client.js');@@ -62,6 +73,7 @@ const { restoreManagedForms } = require('./lib/declared-form-io.js');const { restoreManagedDashboards } = require('./lib/declared-dashboard-io.js');const { restoreManagedRules } = require('./lib/declared-rule-io.js');const { restoreManagedBpfs } = require('./lib/declared-bpf-io.js');+const { settleFragments } = require('./lib/managed-fragments.js');const { fetchSitemap, sitemapGenPages, appNavigationMatchesSitemap } = require('./lib/sitemap-pages.js');const { isRestrictedSolution } = require('./lib/system-solutions.js');const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode, isLocalizedLabelMap, derivedPluralName, ambiguousChoiceAliases, relationshipSchemaName, manyToManySchemaName, dashboardNameKey, PAGE_MODEL_RE, sitemapEntityTables, lookupLabelFor, isOldLookupColumnLabel } = require('./lib/app-spec.js');@@ -2992,6 +3004,35 @@ function writePageTree(pagesRoot, pages) {}}+// The checks writePageTree makes before it removes anything, made on their own: the managed download asks them before it settles its+// fragments file, so a page tree that cannot be replaced stops it before that file, the pages or the spec are written.+function assertPageTreeReplaceable(pagesRoot) {+ try {+ fs.lstatSync(pagesRoot);+ } catch (e) {+ if (e && e.code === 'ENOENT') return;+ throw e;+ }+ assertSafeOutputDir(pagesRoot);+ assertNoPlantedPageLinks(pagesRoot);+}++// A fresh staging folder for the managed download's page tree, made INSIDE <out> (nothing outside the folder the maker named is written)+// under a hidden name unique to this process and call. `mkdir` without `recursive` fails on a name that exists, so a folder that is+// already there (another run's, or the maker's) is never reused or removed: another name is tried.+function makePageStage(outDir) {+ const root = assertSafeOutputDir(outDir, { create: true });+ for (let attempt = 0; ; attempt += 1) {+ const dir = path.join(root, `.download-pages.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`);+ try {+ fs.mkdirSync(dir);+ return dir;+ } catch (e) {+ if (!(e && e.code === 'EEXIST') || attempt >= 4) throw e;+ }+ }+}+// Reads every page the sitemap names, by id — so nothing outside this app is read — a few at a time, and answers// { ok: true, pages: [{ pageId, files }] } in the sitemap's order, or { ok: false, errors } naming each page that could not be read. A page that// cannot be read is a page the spec would drop: the caller refuses to write one rather than report it as an app without that page. That includes@@ -3005,7 +3046,28 @@ async function readSitemapPages(genpage, ids, concurrency) {return { ok: true, pages: results.map(({ id, page }) => ({ pageId: String(id).toLowerCase(), files: pageFolderFiles(page) })) };}-async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy = false, resetPageKeys = false, concurrency, languageCode, includeCapabilities = false, captureTheme = includeCapabilities }) {+// `stagePages` (the managed download, main): the page tree is written to a staging folder inside <out> (makePageStage) and read+// back from there exactly as a download writes it — the same files, the same reverse-resolved page.tsx — and the folder is removed.+// The real pages/ folder is not touched: the result's `stagedPages` publishes it later (`check` makes writePageTree's checks without+// writing, `publish` writes the tree with writePageTree). main publishes it only after everything that can still stop the download+// has succeeded, so a refusal there leaves a maker's page edits as they were. Without the option the download is exactly as before.+async function runDownload(options = {}) {+ if (!options.stagePages) return downloadApp(options);+ const stage = { dir: null, pages: null };+ try {+ const result = await downloadApp({ ...options, stage });+ if (!result.ok || !stage.pages) return result;+ const pagesRoot = path.join(path.resolve(options.outDir), 'pages');+ const pages = stage.pages;+ return { ...result, stagedPages: { check: () => assertPageTreeReplaceable(pagesRoot), publish: () => writePageTree(pagesRoot, pages) } };+ } finally {+ // Best-effort: the pages are in memory by now. A folder that stays is named, so the maker can delete it.+ const left = stage.dir ? removeTreeWithRetry(stage.dir) : null;+ if (left) process.stderr.write(`WARNING: the download's staging folder ${stage.dir} could not be removed (${left}): delete it.\n`);+ }+}++async function downloadApp({ sdk, genpage, outDir, appId, appUnique, allowLossy = false, resetPageKeys = false, concurrency, languageCode, includeCapabilities = false, captureTheme = includeCapabilities, stage = null }) {concurrency = validatedDownloadConcurrency(concurrency);// The caller named this directory. A link at its final component would make every page and// the spec land outside it. Ancestors are the caller's choice and are not inspected.@@ -3175,12 +3237,19 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossyconst read = await readSitemapPages(genpage, sitemapIds, concurrency);if (!read.ok) return { ok: false, error: `page download failed: ${read.errors.join('; ')}` };- writePageTree(pagesRoot, read.pages);+ // Staged (see runDownload): the tree is written, read back and reverse-resolved under the staging folder, which stands in for+ // <out> so each page's codeFile (relative to it) is the one a direct download gives.+ if (stage) stage.dir = makePageStage(outDir);+ const treeRoot = stage ? path.join(stage.dir, 'pages') : pagesRoot;+ const writeRoot = stage ? stage.dir : outDir;+ writePageTree(treeRoot, read.pages);const unreadableConfigs = [];const unkeptModels = [];const unkeptBindings = [];- pages = parseDownloadedPages(pagesRoot, outDir, nameById, unreadableConfigs, unkeptModels, unkeptBindings);+ pages = parseDownloadedPages(treeRoot, writeRoot, nameById, unreadableConfigs, unkeptModels, unkeptBindings);+ // A read error names the file it read; name the one the maker will find.+ if (stage) for (const u of unreadableConfigs) u.reason = String(u.reason).split(stage.dir).join(path.resolve(outDir));// Reported, not gated: a page whose model is left out rebuilds exactly as every page did before the spec carried models — an// update leaves the model the page already has as it is (the SDK writes only what a spec names), and a page the rebuild creates// gets none.@@ -3230,13 +3299,20 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy// place the lexer reads by guess is turned back, and only if the build would take the page written that way (see// reverseResolveNavIdsReport); the ids it leaves are reported below.for (const p of pages) {- const abs = path.join(outDir, p.codeFile);+ const abs = path.join(writeRoot, p.codeFile);assertPlainFileTarget(abs); // FAIL on a planted link (no swallow, no write)const src = fs.readFileSync(abs, 'utf8'); // FAIL on a read error (no swallow)const rev = reverseResolveNavIdsReport(src, idToKey); // structural — nav pageId literals onlyif (rev.code !== src) writeFileSafe(abs, rev.code, { encoding: 'utf8' }); // FAIL on a write error (no swallow)for (const left of rev.left) navIdsLeft.push({ page: p.name, ...left });}+ // The staged tree as it now is on disk, read back whole, for runDownload to publish: the bytes writePageTree will write again.+ if (stage) {+ stage.pages = read.pages.map(({ pageId, files }) => ({+ pageId,+ files: Object.fromEntries(Object.keys(files).map((name) => [name, fs.readFileSync(path.join(treeRoot, pageId, name), 'utf8')])),+ }));+ }// Every page id of this app still in a downloaded page is reported, whether a call the checker recognised holds it or not (see// knownIdsLeft in pageref-resolver.js). One in a navigation call is a hardcoded page id to the build, which refuses one, so say so now// rather than at the rebuild; one that is data can stay.@@ -3682,7 +3758,9 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossyif (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, ...(navIdsLeft.length ? { navIdsLeft } : {}), ...(pageBindings ? { pageBindings } : {}), ...(solutionCandidates ? { solutionCandidates } : {}) };+ // `publisher` is internal (main hands it to the managed restore, which downloads a form's handler library only under this+ // publisher's verified prefix); it is not part of the printed result.+ return { ok: true, spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped, relationships, relationshipsSkipped, publisher: { prefix: solution.publisherPrefix, resolved: solution.prefixResolved }, ...(navIdsLeft.length ? { navIdsLeft } : {}), ...(pageBindings ? { pageBindings } : {}), ...(solutionCandidates ? { solutionCandidates } : {}) };}async function main(deps = {}) {@@ -3813,7 +3891,8 @@ async function main(deps = {}) {// The page backend reads through the download's own throwaway SDK, lent to it: nothing of its own to make or remove.const genpage = io.makeGenpageSdk(env, { sdk });- const result = await io.runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy: allowLossyDownload, resetPageKeys, languageCode: session.languageCode, includeCapabilities });+ // The managed download stages its page tree (runDownload `stagePages`): it is published below, after everything that can still stop it.+ const result = await io.runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy: allowLossyDownload, resetPageKeys, languageCode: session.languageCode, includeCapabilities, ...(includeManaged ? { stagePages: true } : {}) });// The run's last writes: these lines, then the result and the exit, with no turn of the event loop between them — made blocking (lib/output-redaction.js).makeWritesBlocking(process.stdout, io.stderr);if (!result.ok) { finish(false, result); return; }@@ -3854,6 +3933,8 @@ async function main(deps = {}) {let managedDashboards = null;let managedRules = null;let managedBpfs = null;+ // The proved items the restore leaves out only for what the download cannot bring (lib/managed-fragments.js).+ const fragments = [];if (includeManaged) {const source = {sdk,@@ -3863,6 +3944,8 @@ async function main(deps = {}) {appUniqueName: appUnique,solutionUniqueName: spec.solution && spec.solution.uniqueName,validate: (s) => io.validateAppSpec(s, { profile: 'plan', reconstructed: true }),+ fragments,+ publisher: result.publisher,};try {managedForms = await restoreManagedForms(source);@@ -3874,9 +3957,11 @@ async function main(deps = {}) {return;}for (const s of managedForms.stale) io.stderr.write(`WARNING: managed form ${s.key} was not restored: ${s.reason}. It is left out of forms[], as every form is without --include-managed.\n`);+ for (const l of managedForms.libraries || []) io.stderr.write(`NOTE: handler library '${l.name}' of managed form ${l.forms.join(', ')} was downloaded into webResources[] as external: a build reuses it where it exists without writing its content, creates it where it is missing, and a teardown never deletes it.\n`);for (const s of managedDashboards.stale) io.stderr.write(`WARNING: managed dashboard ${s.key} was not restored: ${s.reason}. Its dashboard is downloaded as every dashboard is without --include-managed.\n`);for (const s of managedRules.stale) io.stderr.write(`WARNING: managed business rule ${s.key} was not restored: ${s.reason}. It is left out of businessRules[], as every business rule is without --include-managed.\n`);for (const s of managedBpfs.stale) io.stderr.write(`WARNING: managed business process flow ${s.key} was not restored: ${s.reason}. It is left out of businessProcessFlows[], as every process flow is without --include-managed.\n`);+ for (const p of managedBpfs.personas || []) io.stderr.write(`NOTE: persona '${p.name}' was written from its role as it is now; a build owns a persona's role, so a privilege added to that role outside the spec is removed by the next build.\n`);}const validation = io.validateAppSpec(spec, { profile: 'plan', reconstructed: true });if (!validation.ok) {@@ -3895,6 +3980,23 @@ async function main(deps = {}) {+ ' Review each: change to "selector" if opening the page from the navigation should show a record picker.\n');}+ // The fragments file is settled before anything is published: the staged page tree, the spec and the baseline are written only+ // after it, so a refusal or a failed write here leaves every one of them as it was. The page tree's own checks come first, so a+ // tree that cannot be replaced stops the download before the fragments file is written.+ let managedFragments = null;+ if (includeManaged) {+ if (result.stagedPages) result.stagedPages.check();+ try {+ managedFragments = settleFragments(outDir, { app: appUnique, items: fragments });+ } catch (e) {+ finish(false, { ok: false, code: (e && e.code) || 'managed-fragments-unwritable', error: (e && e.message) || String(e) });+ return;+ }+ if (managedFragments) {+ io.stderr.write(`WARNING: ${managedFragments.keys.length} managed item(s) left out only for what the download could not bring are written ready to paste in ${managedFragments.file}: add each "paste" entry to app-spec.json together with what its "needs" lists (from the spec it was built from), then build.\n`);+ }+ if (result.stagedPages) result.stagedPages.publish();+ }writeFileSafe(specPath, JSON.stringify(spec, null, 2));// AB#6726727: the spec just written is this app's server-current edit snapshot, so it is the baseline a later build// lines the live sitemap up against — a nav change made in the designer after this download is then@@ -3912,7 +4014,7 @@ async function main(deps = {}) {}// Each optional field is in the result only when it has something to say. `navIdsLeft` is absent in the usual case (runDownload leaves it out when no id is// left) and could be an empty list from another producer, so it is checked for both: an empty list is no finding.- finish(true, { ok: true, spec: specPath, pages: pages.length, entities: entities.length, webResources: webResources.length, droppedSubareas, ...(notRoundTripped ? { notRoundTripped } : {}), ...(defaulted.length ? { directEntryDefaulted: defaulted } : {}), ...(navIdsLeft && navIdsLeft.length ? { navIdsLeft } : {}), ... (pageBindings ? { pageBindings } : {}), ...(solutionCandidates ? { solutionCandidates } : {}), ...(managedForms ? { managedForms } : {}), ...(managedDashboards ? { managedDashboards } : {}), ...(managedRules ? { managedRules } : {}), ...(managedBpfs ? { managedBpfs } : {}) });+ finish(true, { ok: true, spec: specPath, pages: pages.length, entities: entities.length, webResources: webResources.length, droppedSubareas, ...(notRoundTripped ? { notRoundTripped } : {}), ...(defaulted.length ? { directEntryDefaulted: defaulted } : {}), ...(navIdsLeft && navIdsLeft.length ? { navIdsLeft } : {}), ... (pageBindings ? { pageBindings } : {}), ...(solutionCandidates ? { solutionCandidates } : {}), ...(managedForms ? { managedForms } : {}), ...(managedDashboards ? { managedDashboards } : {}), ...(managedRules ? { managedRules } : {}), ...(managedBpfs ? { managedBpfs } : {}), ...(managedFragments ? { managedFragments } : {}) });} finally {try { if (session) session.cleanup(); } catch { /* best-effort: the result below matters more */ }if (outcome) io.emitResult(...outcome);diff --git a/plugins/model-apps/scripts/lib/app-roles.js b/plugins/model-apps/scripts/lib/app-roles.jsindex d8fc56f02..b212b6756 100644--- a/plugins/model-apps/scripts/lib/app-roles.js+++ b/plugins/model-apps/scripts/lib/app-roles.js@@ -6,6 +6,8 @@// verify-model-app.js appIdFor / appRoleIdsFor — the ids of the roles a deployed app has, to prove the app is associated with the roles its personas author.// They read as they always did: the published layer, and an answer that carries no list is read as no ids (verify then FAILS the persona's// check, the safe side).+// persona-restore.js appRoleIdsComplete — the same ids for the managed download's persona proof, read strictly (see its comment): there a missing id+// is written into the spec as `appAccess: false`, so a short or malformed answer must be a refusal, not a shorter list.// write-app-spec-doc.js appRolesOf — the roles (by name) an app has, for the design document: an extension of an app that already has roles// says nothing about them in its spec, and the document is where a reviewer is told what they are. It states what it read, so it is// strict where verify is lenient: see below.@@ -30,6 +32,7 @@ const { collectionRows } = require('./app-components.js');// A failure as the one line a caller shows: the message, cut at 200 characters (an error text can carry a whole response body).const reasonOf = (err) => ((err && err.message) ? String(err.message).slice(0, 200) : 'read failed');+const GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;// The association rows of an app, with the role columns in `select` (the navigation property answers role rows).const associationPath = (appId, select) => `/appmodules(${appId})/appmoduleroles_association?$select=${select.join(',')}`;@@ -62,6 +65,31 @@ async function appRoleIdsFor(sdk, appUnique) {}}+/**+ * The managed download's view (lib/persona-restore.js): the same ids as appRoleIdsFor, read the strict way, because there the answer is not a check+ * but a value WRITTEN into the spec — a role missing from it becomes `appAccess: false`, and a build from that spec dissociates the role from the app.+ * So the rows come through collectionRows (every page, a malformed or refused answer an error) and every row must name a role by a GUID; anything+ * less is { ok: false, reason }, never a shorter list. appRoleIdsFor keeps its lenient contract for verify, where a short list fails safe.+ * { ok: true, roleIds } (lower-case, braces stripped) | { ok: false, reason }+ */+async function appRoleIdsComplete(sdk, appUnique) {+ try {+ const appId = await appIdFor(sdk, appUnique);+ if (!appId) return { ok: false, reason: `app '${appUnique}' could not be resolved` };+ if (!sdk.dataverse || typeof sdk.dataverse.get !== 'function') return { ok: false, reason: 'SDK dataverse reader is unavailable' };+ const rows = await collectionRows(sdk.dataverse, associationPath(appId, ['roleid']), 'the association rows');+ const roleIds = [];+ for (const row of rows) {+ const id = row && typeof row.roleid === 'string' ? row.roleid.trim().toLowerCase().replace(/^\{|\}$/g, '') : '';+ if (!GUID_RE.test(id)) return { ok: false, reason: 'an association row names no role' };+ roleIds.push(id);+ }+ return { ok: true, roleIds };+ } catch (err) {+ return { ok: false, reason: reasonOf(err) };+ }+}+/*** The roles associated with the app `appUnique`, as the environment holds them now.* { state: 'read', appUnique, appId, roles: [{ roleId, name, managed }] } `roles` by name (lib/compare-text.js), then id: the same order on every run@@ -95,4 +123,4 @@ async function appRolesOf(sdk, appUnique) {}}-module.exports = { appIdFor, appRoleIdsFor, appRolesOf };+module.exports = { appIdFor, appRoleIdsFor, appRoleIdsComplete, appRolesOf };diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.jsindex ab4e446a6..1019d04e7 100644--- a/plugins/model-apps/scripts/lib/app-spec.js+++ b/plugins/model-apps/scripts/lib/app-spec.js@@ -1155,6 +1155,78 @@ function reportUnknownAppShellKeys(node, level, where, errors) {}}+// The keys the build READS on a `views[]` entry (viewDef in sdk-build.js; compileViewIntent in view-reconcile.js, which also reads `key`,+// `viewId` and `linkEntities` of a declared view; `description` is written to the view by both) and on each of its filter items+// (`attr`, `op`, `value`, `values`; `relatedEntity` scopes a condition to a declared join). Any other key is dropped without a trace,+// so a view written with `filter` instead of `filters` was built WITHOUT its filter and listed every active row (#799). Frozen, in the+// order the messages list them.+const VIEW_KEYS = Object.freeze(['entity', 'name', 'description', 'columns', 'sort', 'filters', 'activeOnly', 'reconcile', 'key', 'viewId', 'linkEntities']);+const VIEW_FILTER_KEYS = Object.freeze(['attr', 'op', 'value', 'values', 'relatedEntity']);+// Keys no code reads that are nevertheless accepted without a warning, because the docs and samples of earlier releases showed them+// and they never changed what is built. Frozen: the list is closed, a new entry needs the same reason.+const IGNORED_VIEW_KEYS = Object.freeze(['type']);++// What to write instead, for the keys an author is most likely to reach for that a near spelling does not explain (`filter`, `column`+// and `activeonly` are caught by the single-edit matcher). Prototype-less for the reason ENTITY_KEY_HINTS is: the lookup key comes from the+// spec.+//+// `type` is deliberately not warned about (see IGNORED_VIEW_KEYS): older docs and the shipped+// samples put it on a view, it never had an effect (a view is always a public view of its table), and a spec written from them must keep+// passing `lint-app-spec.js --strict`, which fails on any warning. The keys that DO warn are the ones whose silent loss changes the view+// (a misspelled `filters` drops the filter), so `--strict` failing on those is intended.+const VIEW_KEY_HINTS = Object.assign(Object.create(null), {+ where: " — did you mean 'filters'?",+ conditions: " — did you mean 'filters'?",+ orderBy: " — did you mean 'sort'? ([{ \"attr\": \"<column>\", \"dir\": \"asc\" | \"desc\" }])",+ order: " — did you mean 'sort'? ([{ \"attr\": \"<column>\", \"dir\": \"asc\" | \"desc\" }])",+ table: " — did you mean 'entity'?",+ active: " — did you mean 'activeOnly'?",+});+const VIEW_FILTER_KEY_HINTS = Object.assign(Object.create(null), {+ column: " — did you mean 'attr'? A filter names its column in 'attr'",+ field: " — did you mean 'attr'? A filter names its column in 'attr'",+ attribute: " — did you mean 'attr'? A filter names its column in 'attr'",+ name: " — did you mean 'attr'? A filter names its column in 'attr'",+ operator: " — did you mean 'op'? A filter names its comparison in 'op'",+ operation: " — did you mean 'op'? A filter names its comparison in 'op'",+ val: " — did you mean 'value'? (or 'values', for in / not-in)",+ table: " — did you mean 'relatedEntity'? Only a condition on a declared join takes one",+ entity: " — did you mean 'relatedEntity'? Only a condition on a declared join takes one",+});++// The warnings for the keys of one `views[]` entry and of its filter items (`filters[]`, and the `filters[]` of each `linkEntities[]` join, which are+// the same shape), each with `vlabel` in front: one per unknown key, naming the key it most likely meant (a written hint first, then the shared+// single-edit matcher, which also settles a casing slip). A WARNING, not an error: the build has always ignored such a key, so a spec that+// carries one still builds as before, and one a release before this check validated clean must keep validating. Only a plain object is+// inspected — a non-object entry or filter is reported by the shape checks — and enumeration is guarded because the spec comes from the caller.+function viewKeyWarnings(v, vlabel) {+ const unknown = (obj, allowed, hints, where, accepted = []) => {+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return [];+ let keys;+ try {+ keys = Object.keys(obj);+ } catch {+ return [`${vlabel}: ${where || 'the view'} could not be inspected — enumerating its keys threw`];+ }+ return keys.filter((k) => !allowed.includes(k) && !accepted.includes(k)).map((k) => {+ let hint = hints[k];+ if (!hint) {+ const near = nearestName(k, allowed.map((a) => a.toLowerCase()));+ const meant = near && allowed.find((a) => a.toLowerCase() === near);+ hint = meant ? ` — did you mean '${meant}'?` : '';+ }+ return `${vlabel}: ${where ? `${where}: ` : ''}unknown key '${k}'${hint}; the build ignores it (allowed: ${allowed.join(', ')})`;+ });+ };+ const out = unknown(v, VIEW_KEYS, VIEW_KEY_HINTS, '', IGNORED_VIEW_KEYS);+ const filterLists = [['filters', v && v.filters]];+ if (v && Array.isArray(v.linkEntities)) v.linkEntities.forEach((l, i) => filterLists.push([`linkEntities[${i}].filters`, l && l.filters]));+ for (const [path, list] of filterLists) {+ if (Array.isArray(list)) list.forEach((f, i) => out.push(...unknown(f, VIEW_FILTER_KEYS, VIEW_FILTER_KEY_HINTS, `${path}[${i}]`)));+ }+ return out;+}+// The column logical names an entity legitimately exposes to a rule / process step: its declared// columns, its primary name column, and any lookup a relationship creates ON it (a lookup is a real// column on the referencing table, just declared elsewhere in the spec).@@ -3378,6 +3450,7 @@ function validateAppSpec(spec, opts = {}) {else v.filters.forEach((f, i) => attrRef(f && f.attr, `filters[${i}].attr`));}if (v && v.reconcile !== undefined && v.reconcile !== 'declared') errors.push(`${vlabel}: reconcile must be "declared" (or left out)`);+ warnings.push(...viewKeyWarnings(v, vlabel));if (isDeclaredView(v)) {// compileViewIntent walks columns, sort, filters and joins as lists; a non-list one is already reported above (or by// the shape normalization), so it is not walked again into a TypeError.diff --git a/plugins/model-apps/scripts/lib/bpf-settlement.js b/plugins/model-apps/scripts/lib/bpf-settlement.jsindex 0b3b48299..41fe6b36f 100644--- a/plugins/model-apps/scripts/lib/bpf-settlement.js+++ b/plugins/model-apps/scripts/lib/bpf-settlement.js@@ -54,6 +54,7 @@ const { CODES, rootCreateAcknowledged } = require('./managed-bindings.js');const { createWorkflowDriver, createCopyGuard, answeredRefusal, coded, completionBytesFor, completionWithin, HASH_BOUND, NAME_BOUND, ACTIVE, DRAFT } = require('./workflow-drive.js');// sdk-build is required lazily: it is the module that will call this one, so a top-level require would be a cycle.+const { markFreshTable, isFreshTableReadLag } = require('./retry-policy.js');const sdkBuild = () => require('./sdk-build.js');const FAMILY = 'bpf';@@ -519,7 +520,7 @@ function wholeBodyErrors(flow, view) {* what security-role grants and the app's components must use.*/async function settleDeclaredBpf(input) {- const { flow, sdk, store, catalog, approvals = null, opts = {}, halt, phase = 'business-process-flows', barrier, httpClient = null, instanceUrl = null, sendObserver = null } = input || {};+ const { flow, sdk, store, catalog, approvals = null, opts = {}, halt, phase = 'business-process-flows', barrier, httpClient = null, instanceUrl = null, sendObserver = null, freshTable = null, retryFreshRead = null } = input || {};const ensureMembership = (input && input.ensureMembership) || (async () => {});if (!isDeclaredBpf(flow)) throw coded(CODES.notSettled, 'settleDeclaredBpf takes a flow with reconcile: "declared"');if (!store || typeof store.snapshot !== 'function') throw coded(CODES.notSettled, 'settleDeclaredBpf needs the managed binding store');@@ -908,11 +909,20 @@ async function settleDeclaredBpf(input) {const { id } = identityFor('bpf', key, { catalog });let sameName;let atId;- try {- sameName = await sdk.queryRecords('workflow', { select: ['workflowid'], filter: sdkBuild().bpfFilter(flow.name, table), paginate: true });- atId = await readVersion(id);- } catch (err) {- throw coded('create-identity-unverified', `${label}: whether the flow already exists could not be read, so it is neither created nor adopted`, { cause: err });+ for (;;) {+ try {+ sameName = await sdk.queryRecords('workflow', { select: ['workflowid'], filter: sdkBuild().bpfFilter(flow.name, table), paginate: true });+ atId = await readVersion(id);+ break;+ } catch (err) {+ // On a table this invocation created (`freshTable`, the caller's), the read can meet the table's metadata-cache lag+ // (retry-policy.js isFreshTableLag): it is read again here, as long as the build's one retry allowance lasts+ // (`retryFreshRead`, build-model-app.js), and nothing was sent before it. Once that is spent, or for any other failure,+ // the failure is final and carries the service's answer.+ if (freshTable) markFreshTable(err, freshTable);+ if (freshTable && typeof retryFreshRead === 'function' && isFreshTableReadLag(err) && (await retryFreshRead(err, freshTable)) === true) continue;+ throw coded('create-identity-unverified', `${label}: whether the flow already exists could not be read, so it is neither created nor adopted`, { cause: err });+ }}if (!Array.isArray(sameName)) throw coded('create-identity-unverified', `${label}: the read of its name answered no list`);const ids = sameName.map((r) => normalizeGuid(r.workflowid));diff --git a/plugins/model-apps/scripts/lib/chart-reconcile.js b/plugins/model-apps/scripts/lib/chart-reconcile.jsindex 22ec5e2b6..d391a9695 100644--- a/plugins/model-apps/scripts/lib/chart-reconcile.js+++ b/plugins/model-apps/scripts/lib/chart-reconcile.js@@ -44,6 +44,7 @@ const {emptyResult,operation,refusal,+ readFailure,approvalKey,isApproved,lookupBinding,@@ -194,8 +195,8 @@ async function planChartReconcile({ chart, sdk, chartArtifact }, ctx = {}) {if (!id && !binding && ctx.managed && typeof ctx.managed.observe === 'function') {try {id = normalizeGuid(await ctx.managed.observe('chart', key)) || '';- } catch {- plan.unknown.push(refusal(key, 'chart-lookup-unreadable', 'whether the chart exists could not be read'));+ } catch (err) {+ plan.unknown.push(readFailure(key, 'chart-lookup-unreadable', 'whether the chart exists could not be read', err));return plan;}}@@ -204,9 +205,10 @@ async function planChartReconcile({ chart, sdk, chartArtifact }, ctx = {}) {id = normalizeGuid(await sdk.findArtifact('chart', { name: intent.name, entity: intent.entity }));} catch (err) {// The SDK refuses a name two rows share (AMBIGUOUS_ARTIFACT): choosing one would edit a row the spec- // may not mean, so the maker names it instead. Any other failure leaves existence unknown.+ // may not mean, so the maker names it instead. Any other failure leaves existence unknown, with the read's own+ // failure kept (as for a view).if (err && err.code === 'AMBIGUOUS_ARTIFACT') plan.refused.push(refusal(key, 'chart-name-ambiguous', 'several charts on the table have this name; rename or remove the extra one before it can be managed'));- else plan.unknown.push(refusal(key, 'chart-lookup-unreadable', 'whether the chart exists could not be read'));+ else plan.unknown.push(readFailure(key, 'chart-lookup-unreadable', 'whether the chart exists could not be read', err));return plan;}}diff --git a/plugins/model-apps/scripts/lib/create-request-body.js b/plugins/model-apps/scripts/lib/create-request-body.jsnew file mode 100644index 000000000..dfe716141--- /dev/null+++ b/plugins/model-apps/scripts/lib/create-request-body.js@@ -0,0 +1,78 @@+'use strict';+// The JSON body the vendored SDK's push sends to create one artifact, worked out without sending it. Shared by the stable+// view/chart creates (creates-stable-build.js) and the declared dashboard create receipt (dashboard-reconcile.js): each pins+// its one create POST to the body this answers, so the request the push actually dispatches must carry the draft this build+// made, field for field.++const { normalizeGuid } = require('./reconcile-common.js');++/**+ * The JSON body the SDK's push sends to create `artifact` at `id`: the same SDK, made over a throwaway workspace+ * (lib/throwaway-sdk.js) with the same connection, language and solution, is given the draft and pushed, and its first write+ * is captured and never sent (nor any write after it). Its reads go to the real connection (a view's push reads its table's+ * metadata for the layout, one GET; a chart's and a dashboard's read nothing), so the body is serialised exactly as the real+ * push serialises it — from the draft held in memory, not from any file a second process could change. Throws when that+ * cannot be shown: no SDK connection, or a first write that is not one POST to `family.collection` naming `id`.+ * POST https://contoso.crm.dynamics.com/api/data/v9.2/savedqueries?$select=savedqueryid+ * { "name": "Declared Items", "fetchxml": "<fetch …>", "layoutxml": "<grid …>", …, "savedqueryid": "a1d1e2a3-…" }+ *+ * How the draft is loaded into the throwaway workspace (`family.load`):+ * 'create' `createArtifact(kind, artifact)` — a view or chart draft as createArtifact answered it. The SDK fills a fresh+ * default and lays the draft over it, which for these kinds is the draft itself.+ * 'write' the SDK's own `workspace.writeArtifact(kind, id, artifact)` — a dashboard. Its `createArtifact` would REPLACE the+ * bag with a fresh default layout, losing the reseeded tab and section and every caption edit the build already+ * made, so the complete assembled draft is written as it is, with no saved snapshot: the push then reads it as a+ * new artifact and serialises its create normally. Nothing of it is rewritten here.+ *+ * @param {object} sdk the build's SDK (its `dataverse` connection and `languageCode` are reused)+ * @param {{ kind: string, collection: string, idField: string, load?: 'create'|'write' }} family+ * @param {string} id+ * @param {object} artifact+ */+async function expectedCreateBody(sdk, family, id, artifact) {+ const { kind, collection, idField, load = 'create' } = family || {};+ const conn = sdk && sdk.dataverse;+ if (!conn || typeof conn.instanceUrl !== 'string' || !conn.httpClient || typeof conn.httpClient.get !== 'function') {+ throw new Error('the SDK exposes no connection to serialise the create with');+ }+ const { withThrowawaySdk } = require('./throwaway-sdk.js');+ const DRY = Symbol('dry');+ let captured = null;+ const client = { get: (url, options) => conn.httpClient.get(url, options) };+ for (const m of ['post', 'patch', 'put', 'delete']) {+ client[m] = async (url, body) => {+ if (!captured) captured = { method: m, url: String(url), body };+ throw Object.assign(new Error('not sent: the create body is only being worked out'), { [DRY]: true });+ };+ }+ await withThrowawaySdk({ env: conn.instanceUrl, prefix: 'create-body-', httpClient: client }, async (make) => {+ const dry = make({+ ...(typeof sdk.languageCode === 'number' || typeof sdk.languageCode === 'string' ? { languageCode: sdk.languageCode } : {}),+ ...(typeof conn.solutionUniqueName === 'string' && conn.solutionUniqueName ? { solutionUniqueName: conn.solutionUniqueName } : {}),+ });+ await dry.initWorkspace();+ if (load === 'write') {+ if (!dry.workspace || typeof dry.workspace.writeArtifact !== 'function') throw new Error('the SDK exposes no workspace to load the draft into');+ await dry.workspace.writeArtifact(kind, id, JSON.parse(JSON.stringify(artifact)));+ } else {+ await dry.createArtifact(kind, artifact);+ }+ try {+ await dry.pushArtifact(kind, id);+ } catch (err) {+ if (!captured) throw err;+ }+ });+ if (!captured) throw new Error('the push sent no create');+ let path = '';+ try { path = new URL(captured.url, conn.instanceUrl).pathname; } catch { /* checked below */ }+ let body = captured.body;+ if (typeof body === 'string') { try { body = JSON.parse(body); } catch { body = null; } }+ if (captured.method !== 'post' || !path.toLowerCase().endsWith(`/${String(collection).toLowerCase()}`) || !body || typeof body !== 'object' || Array.isArray(body)+ || normalizeGuid(body[idField]) !== normalizeGuid(id)) {+ throw new Error(`the push's first write was not one create of ${id}`);+ }+ return body;+}++module.exports = { expectedCreateBody };diff --git a/plugins/model-apps/scripts/lib/creates-stable-build.js b/plugins/model-apps/scripts/lib/creates-stable-build.jsindex 3ed411846..31578dbea 100644--- a/plugins/model-apps/scripts/lib/creates-stable-build.js+++ b/plugins/model-apps/scripts/lib/creates-stable-build.js@@ -65,6 +65,7 @@ const { AsyncLocalStorage } = require('node:async_hooks');const { createCompositePortForSpec, markPreSend } = require('./creates-port.js');const { createStop } = require('./creates-identity.js');const { assertCleanContinuation, readLocalCreateState } = require('./creates-local.js');+const { expectedCreateBody } = require('./create-request-body.js');const { authorizeFlag } = require('./cli-failure.js');const viewReconcile = require('./view-reconcile.js');const chartReconcile = require('./chart-reconcile.js');@@ -106,57 +107,6 @@ const FAMILY = Object.freeze({const lc = (s) => String(s == null ? '' : s).toLowerCase();const nonempty = (s) => typeof s === 'string' && s.trim().length > 0;-/**- * The JSON body the SDK's push sends to create `artifact` (a view or chart draft as createArtifact answered it) at `id`: the same- * SDK, made over a throwaway workspace (lib/throwaway-sdk.js) with the same connection and language, is given the draft and pushed,- * and its first write is captured and never sent. Its reads go to the real connection (a view's push reads its table's metadata- * for the layout, one GET; a chart's reads nothing), so the body is serialised exactly as the real push serialises it — from the- * draft held in memory, not from any file a second process could change. Throws when that cannot be shown: no SDK connection,- * or a first write that is not one POST to the family's collection naming `id`.- * POST https://contoso.crm.dynamics.com/api/data/v9.2/savedqueries?$select=savedqueryid- * { "name": "Declared Items", "fetchxml": "<fetch …>", "layoutxml": "<grid …>", …, "savedqueryid": "a1d1e2a3-…" }- */-async function expectedCreateBody(sdk, kind, id, artifact) {- const fam = FAMILY[kind];- const conn = sdk && sdk.dataverse;- if (!conn || typeof conn.instanceUrl !== 'string' || !conn.httpClient || typeof conn.httpClient.get !== 'function') {- throw new Error('the SDK exposes no connection to serialise the create with');- }- const { withThrowawaySdk } = require('./throwaway-sdk.js');- const DRY = Symbol('dry');- let captured = null;- const client = { get: (url, options) => conn.httpClient.get(url, options) };- for (const m of ['post', 'patch', 'put', 'delete']) {- client[m] = async (url, body) => {- if (!captured) captured = { method: m, url: String(url), body };- throw Object.assign(new Error('not sent: the create body is only being worked out'), { [DRY]: true });- };- }- await withThrowawaySdk({ env: conn.instanceUrl, prefix: 'create-body-', httpClient: client }, async (make) => {- const dry = make({- ...(typeof sdk.languageCode === 'number' || typeof sdk.languageCode === 'string' ? { languageCode: sdk.languageCode } : {}),- ...(typeof conn.solutionUniqueName === 'string' && conn.solutionUniqueName ? { solutionUniqueName: conn.solutionUniqueName } : {}),- });- await dry.initWorkspace();- await dry.createArtifact(kind, artifact);- try {- await dry.pushArtifact(kind, id);- } catch (err) {- if (!captured) throw err;- }- });- if (!captured) throw new Error('the push sent no create');- let path = '';- try { path = new URL(captured.url, conn.instanceUrl).pathname; } catch { /* checked below */ }- let body = captured.body;- if (typeof body === 'string') { try { body = JSON.parse(body); } catch { body = null; } }- if (captured.method !== 'post' || !path.toLowerCase().endsWith(`/${fam.collection}`) || !body || typeof body !== 'object' || Array.isArray(body)- || normalizeGuid(body[fam.idField]) !== normalizeGuid(id)) {- throw new Error(`the push's first write was not one create of ${id}`);- }- return body;-}-/*** The catalog intents of a spec's declared views and charts (creates-catalog.js shape). An entry without a table or a name is left* out: it does not compile, and the planner refuses it before any create.@@ -319,7 +269,7 @@ function createStableCreates({ spec, sdk, store = null, barrier = null, basePort}let expected;try {- expected = await expectedCreateBody(sdk, kind, id, artifact);+ expected = await expectedCreateBody(sdk, { kind, collection: FAMILY[kind].collection, idField: FAMILY[kind].idField, load: 'create' }, id, artifact);} catch (err) {refuse(`the create request the draft makes could not be worked out (${String((err && err.message) || err).slice(0, 200)})`);}diff --git a/plugins/model-apps/scripts/lib/dashboard-reconcile.js b/plugins/model-apps/scripts/lib/dashboard-reconcile.jsindex e2a1c19c4..172d8504d 100644--- a/plugins/model-apps/scripts/lib/dashboard-reconcile.js+++ b/plugins/model-apps/scripts/lib/dashboard-reconcile.js@@ -88,6 +88,12 @@ const {rulesOf,} = require('./reconcile-common.js');const { hasUnsyncedEdits } = require('./unsynced-edits.js');+const { readRetainedCopy } = require('./dashboard-recovery-workspace.js');+const { expectedCreateBody } = require('./create-request-body.js');+// Loaded lazily, by the one accessor below: reseedBag runs only for a declared dashboard's create, and a default build must not+// load the stable-identity modules (creates-port.test.js walks every require edge of the default build).+const identity = () => require('./creates-identity.js');+const { rootCreateAcknowledged: storeRootCreateAcknowledged, dashboardCreateAcknowledged } = require('./managed-bindings.js');const contract = require('./managed-feature-contract.js');const { runManagedFeature, publishManagedScope, CREATION_RECORD_UNSETTLED, PUBLICATION_UNVERIFIED, PUBLICATION_REFUSED } = contract;const { readSystemFormPublication, readSystemFormRootPresence, systemFormRootLayerSha256 } = require('./systemform-published.js');@@ -138,6 +144,10 @@ function stop(code, message, details = {}) {return Object.assign(new Error(message), { code }, details);}+// The maker's workspace SDK: the scope's source when the settle has a workspace scope (dashboard-recovery-workspace.js),+// whose `currentSdk` may be an isolated one; the settle's own SDK otherwise.+const sourceSdkOf = (s) => (s.workspaceScope && s.workspaceScope.sourceSdk) || s.sdk;+function isDeclaredDashboard(d) {return !!d && d.reconcile === 'declared';}@@ -774,7 +784,17 @@ function savedSnapshot(sdk, saved, key) {return { ...parsed, id: saved.formid, dashboardType: dashboardTypeOf(saved.type), entityLogicalName: parsed.entityLogicalName == null ? null : parsed.entityLogicalName };}-/** Replace the seed tab's and section's ids in the SDK's freshly generated local seed; throws on any other shape. */+/**+ * Replace the seed tab's and section's ids in the SDK's freshly generated local seed with the catalog's, and the id of+ * each cell the seed section holds with one derived from the section's id and its ordinal; throws on any other shape.+ *+ * Why the cells: the SDK's default dashboard layout mints a random id for its empty cell on every call, e.g.+ * section {4fc1...af09} > rows > row > cell [["id","{06f0c1b3-...-fb009c3dbbfa}"],["rowspan","12"],["colspan","2"],...]+ * then, from another call, cell [["id","{9b2e...}"], ...]+ * so the same declaration gave a different create draft on every run. A create's receipt pins the POST to the hash of+ * that whole draft, and a proven-unsent create continued by a later run must send the same one, so the id is derived+ * (UUIDv5 under the section's catalog id, as bpf-settlement.js settleControlIds derives its ControlIds) rather than kept.+ */function reseedBag(seedBag, tabId, sectionId) {const bag = JSON.parse(JSON.stringify(seedBag || {}));const found = { tab: [], section: [] };@@ -787,6 +807,17 @@ function reseedBag(seedBag, tabId, sectionId) {if (found.tab.length !== 1 || found.section.length !== 1) throw stop('dashboard-seed-unrecognized', 'the SDK seeded a dashboard layout this build does not recognize; nothing was sent');found.tab[0].a.find((p) => p[0] === 'id')[1] = braced(tabId);found.section[0].a.find((p) => p[0] === 'id')[1] = braced(sectionId);+ let n = 0;+ const rekeyCells = (el) => {+ if (!el || typeof el !== 'object') return;+ const idAttr = el.n === 'cell' ? (el.a || []).find((p) => Array.isArray(p) && p[0] === 'id') : null;+ if (idAttr) {+ idAttr[1] = braced(identity().uuidV5(normalizeGuid(sectionId), JSON.stringify(['dashboard-seed-cell', 1, n])));+ n += 1;+ }+ for (const child of el.c || []) rekeyCells(nodeOf(child));+ };+ rekeyCells(found.section[0]);return bag;}@@ -930,7 +961,9 @@ function intendedDashboard(s, r) {for (const { path, value } of captionEdits) setAtPointer(art, path, value);intended = readBack(adapter.fromArtifact(art));}- return { intended, captionEdits };+ // A create's complete local draft, as applyDashboard must assemble it in the workspace: the one its create receipt+ // pins the POST to (applyDashboard compares the assembled artifact with it, whole, before anything is sent).+ return { intended, captionEdits, ...(r.create ? { createDraft: JSON.parse(JSON.stringify(art)) } : {}) };} catch (err) {if (err && err.code === 'dashboard-seed-unrecognized') throw err;throw stop('dashboard-rejected', `the planned edit of dashboard "${s.key}" could not be written by the SDK; nothing was sent`, { cause: err });@@ -1005,17 +1038,64 @@ function requireOriginalDeclaration(key, { committed, pending }) {* such a copy is checked before the first one. `create-completion-required`, category `workspace-copy-unsent-edits`:* the maker saves the edit into the spec or discards the copy; an identical rerun stops the same way.* A copy the SDK cannot diff reads as edited (hasUnsyncedEdits fails open), so a doubtful copy is never dropped.+ * The one exception is this build's own create draft, retained when a run stopped after the service acknowledged+ * the create and before the SDK recorded it (retainedCreateDraft): with a workspace scope, the copy is left as it+ * is and the rest of the settle reads and writes through an isolated workspace (`s.sdk` from here on).*/async function preflightDashboard(s, { committed, pending }) {- const { key, sdk, dashboard, catalog } = s;+ const { key, dashboard, catalog } = s;+ // The maker's own workspace is the one inspected, even when an earlier preflight of this settle already isolated it.+ const sdk = sourceSdkOf(s);requireOriginalDeclaration(key, { committed, pending });if (s.retainedCreationIds.length) throw stop(CREATION_RECORD_UNSETTLED, `the creation record of dashboard "${key}" is not settled; it is not written or published in this run`);const ids = [committed && committed.root.id, pending && pending.root && pending.root.id, dashboard && dashboard.dashboardId, s.resolvedId];try { ids.push(catalog.identityFor(KIND, key).derivedId); } catch { /* not in the catalog: resolve stops it */ }+ let isolate = null;for (const id of [...new Set(ids.map(normalizeGuid).filter(Boolean))]) {- if (await hasUnsyncedEdits(sdk, KIND, id)) {+ if (!(await hasUnsyncedEdits(sdk, KIND, id))) continue;+ const draftSha256 = await retainedCreateDraft(s, id, { committed, pending });+ if (!draftSha256) {throw stop('create-completion-required', `the workspace copy of dashboard "${key}" holds edits that were never sent; save them into the spec or discard the copy before the build reconciles it`, { category: 'workspace-copy-unsent-edits', id });}+ isolate = { id, draftSha256 };+ }+ // The retained copy of this build's own acknowledged create is left exactly as it is: every SDK read and write of this+ // settle (and of its publish) goes through an isolated workspace from here on, over the same connection.+ if (isolate) {+ await s.workspaceScope.activateIsolated(isolate);+ s.sdk = s.workspaceScope.currentSdk;+ }+}++/**+ * Whether the edited workspace copy at `id` is this build's own create draft, retained because the run that sent it+ * stopped after the service acknowledged the create and before the SDK recorded it as synced. Answers the recorded+ * draft hash when it is, null otherwise (the caller's unsent-edits refusal stands). It is only when all of these hold:+ * - `id` is the pending attempt's root and that attempt durably recorded the create's acknowledgement (its receipt,+ * managed-bindings.js dashboardCreateAcknowledged), or the committed group's root created by this build, whose+ * record keeps the create evidence (`localCreateDraft`);+ * - the settle has a workspace scope to isolate the rest of its work in (a caller without one keeps the refusal);+ * - the SDK reads the copy locally and consistently, as a pending create or a synced copy (creates-local.js), and+ * the whole artifact hashes to the recorded draft hash. Nothing is normalised first: any change, even one the+ * create's serializer would drop, refuses.+ */+async function retainedCreateDraft(s, id, { committed, pending }) {+ const scope = s.workspaceScope;+ if (!scope || typeof scope.activateIsolated !== 'function' || typeof scope.assertSourceUnchanged !== 'function') return null;+ let recorded = null;+ if (pending && pending.root && normalizeGuid(pending.root.id) === id && dashboardCreateAcknowledged(pending)) {+ recorded = pending.dashboardCreate.draftSha256;+ } else if (committed && normalizeGuid(committed.root.id) === id) {+ const rootRec = committed.records.find((x) => x.kind === KIND && x.key === s.key);+ const marker = rootRec && rootRec.origin === 'created' ? rootRec.localCreateDraft : null;+ if (marker && normalizeGuid(marker.rootId) === id) recorded = marker.draftSha256;+ }+ if (!recorded) return null;+ try {+ const art = await readRetainedCopy(sourceSdkOf(s), id);+ return art && typeof art === 'object' && sha(art) === recorded ? recorded : null;+ } catch {+ return null;}}@@ -1192,14 +1272,14 @@ async function resolveDashboard(s, committed, pending) {async function withIntended(s, r) {if (!r.writes) return r;const tileLanguages = r.additions.length ? await tileCaptionLanguages(s) : null;- const { intended, captionEdits } = intendedDashboard(s, { ...r, tileLanguages });+ const { intended, captionEdits, createDraft } = intendedDashboard(s, { ...r, tileLanguages });const why = unpreservableSend(s, r, intended, plannedTiles(r));if (why) {const keys = r.entries.filter((e) => r.create || r.additions.includes(e) || (e.changed && e.changed.length)).map((e) => e.tileKey);const refusals = (keys.length ? keys : [s.key]).map((k) => ({ key: k, code: 'dashboard-layout-unsupported', message: `${why}; make this change in Maker` }));throw stop('dashboard-layout-unsupported', `declared dashboard "${s.key}": ${refusals.map((x) => `${x.key}: ${x.message}`).join('; ')}`, { refusals });}- return { ...r, tileLanguages, intended, captionEdits };+ return { ...r, tileLanguages, intended, captionEdits, ...(createDraft ? { createDraft } : {}) };}/** A dashboard no id names that is not there: it is created under its catalog id, every tile a catalog child of it. */@@ -1291,21 +1371,30 @@ function planDashboard(s, resolution, committed) {// very large dashboard is refused before its send rather than sent with a reservation too small for its completion.const COMPLETION_TILE_BYTES = 2048;const COMPLETION_FIXED_BYTES = 64 * 1024;+// A create's receipt (the attempt's `dashboardCreate`, about 330 bytes) and the create evidence its committed root keeps+// (`localCreateDraft`, about 300): fixed-width ids and hashes, with margin.+const COMPLETION_CREATE_EVIDENCE_BYTES = 2048;const COMPLETION_COPY_DEPTH = 8;function completionBound(s, entries, declaration) {const app = Buffer.byteLength(String((s.ctx && s.ctx.appUniqueName) || ''), 'utf8');- let bytes = COMPLETION_FIXED_BYTES;+ let bytes = COMPLETION_FIXED_BYTES + COMPLETION_CREATE_EVIDENCE_BYTES;for (const e of entries) bytes += COMPLETION_TILE_BYTES + 4 * (Buffer.byteLength(`${s.key}/${e.tileKey}`, 'utf8') + app);const text = JSON.stringify(declaration, null, 2);return bytes + Buffer.byteLength(text, 'utf8') + text.split('\n').length * 2 * COMPLETION_COPY_DEPTH;}-/** Send the planned change once: a create, or the edits and appends of an existing dashboard, in one push. */-async function applyDashboard(s, r) {+/**+ * Send the planned change once: a create, or the edits and appends of an existing dashboard, in one push.+ * A create sent through the build's gated, observed connection (the run's publication barrier gates it and the send+ * observer is installed on it) is receipted (createReceipted): the service's answer to the one create POST is recorded+ * in the binding store before the SDK sees it. Without that connection a create is sent as before, with no receipt.+ */+async function applyDashboard(s, r, { token = null, sendEpoch = null } = {}) {const { sdk, key } = s;const id = r.id;if (!r.writes) return { createdRoot: false, createdTiles: [] };let pushed;+ const receipted = r.create && receiptable(s, token, sendEpoch);try {if (r.create) {const art = await sdk.createArtifact(KIND, { name: s.dashboard.name, ...(r.description ? { description: r.description } : {}), id });@@ -1324,10 +1413,65 @@ async function applyDashboard(s, r) {if (err && err.code === 'dashboard-create-id-not-kept') throw err;throw stop(err && err.code === 'dashboard-seed-unrecognized' ? err.code : 'dashboard-rejected', `the edit of dashboard "${key}" was refused before it was sent`, { cause: err, rules: rulesOf(err) });}- pushed = r.create ? await pushChecked(sdk, KIND, id) : await pushIfChanged(sdk, KIND, id);+ let descriptor = false;+ if (receipted) {+ pushed = await createReceipted(s, r, { token, sendEpoch });+ descriptor = true;+ } else {+ pushed = r.create ? await pushChecked(sdk, KIND, id) : await pushIfChanged(sdk, KIND, id);+ }if (pushed.outcome === 'refused') throw stop('dashboard-rejected', `the edit of dashboard "${key}" was refused`, { rules: pushed.rules || [] });if (pushed.outcome === 'unknown') throw stop('dashboard-write-unknown', `the write of dashboard "${key}" did not report its outcome; check the dashboard`);- return { createdRoot: r.create, createdTiles: r.additions.map((e) => e.tileKey) };+ return { createdRoot: r.create, createdTiles: r.additions.map((e) => e.tileKey), ...(descriptor ? { descriptor: true } : {}) };+}++// Whether this create can be receipted: an installed send observer that scopes a create receipt, a barrier that gates the+// connection the push uses (so the create can be pinned to its body), the attempt's token and its send epoch. Without+// all of them the create is sent as before, with no receipt (and a lost answer stays a manual recovery).+function receiptable(s, token, sendEpoch) {+ const observer = s.sendObserver;+ const barrier = s.barrier;+ return !!(observer && typeof observer.withDashboardCreateReceipt === 'function' && observer.installed+ && barrier && typeof barrier.pinCreate === 'function' && typeof barrier.gatesTransport === 'function' && barrier.gatesTransport()+ && typeof token === 'string' && token && Number.isSafeInteger(sendEpoch) && sendEpoch > 0);+}++/**+ * The receipted create of a dashboard. In order:+ * 1. the artifact the workspace now holds must be, whole, the draft intendedDashboard modelled (`r.createDraft`): any+ * other content (an edit made to the copy meanwhile, an SDK assembly the model does not reproduce) is refused+ * before anything is sent (`create-local-draft-changed`);+ * 2. the body the SDK's push sends for that draft is worked out without sending it (create-request-body.js);+ * 3. the draft's and the body's hashes are recorded on the attempt (noteDashboardCreateDraft) before the POST;+ * 4. the create POST is pinned to exactly that body (a different body is refused with no request sent) and sent inside+ * the observer's receipt scope, which records its dispatch before it leaves and the service's answer before the SDK+ * sees it. A store failure there is raised as itself after the push, never read as the push's own outcome.+ */+async function createReceipted(s, r, { token, sendEpoch }) {+ const { sdk, key, store, barrier } = s;+ const id = r.id;+ const changed = (why, extra = {}) => stop('create-local-draft-changed', `the local copy of dashboard "${key}" is not the draft this build assembled (${why}); nothing was sent`, { id, ...extra });+ if (!r.createDraft || typeof r.createDraft !== 'object') throw changed('no draft was modelled');+ const local = await sdk.getArtifact(KIND, id);+ if (canonicalJson(local) !== canonicalJson(r.createDraft)) throw changed('the assembled copy differs from the modelled one');+ let body;+ try {+ body = await expectedCreateBody(sdk, { kind: KIND, collection: 'systemforms', idField: 'formid', load: 'write' }, id, r.createDraft);+ } catch (err) {+ throw changed('the body its create would send could not be worked out', { cause: err });+ }+ const want = canonicalJson(body);+ const bodySha256 = crypto.createHash('sha256').update(want).digest('hex');+ store.noteDashboardCreateDraft(token, { sendEpoch, rootId: id, draftSha256: sha(r.createDraft), bodySha256 });+ const pin = barrier.pinCreate({ collection: 'systemforms', idField: 'formid', id, matches: (b) => canonicalJson(b) === want });+ let pushed;+ try {+ pushed = await s.sendObserver.withDashboardCreateReceipt({ store, token, sendEpoch, rootId: id, bodySha256 }, () => pushChecked(sdk, KIND, id));+ } finally {+ pin.release();+ }+ if (pin.refused) throw changed('the create the push sent was not the one recorded');+ return pushed;}/**@@ -1408,11 +1552,16 @@ async function proveDashboard(s, expected, applied, { token = null, recovering =const created = expected.baseObservation === null;const { committed, pending } = store.readGroup(KIND, key);const attempt = recovering ? (pending && (!token || pending.token === token) ? pending : null) : null;- // The root create is acknowledged only by this run's own answer to its create, never by a read. A recovered- // attempt counts it only when the attempt itself durably recorded that acknowledgement before the run stopped.+ // The root create is acknowledged only by this build's own answer to its create, never by a read: the shared rule+ // (managed-bindings.js rootCreateAcknowledged) that consent and the commit apply too. A recovered attempt counts it+ // only when the attempt itself durably recorded that acknowledgement — its create receipt, or the saved answer —+ // before the run stopped. This run's receipted create (`applied.descriptor`) counts it only when the receipt was+ // recorded; a create sent without a receipt (no observed connection) counts this run's own answer, as before.+ const current = !recovering && applied && applied.descriptor && pending && token && pending.token === token ? pending : null;const rootCreateAcknowledged = recovering- ? created && !!attempt && (attempt.acknowledgedRoot === true || !!(attempt.savedObservation && attempt.savedObservation.acknowledgedRoot === true))- : !!(applied && applied.createdRoot);+ ? created && !!attempt && storeRootCreateAcknowledged(attempt)+ : applied && applied.descriptor ? created && !!current && storeRootCreateAcknowledged(current)+ : !!(applied && applied.createdRoot);const orphan = !created ? '': rootCreateAcknowledged? `. This build created dashboard ${id} and nothing binds it: delete it (in Maker, or by its id), then run the build again to create it anew`@@ -1525,8 +1674,9 @@ async function proveDashboard(s, expected, applied, { token = null, recovering =}return {savedProof: { savedSha256: savedSha },- // Acknowledged only by this run's own answer to its create: never on a recovery, never from a read.- acknowledgedRoot: !recovering && !!(applied && applied.createdRoot),+ // Acknowledged only by this build's own answer to its create (rootCreateAcknowledged above): never on a recovery,+ // never from a read. The store refuses it, too, for a receipted create whose receipt was not recorded.+ acknowledgedRoot: !recovering && rootCreateAcknowledged,records,proof: { savedSha256: savedSha, semanticSha256: semantic, preservationSha256: preserved, expectedChildrenSha256: expected.children.length ? sha(expected.children) : null },consumerState: {@@ -1557,7 +1707,12 @@ async function proveDashboard(s, expected, applied, { token = null, recovering =* ONLY consent to manage a dashboard this build did not create (a pin is not);* ensureMembership solution membership of the root ({ root, records, recovering });* sendObserver the build-wide send observer (managed-feature-contract.js createAttemptSendObserver, installed- * on the client every send goes through), or none: with it, an attempt proven unsent continues;+ * on the client every send goes through), or none: with it, an attempt proven unsent continues,+ * and a create sent through the barrier's gated connection is receipted (applyDashboard);+ * workspaceScope the dashboard workspace scope (dashboard-recovery-workspace.js withDashboardWorkspaceScope over+ * `sdk`), or none: with it, a workspace copy that is exactly this build's own acknowledged create+ * draft is kept as it is and the settle works in an isolated workspace instead+ * (preflightDashboard); without it such a copy stops as any other unsent edit does;* provisionedLanguages the organization's languages: an async function answering LCIDs (the build's* `() => readProvisionedLanguages(env)`, dataverse-auth.js) or the list itself. Read only when the* write creates a tile; without a usable answer such a write stops before it is sent;@@ -1582,6 +1737,11 @@ async function settleDeclaredDashboard(args) {const key = dashboardKey(dashboard);const s = {dashboard, key, catalog, sdk, store,+ // The run's publication barrier and the build's send observer, read by a create's receipt (applyDashboard), and the+ // workspace scope a retained create draft is isolated in (preflightDashboard); `s.sdk` becomes its isolated SDK then.+ barrier: args.barrier || null,+ sendObserver: args.sendObserver || null,+ workspaceScope: args.workspaceScope || null,resolveTile: args.resolveTile, toComponent: args.toComponent,retainedCreationIds: (args.retainedCreationIds || []).map(normalizeGuid).filter(Boolean),resolvedId: args.resolvedId || null,@@ -1628,9 +1788,15 @@ async function settleDeclaredDashboard(args) {s.lastPlan = planDashboard(s, r, committed);return s.lastPlan;},- apply: async ({ resolution: r }) => applyDashboard(s, r),+ apply: async ({ resolution: r, token, sendEpoch }) => applyDashboard(s, r, { token, sendEpoch }),prove: async ({ token, expected, applied, recovering, declaration }) => { id = expected.rootId; return proveDashboard(s, expected, applied, { token, recovering, declaration }); },- ensureMembership,+ // A retained create draft (preflightDashboard) must still be exactly as recorded when this settle binds: checked+ // before membership and again just before the commit. Neither claims a lock on the copy; it is never overwritten,+ // so a later edit survives and the next run sees it.+ ensureMembership: s.workspaceScope && typeof ensureMembership === 'function'+ ? async (...a) => { await s.workspaceScope.assertSourceUnchanged(); return ensureMembership(...a); }+ : ensureMembership,+ ...(s.workspaceScope ? { beforeCommit: async () => s.workspaceScope.assertSourceUnchanged() } : {}),});} catch (err) {// Second belt (the wrapper is the first): a dashboard that did not settle, whatever step failed, keeps every rowdiff --git a/plugins/model-apps/scripts/lib/dashboard-recovery-workspace.js b/plugins/model-apps/scripts/lib/dashboard-recovery-workspace.jsnew file mode 100644index 000000000..1dbc745d2--- /dev/null+++ b/plugins/model-apps/scripts/lib/dashboard-recovery-workspace.js@@ -0,0 +1,120 @@+'use strict';+// The workspace a declared dashboard's settle and publish read and write through, and the isolated one they move to when the+// maker's workspace holds this build's own create draft (dashboard-reconcile.js preflightDashboard).+//+// WHY ISOLATED, AND NOT A REFRESH OF THE COPY. A run can stop after the service acknowledged a dashboard's create (the receipt+// is in the binding store) and before the SDK recorded the copy as synced, so the next run finds the copy "edited". When that+// copy is, whole, exactly the draft the receipt was recorded for, the next run may recover the create. It must not do that by+// reading the copy's hash and then fetching over it (`fetchArtifact(..., { overwrite: true })`): another local writer can edit+// the copy between the two, and the build's lease does not exclude it. So the copy is never written: the settle (its reads,+// proof and any later write) and the publish run in a fresh workspace of their own, made through lib/maker-sdk.js over the+// SAME already-gated HTTP client, instance and language (and the solution header only if the source has one). No second+// auth client, retry budget, send observer or barrier is made. The isolated folder is removed when the callback ends; the+// maker's copy stays as it was, and refreshing it is left to the maker.+//+// await withDashboardWorkspaceScope({ sourceSdk: provision }, async (scope) => {+// const settled = await settleDeclaredDashboard({ ..., sdk: provision, workspaceScope: scope });+// await publishDeclaredDashboard({ ..., sdk: scope.currentSdk });+// });+const fs = require('node:fs');+const crypto = require('node:crypto');+const { makeTempWorkspace } = require('./temp-workspace.js');+const { canonicalJson } = require('./reconcile-common.js');+// Loaded lazily, by the one accessor below: only a declared dashboard's retained create copy is read through it, and a+// default build must not load the stable-identity modules creates-local.js depends on (creates-port.test.js).+const createsLocal = () => require('./creates-local.js');++const KIND = 'dashboard';++/**+ * The maker's copy at `id`, read only locally: a pending create's draft, or a synced copy with edits (the SDK does not+ * refresh a dirty copy on a read). Anything else — a clean copy, which a read could refresh over, none, or one the SDK+ * cannot read consistently — answers null (creates-local.js readLocalCreateState). preflightDashboard reads it the same way.+ */+async function localCopy(sdk, id) {+ const local = await createsLocal().readLocalCreateState(sdk, KIND, id);+ if (local.state === 'pending') return local.draft;+ if (local.state === 'synced' && local.dirty) return await sdk.getArtifact(KIND, id);+ return null;+}++const changedSource = (id) => Object.assign(new Error(`the local copy of dashboard ${id} changed while the build recovered its create; the copy was kept as it is and nothing was bound. Run the build again`), {+ code: 'create-completion-required',+ category: 'workspace-copy-unsent-edits',+ id,+});++/**+ * Runs `fn(scope)` with a dashboard workspace scope over `sourceSdk`, and removes the isolated workspace (only it) when+ * `fn` ends, however it ends. The scope:+ * sourceSdk the maker's workspace SDK, never written through once the scope is isolated;+ * currentSdk the SDK to work through: `sourceSdk` until activateIsolated, the isolated one after;+ * activateIsolated({ id, draftSha256 }) make the isolated SDK (once; later calls for the same id and hash answer it+ * again, another id or hash is refused) and record the source copy's draft hash;+ * assertSourceUnchanged() no-op before activation; after it, the source copy at `id` must still hash to `draftSha256`+ * (a local read: a dirty copy is never refreshed by the SDK), or it throws+ * `create-completion-required` (category `workspace-copy-unsent-edits`).+ * @param {{ sourceSdk: object, deps?: { makerSdk?: object } }} options+ * @param {(scope: object) => Promise<*>} fn+ */+async function withDashboardWorkspaceScope({ sourceSdk, deps = {} } = {}, fn) {+ if (!sourceSdk || typeof fn !== 'function') throw new TypeError('withDashboardWorkspaceScope needs the source SDK and a callback');+ let isolatedDir = null;+ let isolated = null;+ let recorded = null;+ const scope = {+ get sourceSdk() { return sourceSdk; },+ get currentSdk() { return isolated || sourceSdk; },+ get isolated() { return !!isolated; },+ async activateIsolated({ id, draftSha256 } = {}) {+ if (typeof id !== 'string' || !id || typeof draftSha256 !== 'string' || !/^[0-9a-f]{64}$/.test(draftSha256)) {+ throw new TypeError('activateIsolated needs the copy\'s id and its recorded draft hash');+ }+ if (recorded) {+ if (recorded.id !== id || recorded.draftSha256 !== draftSha256) throw new Error('the dashboard workspace scope is already isolated for another copy');+ return isolated;+ }+ const conn = sourceSdk.dataverse;+ if (!conn || typeof conn.instanceUrl !== 'string' || !conn.httpClient) throw new Error('the SDK exposes no connection to make an isolated workspace over');+ const dir = makeTempWorkspace('dashboard-recover-');+ try {+ const { createMakerSdk, createNodeWorkspaceStorage } = deps.makerSdk || require('./maker-sdk.js');+ const made = createMakerSdk({+ workspaceStorage: createNodeWorkspaceStorage(dir),+ instanceUrl: conn.instanceUrl,+ httpClient: conn.httpClient,+ ...(sourceSdk.languageCode !== undefined && sourceSdk.languageCode !== null ? { languageCode: sourceSdk.languageCode } : {}),+ // The solution header only when the source sends one: a header-less provision SDK must stay header-less.+ ...(typeof conn.solutionUniqueName === 'string' && conn.solutionUniqueName ? { solutionUniqueName: conn.solutionUniqueName } : {}),+ });+ await made.initWorkspace();+ isolated = made;+ isolatedDir = dir;+ } catch (err) {+ fs.rmSync(dir, { recursive: true, force: true });+ throw err;+ }+ recorded = { id, draftSha256 };+ return isolated;+ },+ async assertSourceUnchanged() {+ if (!recorded) return;+ const art = await localCopy(sourceSdk, recorded.id).catch(() => null);+ const hash = art && typeof art === 'object' ? crypto.createHash('sha256').update(canonicalJson(art)).digest('hex') : null;+ if (hash !== recorded.draftSha256) throw changedSource(recorded.id);+ },+ };+ try {+ return await fn(scope);+ } finally {+ if (isolatedDir) {+ try {+ fs.rmSync(isolatedDir, { recursive: true, force: true });+ } catch {+ // A folder that held only this build's isolated read must not turn a finished settle into a failure, or hide a failed one.+ }+ }+ }+}++module.exports = { withDashboardWorkspaceScope, readRetainedCopy: localCopy };diff --git a/plugins/model-apps/scripts/lib/declared-bpf-io.js b/plugins/model-apps/scripts/lib/declared-bpf-io.jsindex 514fe4af5..d209fff5e 100644--- a/plugins/model-apps/scripts/lib/declared-bpf-io.js+++ b/plugins/model-apps/scripts/lib/declared-bpf-io.js@@ -96,14 +96,17 @@ function verifyDeclaredBpf({ flow, group, art }) {* - the store keeps its original declaration, and it is a declared flow,* - a fresh read of its bound flow through `sdk` (the download's own throwaway SDK) answers,* - that read certifies the group's last proof (bpfProofIssues answers none),- * - every persona its securityRoles name is declared in the downloaded spec, which a download never writes, so a flow with- * securityRoles is always left out (personasNotIn), and+ * - every persona its securityRoles name is declared in the downloaded spec, or is read from its role and proved to rebuild+ * that role exactly with the flow's grants already on it (lib/persona-restore.js; then it is added to `spec.personas`), and* - the downloaded spec still validates with it (`validate`, the download's own validator).* Every other group (unread, changed since, not valid here, or still pending or unusable in the store) is answered in `stale` with- * its reason, never silently dropped. Answers { restored: [key], stale: [{ key, reason }] }; a store file that cannot be used- * throws `managed-manifest-unusable`.+ * its reason, never silently dropped. Answers { restored: [key], stale: [{ key, reason }], personas?: [{ name, flows: [key] }] },+ * `personas` only when one was written; a store file that cannot be used+ * throws `managed-manifest-unusable`. `fragments`, when given, is an array a stale flow is pushed onto (noteBpfFragment) when its+ * declaration is proved and left out only for the personas it names; the caller writes them to the fragments file+ * (lib/managed-fragments.js).*/-async function restoreManagedBpfs({ sdk, spec, file, environment, appUniqueName, solutionUniqueName, validate }) {+async function restoreManagedBpfs({ sdk, spec, file, environment, appUniqueName, solutionUniqueName, validate, fragments }) {const { groups, pending, invalid } = readManagedFormFile({ file, environment, appUniqueName, solutionUniqueName }, 'bpf');const restored = [];const stale = [@@ -112,6 +115,9 @@ async function restoreManagedBpfs({ sdk, spec, file, environment, appUniqueName,];if (!groups.size) return { restored, stale: sortByKey(stale) };const base = validate(spec);+ // The personas this download writes, by lower-cased name -> { name, flows }, and the prover that reads them (made at first need).+ const written = new Map();+ let prover = null;for (const key of [...groups.keys()].sort()) {const group = groups.get(key);const id = bareId(group.root && group.root.id);@@ -135,31 +141,78 @@ async function restoreManagedBpfs({ sdk, spec, file, environment, appUniqueName,const flows = Array.isArray(spec.businessProcessFlows) ? spec.businessProcessFlows : [];const at = flows.findIndex((f) => f && lc(f.entity) === lc(declaration.entity) && lc(f.name) === lc(declaration.name));const next = at >= 0 ? flows.map((f, i) => (i === at ? declaration : f)) : [...flows, declaration];- // A flow's securityRoles name personas of the spec it was built from, and a download writes no personas[]: a persona- // owns its role and the build converges that role onto exactly the privileges declared (ReplacePrivilegesRole), so a- // persona guessed from the environment would strip every privilege the guess missed on the next build. The flow is- // not restored without its roles either (that would drop authored intent), so it is left out with what to copy.+ // A flow's securityRoles name personas of the spec it was built from, and a persona is not a reference: the build OWNS+ // its role and converges it onto exactly the privileges declared (ReplacePrivilegesRole). So a persona the downloaded+ // spec lacks is written only when it is read from its role and PROVED to rebuild that role exactly, and the flow's grants+ // are already on it (lib/persona-restore.js). A persona this download wrote for an earlier flow needs this flow's grants+ // proved too. The flow is not restored without its roles either (that would drop authored intent): when any persona is+ // not proved, it is left out with what to copy.const missing = personasNotIn(spec, declaration);- if (missing.length) {- stale.push({ key, reason: `its securityRoles name ${missing.map((p) => `persona '${p}'`).join(', ')}, and a download writes no personas[]; copy this flow and the personas it names from the spec it was built from` });- continue;+ const own = personasWrittenFor(declaration, written);+ const add = [];+ if (missing.length || own.length) {+ prover = prover || require('./persona-restore.js').createPersonaProver({ sdk, appUniqueName, solutionUniqueName });+ // The flow is proved above, so its projection is readable; a throw here still only leaves the grants unproved.+ let backing = '';+ try { backing = settlement().projectBpf(art).uniqueName; } catch { /* flowGrantsMissing refuses an unknown table */ }+ const failed = [];+ // A name listed twice (in any case) is proved and written once: two entries would be a duplicate persona.+ const seen = new Set();+ for (const name of [...missing, ...own]) {+ if (seen.has(lc(String(name).trim()))) continue;+ seen.add(lc(String(name).trim()));+ const proof = await prover.prove(name);+ const why = proof.ok ? await prover.flowGrantsMissing(proof, backing) : proof.why;+ if (why) failed.push(`persona '${name}', which the download could not prove from its role: ${why}`);+ else if (missing.includes(name) && !add.some((p) => lc(p.name) === lc(proof.name))) add.push(proof);+ }+ if (failed.length) {+ const reason = `its securityRoles name ${failed.join('; ')}; copy this flow and the personas it names from the spec it was built from`;+ stale.push({ key, reason });+ noteBpfFragment(fragments, { key, reason, spec, declaration, next, missing, validate });+ continue;+ }}- const check = validate({ ...spec, businessProcessFlows: next });+ const personas = add.length ? [...(Array.isArray(spec.personas) ? spec.personas : []), ...add.map((p) => p.persona)] : null;+ const check = validate({ ...spec, ...(personas ? { personas } : {}), businessProcessFlows: next });if (!check || !check.ok) {const errors = ((check && check.errors) || []).slice(0, 3).map((x) => (typeof x === 'string' ? x : (x && x.message) || JSON.stringify(x)));stale.push({ key, reason: `its declaration does not validate in the downloaded spec (${errors.join('; ') || 'invalid'})` });continue;}spec.businessProcessFlows = next;+ if (personas) spec.personas = personas;+ for (const p of add) written.set(lc(p.name), { name: p.name, flows: [key] });+ for (const name of new Set(own.map((n) => lc(String(n).trim())))) written.get(name).flows.push(key);restored.push(key);}- return { restored, stale: sortByKey(stale) };+ const personas = [...written.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));+ return { restored, stale: sortByKey(stale), ...(personas.length ? { personas } : {}) };+}++// The personas a flow declaration's securityRoles name that this download wrote for an earlier flow (`written`, by lower-cased+// trimmed name), in declaration order.+function personasWrittenFor(declaration, written) {+ const named = declaration.securityRoles && Array.isArray(declaration.securityRoles.personas) ? declaration.securityRoles.personas : [];+ return named.filter((p) => written.has(lc(String(p).trim())));}function sortByKey(list) {return list.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));}+// A proved flow left out only for the personas its securityRoles name goes to the fragments file (lib/managed-fragments.js),+// ready to paste. "Only" is checked, not assumed: the spec must validate with the flow (`next`, the flows it would hold) and a+// stub for each missing persona. The stubs are never written. Without a collector nothing is noted.+function noteBpfFragment(fragments, { key, reason, spec, declaration, next, missing, validate }) {+ if (!Array.isArray(fragments)) return;+ const { stubPersona } = require('./managed-fragments.js');+ const personas = [...(Array.isArray(spec.personas) ? spec.personas : []), ...missing.map((p) => stubPersona(String(p).trim(), declaration.entity))];+ const check = validate({ ...spec, personas, businessProcessFlows: next });+ if (!check || !check.ok) return;+ fragments.push({ family: 'bpf', key, reason, needs: missing.map((p) => ({ persona: String(p).trim() })), paste: { businessProcessFlows: [declaration] } });+}+// The personas a flow declaration's securityRoles name that `spec.personas` does not declare, in declaration order,// matched as the spec validator matches them (app-spec.js: the trimmed persona name, case-insensitively).function personasNotIn(spec, declaration) {diff --git a/plugins/model-apps/scripts/lib/declared-form-io.js b/plugins/model-apps/scripts/lib/declared-form-io.jsindex 16c83fc92..8f7dcbbb2 100644--- a/plugins/model-apps/scripts/lib/declared-form-io.js+++ b/plugins/model-apps/scripts/lib/declared-form-io.js@@ -15,6 +15,7 @@ const path = require('node:path');const { discoverManagedStore, managedManifestView, readManagedManifest, isStoreEnvironment, storeFileName, CODES } = require('./managed-bindings.js');const { environmentFingerprint } = require('./page-ownership-records.js');const { hydrateDeclaredForm } = require('./form-layout-reconcile.js');+const { hasMoreOf } = require('./query-completeness.js');const FORM = 'form';// lib/dashboard-reconcile.js KIND; kept as a literal so verify's manifest read does not load the dashboard helper.@@ -130,14 +131,22 @@ async function readLiveForm(sdk, formId) {* - a fresh read of its bound form through `sdk` (the download's own throwaway SDK) answers,* - the form helper's hydrate (hydrateDeclaredForm) certifies it: the same id, type and table, every proved child where it was,* the layout, handlers and hosts exactly as the proof saw them; and+ * - every handler library the form names that the downloaded spec does not declare is downloaded with it (libraryEntry: this+ * publisher's own unmanaged script, declared `external`), all or none; and* - the downloaded spec still validates with it (`validate`, the download's own validator): a declaration naming a table, column* or sub-grid child the download did not carry would make the whole spec unwritable, so that one form is left out instead.* Every other group — unread, stale, not valid here, or still pending or unusable in the store — is answered in `stale` with its- * reason, never silently dropped. Answers { restored: [key], stale: [{ key, reason }] }; a store file that cannot be used throws.+ * reason, never silently dropped. Answers { restored: [key], stale: [{ key, reason }], libraries?: [{ name, forms: [key] }] }+ * (`libraries` only when one was downloaded); a store file that cannot be used throws. `publisher` is the download's+ * { prefix, resolved } (runDownload); without it no library is downloaded.+ * `fragments`, when given, is an array a stale form is pushed onto (noteFormFragment) when its declaration is proved and left out+ * only for the handler libraries it names; the caller writes them to the fragments file (lib/managed-fragments.js).*/-async function restoreManagedForms({ sdk, spec, file, environment, appUniqueName, solutionUniqueName, validate }) {+async function restoreManagedForms({ sdk, spec, file, environment, appUniqueName, solutionUniqueName, validate, fragments, publisher }) {const { groups, pending, invalid } = readManagedFormFile({ file, environment, appUniqueName, solutionUniqueName });const restored = [];+ const libraries = [];+ const libraryReads = new Map();const stale = [...pending.map((p) => ({ key: p.key, reason: `its last attempt is not settled (${p.code}); build again to settle it` })),...invalid.map((p) => ({ key: p.key, reason: `its stored record is not usable (${p.reason})` })),@@ -157,17 +166,131 @@ async function restoreManagedForms({ sdk, spec, file, environment, appUniqueName}const h = hydrateDeclaredForm(group, { formId, liveForm });if (!h.form) { stale.push({ key, reason: h.stale }); continue; }- const check = validate({ ...spec, forms: [...spec.forms, h.form] });+ // The handler libraries the form names and the spec does not declare: each is downloaded as the build would need it, or the+ // form is left out with why (all or nothing: a form is never restored with only some of its libraries).+ const wanted = librariesNotIn(spec, h.form);+ const libs = [];+ const refusals = [];+ for (const name of wanted) {+ const got = await libraryEntry(sdk, publisher, name, libraryReads);+ if (got.entry) libs.push(got.entry);+ else refusals.push(`its ${eventOf(h.form, name)} handler library '${name}' was not downloaded: ${got.why}`);+ }+ if (refusals.length) {+ const reason = refusals.join('; ');+ stale.push({ key, reason });+ noteFormFragment(fragments, { key, reason, spec, form: h.form, validate });+ continue;+ }+ const webResources = [...(Array.isArray(spec.webResources) ? spec.webResources : []), ...libs];+ const check = validate({ ...spec, ...(libs.length ? { webResources } : {}), forms: [...spec.forms, h.form] });if (!check || !check.ok) {const errors = ((check && check.errors) || []).slice(0, 3).map((x) => (typeof x === 'string' ? x : (x && x.message) || JSON.stringify(x)));- stale.push({ key, reason: `its declaration does not validate in the downloaded spec (${errors.join('; ') || 'invalid'})` });+ const reason = `its declaration does not validate in the downloaded spec (${errors.join('; ') || 'invalid'})`;+ stale.push({ key, reason });+ noteFormFragment(fragments, { key, reason, spec, form: h.form, validate });continue;}+ // The form and its libraries are committed together. A new array, so the list runDownload counted is not grown under it.+ if (libs.length) spec.webResources = webResources;+ for (const lib of libs) libraries.push({ name: lib.name, forms: [key] });spec.forms.push(h.form);restored.push(key);}stale.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));- return { restored, stale };+ return { restored, stale, ...(libraries.length ? { libraries } : {}) };+}++// The event a form handler names `library` on, for the reason a library was not downloaded.+function eventOf(form, library) {+ const folded = String(library).toLowerCase();+ const ev = (Array.isArray(form.events) ? form.events : []).find((e) => e && typeof e.library === 'string' && e.library.toLowerCase() === folded);+ return (ev && ev.event) || 'form';+}++/**+ * One handler library a restored form names, read from the environment and declared as a rebuild needs it, or why not.+ * The entry is `external: true`, as a path-referenced navigation icon's is (download-model-app.js iconWebResources): a build+ * reuses a library it finds without writing or comparing its content, creates it from this content only where it is missing,+ * and a teardown never deletes it. It is downloaded only when all of these hold, because each one is what makes that safe:+ * - exactly one row answers the name (Dataverse matches it without regard to letter case);+ * - the row is unmanaged (`ismanaged === false`; an absent flag is unknown, not unmanaged): a managed library belongs to a+ * managed solution, and a build must not create an unmanaged copy of it where that solution is missing;+ * - it is a script (webresourcetype 3, JScript), the only kind a form handler runs;+ * - it has content, so a rebuild where it is missing creates it whole;+ * - its name carries the app's own publisher prefix, read from the solution's publisher and verified (`publisher.resolved`):+ * a build creates a missing web resource under the spec's publisher, and a name under another prefix stops that build.+ * The read, as the platform answers it:+ * GET /webresourceset?$select=webresourceid,name,displayname,webresourcetype,content,ismanaged&$filter=name eq 'contoso_/scripts/item.js'&$top=2+ * { "value": [ { "webresourceid": "…", "name": "contoso_/scripts/item.js", "displayname": "Item script", "webresourcetype": 3,+ * "content": "dmFyIEl0ZW0g…", "ismanaged": false } ] }+ * `reads` caches each name's answer for the run, so two forms naming one library read it once.+ */+async function libraryEntry(sdk, publisher, name, reads) {+ const folded = String(name).toLowerCase();+ if (!reads.has(folded)) reads.set(folded, readLibrary(sdk, publisher, name));+ return reads.get(folded);+}++const JSCRIPT = 3;++async function readLibrary(sdk, publisher, name) {+ const prefix = publisher && publisher.resolved === true && typeof publisher.prefix === 'string' && publisher.prefix ? publisher.prefix.toLowerCase() : null;+ if (!prefix) return { why: 'the app\'s publisher prefix was not verified, so it is not known to be this publisher\'s' };+ if (!String(name).toLowerCase().startsWith(`${prefix}_`)) return { why: `its name does not carry this publisher's prefix '${prefix}_'` };+ let rows;+ try {+ rows = await sdk.queryRecords('webresource', {+ select: ['webresourceid', 'name', 'displayname', 'webresourcetype', 'content', 'ismanaged'],+ filter: `name eq '${String(name).replace(/'/g, "''")}'`,+ top: 2,+ });+ } catch (e) {+ return { why: `it could not be read (${(e && e.message) || e})` };+ }+ // One row read is proof of one row only on a complete answer. With `top: 2` the SDK reports `hasMore: true` when the+ // server names a next link (query-completeness.js), so more rows answer this name than were read; judge that on the+ // array the SDK returned, before any filter makes a copy that no longer carries the report.+ if (!Array.isArray(rows)) return { why: 'its lookup did not answer a list of rows' };+ if (hasMoreOf(rows) === true) return { why: 'its lookup was cut short, so it is not known to be the only web resource of its name' };+ const found = rows.filter((r) => r && typeof r.name === 'string' && r.name.toLowerCase() === String(name).toLowerCase());+ if (!found.length) return { why: 'it was not found' };+ if (found.length > 1) return { why: 'more than one web resource answers its name' };+ const row = found[0];+ if (row.ismanaged !== false) return { why: row.ismanaged === true ? 'it is managed' : 'whether it is managed is not known' };+ if (row.webresourcetype !== JSCRIPT) return { why: 'it is not a script' };+ if (typeof row.content !== 'string' || !row.content) return { why: 'it has no content' };+ return { entry: { name: row.name, ...(row.displayname ? { displayName: row.displayname } : {}), type: 'js', contentBase64: row.content, external: true } };+}++// The handler libraries a form's events name that `spec.webResources` does not declare, in event order, each once. Matched+// as the spec validator matches them (app-spec.js: the library name, case-insensitively).+function librariesNotIn(spec, form) {+ const declared = new Set((Array.isArray(spec.webResources) ? spec.webResources : []).map((w) => String((w && w.name) || '').toLowerCase()));+ const out = [];+ const seen = new Set();+ for (const ev of (Array.isArray(form && form.events) ? form.events : [])) {+ const name = ev && typeof ev.library === 'string' ? ev.library : '';+ const folded = name.toLowerCase();+ if (!name || declared.has(folded) || seen.has(folded)) continue;+ seen.add(folded);+ out.push(name);+ }+ return out;+}++// A proved form left out only for its handler libraries goes to the fragments file (lib/managed-fragments.js), ready to paste.+// "Only" is checked, not assumed: the spec must validate with the form and a stub for each missing library. The stubs are never+// written. Without a collector (a caller that keeps no fragments) nothing is noted.+function noteFormFragment(fragments, { key, reason, spec, form, validate }) {+ if (!Array.isArray(fragments)) return;+ const missing = librariesNotIn(spec, form);+ if (!missing.length) return;+ const { stubWebResource } = require('./managed-fragments.js');+ const webResources = [...(Array.isArray(spec.webResources) ? spec.webResources : []), ...missing.map(stubWebResource)];+ const check = validate({ ...spec, webResources, forms: [...spec.forms, form] });+ if (!check || !check.ok) return;+ fragments.push({ family: 'form', key, reason, needs: missing.map((name) => ({ webResource: name })), paste: { forms: [form] } });}module.exports = { readVerifyManifest, readManagedFormFile, readLiveForm, restoreManagedForms, committedUnits };diff --git a/plugins/model-apps/scripts/lib/entity-provision.js b/plugins/model-apps/scripts/lib/entity-provision.jsindex 07c8fb027..255a0cff9 100644--- a/plugins/model-apps/scripts/lib/entity-provision.js+++ b/plugins/model-apps/scripts/lib/entity-provision.js@@ -142,6 +142,12 @@ function localizedLabelLcidsInSpec(spec) {return [...byLcid.entries()].sort(([a], [b]) => a - b).map(([lcid, where]) => ({ lcid, where }));}+// Whether the entity carries any localized label: the one fact that decides whether an inconclusive existence probe of its table may be+// settled by the broad, label-bearing table list (findExistingTable). Every caller that probes a table the build may go on to create asks it here.+function entityHasLocalizedLabels(entity) {+ return localizedLabelLcidsInSpec({ entities: [entity] }).length > 0;+}+// Halt when a LOCALIZED label names a language the organization has not provisioned. AB#6686428.//// This is NOT a validation nicety — it is the difference between the feature working and the feature@@ -2679,7 +2685,7 @@ async function settleOwedLengths({ sdk, provision, spec, owed, warn, sleep } = {// `owed` is the Map provisionDataModel keeps (see there): this attempt's tables whose length is to be set, and those an earlier attempt// left unset. `carriedIn` is the set of the second kind as the phase found them; `waitingKeys` collects the alternate keys that wait for// a length step, for createWaitingKeys to make once the steps have run.-async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, languageCode, warn, provisionedLanguages, preResolvedLanguageCode, sleep, reconcileLookupLabels = false, inlineColumns = true, dateBehaviorPreflight = false, authorizedDestructive, publicationBarrier, createdTables }, { owed, carriedIn, waitingKeys, waitingStatuses, lag }) {+async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, languageCode, warn, provisionedLanguages, preResolvedLanguageCode, sleep, reconcileLookupLabels = false, inlineColumns = true, dateBehaviorPreflight = false, authorizedDestructive, publicationBarrier, createdTables, localizedLabelsChecked = false }, { owed, carriedIn, waitingKeys, waitingStatuses, lag }) {// `lookupLabels` records the label each spec lookup column carries once this phase is done// (`<referencing>|<lookup logical>` -> { label }), so a later phase that repairs something derived// from it — an existing form's cell label — repairs it to what the column now says.@@ -2695,8 +2701,10 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la// Before any write: refuse a localized label naming a language this org has not provisioned.// Dataverse would accept it and silently keep only the provisioned label (live-measured), so this- // must run ahead of the first createTable rather than as a post-hoc verify.- await checkLocalizedLabelLanguages(spec, provisionedLanguages);+ // must run ahead of the first createTable rather than as a post-hoc verify. A caller that also creates the+ // publisher and the solution checks earlier still, before those (runSdkBuildPhases, provisionEntities), and+ // says so with `localizedLabelsChecked`, so the language list is read once.+ if (!localizedLabelsChecked) await checkLocalizedLabelLanguages(spec, provisionedLanguages);const globalChoiceIds = result.globalChoiceIds;// The declared tables (lower-case logical names) this run found already in the environment, as opposed@@ -2735,7 +2743,7 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la// Whether THIS entity carries any localized label. It decides whether an inconclusive existence// probe may be resolved by the broad `findTables` read — safe for a plain-label entity, poisoning// for a localized one. See findExistingTable.- const entityIsLocalized = localizedLabelLcidsInSpec({ entities: [e] }).length > 0;+ const entityIsLocalized = entityHasLocalizedLabels(e);const hits = await findExistingTable(provision, e.schemaName, {hasLocalizedLabels: entityIsLocalized, includeKeys: !!(e.alternateKeys && e.alternateKeys.length),});@@ -2830,6 +2838,15 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, launprovenTables.add(logical);}}, { recoverable: true });+ // A table found only after its create was answered "already exists" has its columns read now, as one the first lookup found does:+ // the Date and Time guard below picks the declared repairs from them, so an authorized repair is made (and a refused one stops the+ // build) BEFORE a column is added, in this build, and a column the table has is not sent again. The read is the same narrow one, and+ // an unreadable answer leaves every declared column looking new, as before. A table that declares no column has nothing the read+ // decides, so it is not read.+ if (foundAfterCreate && buildable.length) {+ existingColRows = await findExistingColumns(provision, logical, warn);+ existingCols = new Set(existingColRows.map((c) => String(c.logicalName || c.schemaName || '').toLowerCase()));+ }}// The primary name column's length, when the spec asks for one: one narrated step in every case (the plan counts it). For a// table this build created the step is queued here and runs at the end of the phase (provisionDataModel) — a label-bearing@@ -3041,7 +3058,7 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la// already existed (reconcileColumnSecurity). A secured column is secured in this phase, before any sample row is written. Never on a// Customer column (validation refuses it: updateColumn refuses every change to one), and the required and capability updates above// never carry it. A Lookup column is reconciled after the relationships that create it.- const securityTargets = existingTable ? new Set([...existingCols, ...skippedExisting]) : skippedExisting;+ const securityTargets = (existingTable || foundAfterCreate) ? new Set([...existingCols, ...skippedExisting]) : skippedExisting;await reconcileColumnSecurity({ sdk, provision, runner, name: e.schemaName, logical, columns: buildable.filter((c) => c.type !== 'Customer'), targets: securityTargets, authorizedDestructive });for (const c of requiredDeclared) {if (existingTable && existingCols.has(c.schemaName.toLowerCase())) continue;@@ -3764,4 +3781,4 @@ async function provisionSampleData({ sdk, provision, runner, spec, dataModel })return { records: result.records, entitySetFor };}-module.exports = { makeRunner, mapLimit, runBestEffort, requireSuccessfulPush, pushFailed, reportPartialPush, errorCodeChain, RESET_WORKSPACE, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, settleOwedLengths, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, DEFAULT_MAX_SIZE_KB, isVisualizationUnsupported, ALREADY_EXISTS_CODES, localizedLabelLcidsInSpec, checkLocalizedLabelLanguages, findExistingTable, findExistingColumns, relationshipExists, lookupsWithDefaultLabel, relationshipsInCreateOrder, statusReasonTargets };+module.exports = { makeRunner, entityHasLocalizedLabels, mapLimit, runBestEffort, requireSuccessfulPush, pushFailed, reportPartialPush, errorCodeChain, RESET_WORKSPACE, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, settleOwedLengths, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, DEFAULT_MAX_SIZE_KB, isVisualizationUnsupported, ALREADY_EXISTS_CODES, localizedLabelLcidsInSpec, checkLocalizedLabelLanguages, findExistingTable, findExistingColumns, relationshipExists, lookupsWithDefaultLabel, relationshipsInCreateOrder, statusReasonTargets };diff --git a/plugins/model-apps/scripts/lib/form-caption-diagnostics.js b/plugins/model-apps/scripts/lib/form-caption-diagnostics.jsnew file mode 100644index 000000000..4fc4100fe--- /dev/null+++ b/plugins/model-apps/scripts/lib/form-caption-diagnostics.js@@ -0,0 +1,141 @@+'use strict';++// form-caption-diagnostics.js — name the form cells whose caption reads one way in a form's saved layer and another+// way in its published layer, for the message of a publish that a fresh read did not prove live.+//+// DIAGNOSTIC ONLY. This module decides nothing. Its answer is never hashed, never compared for a publication decision,+// never written to the binding store, and never makes a publish confirmed. A saved layer has no version, so the same+// observed pair — saved "Inspections", published "Issues" in one cell — is what a platform read that projects the two+// layers apart shows AND what a maker's unpublished caption edit shows; nothing read here tells them apart. The answer+// only tells the maker WHERE to look. Every caller treats a throw or an unusable answer as "no diagnostic"+// (systemform-published.js readSystemFormLayers, managed-feature-contract.js), so nothing here can change a stop.+//+// What is compared, in each layer's form XML (strict-xml.js; a document it does not read answers no diagnostic):+// <tab id="{…}"> … <section id="{…}"> … <cell id="{0f3c…}">+// <labels><label description="Inspections" languagecode="1033" /></labels>+// <control id="subgrid_inspections" … />+// </cell>+// A cell is matched across the layers by its id (a GUID, in any spelling) only — never by its caption, its position or+// a name — and only when the tab and section that contain it and the control it holds have the same ids in both+// layers. Within a matched cell, a caption is compared only for a language code that has exactly ONE label on each+// side; a language present on one side only is not reported (no base language is inferred from label order). Any+// ambiguity — a cell id twice in one layer, a language code twice in one cell, a language code that is not a whole+// number — answers no diagnostic at all rather than a guess.++const { readXmlElements } = require('./strict-xml.js');+const { normalizeGuid } = require('./reconcile-common.js');++// The most entries an answer names; the rest are counted (`omittedCount`). A message names a handful of cells.+const MAX_ENTRIES = 8;+// A form's XML is tens of kilobytes; a document far beyond that is not read for a diagnostic.+const MAX_XML_CHARS = 8 * (1 << 20);+const WANTED = new Set(['tab', 'section', 'cell', 'control', 'label']);+// A Windows locale id (LCID) as Dataverse writes `languagecode`, e.g. "1033" (English) or "3082" (Spanish).+// See: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-lcid/+const LCID = /^[1-9]\d{3,4}$/;++class Ambiguous extends Error {}++// An element id as compared across the layers: a GUID in its normalized spelling, any other id as written, or null.+const idOf = (attrs) => {+ const raw = attrs && typeof attrs.id === 'string' ? attrs.id : null;+ if (raw === null) return null;+ return normalizeGuid(raw) || raw;+};++// The cells of one layer: Map<cellId, { tab, section, controls, captions: Map<lcid, description> }>, or null when the+// document is not read. Elements are answered in document order (by their start), so one pass with a stack of the+// open tab / section / cell elements finds the innermost container of each element in linear time.+function cellsOf(xml) {+ if (typeof xml !== 'string' || xml.length > MAX_XML_CHARS) return null;+ const read = readXmlElements(xml, (name) => WANTED.has(name), { spans: true });+ if (!read.ok) return null;+ const cells = new Map();+ const stack = [];+ const innermost = (name) => {+ for (let i = stack.length - 1; i >= 0; i -= 1) if (stack[i].el.name === name) return stack[i];+ return null;+ };+ for (const el of read.elements) {+ while (stack.length && stack[stack.length - 1].el.end <= el.start) stack.pop();+ const top = stack.length ? stack[stack.length - 1] : null;+ if (el.name === 'tab' || el.name === 'section') {+ stack.push({ el, id: idOf(el.attrs) });+ } else if (el.name === 'cell') {+ const cellId = normalizeGuid(el.attrs.id);+ const tab = innermost('tab');+ const section = innermost('section');+ const entry = { el, id: cellId, tab: tab ? tab.id : null, section: section ? section.id : null, controls: [], captions: new Map() };+ if (cellId) {+ if (cells.has(cellId)) throw new Ambiguous();+ cells.set(cellId, entry);+ }+ stack.push(entry);+ } else if (top && top.el.name === 'cell' && top.id) {+ // Only what sits directly in the cell: its own control, and the labels of its own <labels> element.+ if (el.name === 'control' && el.path.endsWith('/cell')) top.controls.push(idOf(el.attrs));+ if (el.name === 'label' && el.path.endsWith('/cell/labels')) {+ const code = el.attrs.languagecode;+ if (typeof code !== 'string' || !LCID.test(code)) throw new Ambiguous();+ const lcid = Number(code);+ if (top.captions.has(lcid)) throw new Ambiguous();+ top.captions.set(lcid, typeof el.attrs.description === 'string' ? el.attrs.description : null);+ }+ }+ }+ return cells;+}++const sameControls = (a, b) => a.length === b.length && a.every((c, i) => c === b[i]);++/**+ * The cells whose caption in one language reads differently in `savedXml` and `publishedXml`:+ * { entries: [{ cellId: '<normalized GUID>', languageCode: 1033 }], omittedCount: 0 }+ * sorted by cell id then language code, at most MAX_ENTRIES named. Answers null when there is no such cell, or when+ * either document is not read or anything in it is ambiguous (see the header). No caption text is answered.+ */+function cellCaptionDifferences(savedXml, publishedXml) {+ let saved;+ let published;+ try {+ saved = cellsOf(savedXml);+ published = cellsOf(publishedXml);+ } catch (e) {+ if (e instanceof Ambiguous) return null;+ throw e;+ }+ if (!saved || !published) return null;+ const found = [];+ for (const [cellId, s] of saved) {+ const p = published.get(cellId);+ if (!p || s.tab !== p.tab || s.section !== p.section || !sameControls(s.controls, p.controls)) continue;+ for (const [lcid, text] of s.captions) {+ if (p.captions.has(lcid) && p.captions.get(lcid) !== text) found.push({ cellId, languageCode: lcid });+ }+ }+ if (!found.length) return null;+ found.sort((a, b) => (a.cellId < b.cellId ? -1 : a.cellId > b.cellId ? 1 : a.languageCode - b.languageCode));+ return { entries: found.slice(0, MAX_ENTRIES), omittedCount: Math.max(0, found.length - MAX_ENTRIES) };+}++/**+ * The sentence a stop appends for `differences` (cellCaptionDifferences' answer), e.g.+ * Caption difference at cell 0f3c…-… (language 1033). This observation does not show whether the difference is an+ * unpublished edit or a platform read projection.+ * Answers null for anything that is not such an answer.+ */+function formatCaptionDifferences(differences) {+ if (!differences || typeof differences !== 'object' || !Array.isArray(differences.entries) || !differences.entries.length) return null;+ const { entries, omittedCount } = differences;+ if (entries.length > MAX_ENTRIES || !Number.isSafeInteger(omittedCount) || omittedCount < 0) return null;+ const named = [];+ for (const e of entries) {+ if (!e || normalizeGuid(e.cellId) !== e.cellId || !Number.isSafeInteger(e.languageCode) || !LCID.test(String(e.languageCode))) return null;+ named.push(`cell ${e.cellId} (language ${e.languageCode})`);+ }+ const more = omittedCount ? `, and ${omittedCount} more` : '';+ const plural = named.length + omittedCount > 1;+ return `Caption difference${plural ? 's' : ''} at ${named.join(', ')}${more}. This observation does not show whether the difference is an unpublished edit or a platform read projection.`;+}++module.exports = { cellCaptionDifferences, formatCaptionDifferences, MAX_CAPTION_DIFFERENCES: MAX_ENTRIES };diff --git a/plugins/model-apps/scripts/lib/managed-bindings.js b/plugins/model-apps/scripts/lib/managed-bindings.jsindex eedf29c91..d40fe28e7 100644--- a/plugins/model-apps/scripts/lib/managed-bindings.js+++ b/plugins/model-apps/scripts/lib/managed-bindings.js@@ -436,7 +436,9 @@ function validateProof(proof, where) {}function validateRecord(rec, header, where) {- closedKeys(rec, ['formatVersion', 'appUniqueName', 'environmentFingerprint', 'kind', 'key', 'id', 'intentSha256', 'origin', 'parentKey', 'partsSha256'], where);+ // `localCreateDraft` is placed only by the store (commitGroup) and only on a created dashboard root; validateGroup+ // checks where it sits (validateLocalCreateDraft).+ closedKeys(rec, ['formatVersion', 'appUniqueName', 'environmentFingerprint', 'kind', 'key', 'id', 'intentSha256', 'origin', 'parentKey', 'partsSha256', 'localCreateDraft'], where);if (rec.formatVersion !== 1) throw invalid(where, 'has an unknown format');if (rec.appUniqueName !== header.appUniqueName || rec.environmentFingerprint !== header.environmentFingerprint) throw invalid(where, 'belongs to another app or environment');if (!nonempty(rec.kind) || !nonempty(rec.key)) throw invalid(where, 'has no kind or key');@@ -553,6 +555,7 @@ function validateGroup(g, header, where) {if (!nonempty(g.proofSchema)) throw invalid(where, 'names no proof schema');validateRecords(g.records, g.root, header, `${where}.records`);if (!g.records.some((r) => r.kind === g.root.kind && r.key === g.root.key)) throw invalid(where, 'holds no record of its root');+ g.records.forEach((r, i) => { if (r.localCreateDraft !== undefined) validateLocalCreateDraft(g, r, `${where}.records[${i}].localCreateDraft`); });validateProof(g.proof, `${where}.proof`);closedKeys(g.consumerState, CONSUMER_KEYS[g.family], `${where}.consumerState`);validateConsumerValue(g.consumerState, `${where}.consumerState`);@@ -565,8 +568,56 @@ function validateGroup(g, header, where) {validatePublication(g.publication, g.family, `${where}.publication`);}+// A dashboard create's durable receipt, kept on its attempt (noteDashboardCreateDraft / Dispatch / Answer), e.g.+// { formatVersion: 1, rootId: '<guid>', sendEpoch: 1, draftSha256: '<64 hex>', bodySha256: '<64 hex>',+// dispatchToken: null | '<uuid>', acknowledged: false }+// draftSha256 is the canonical hash of the whole local artifact the build assembled and sent; bodySha256 that of the+// create request body it produced. The hashes canonicalize object-key order only: the XML strings inside are compared+// byte for byte. `acknowledged` is true only once the observed transport saw a successful answer to that exact POST.+// It is valid only on a create of a new dashboard root, after its send window was armed, under the window's epoch.+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;+const DASHBOARD_CREATE_KEYS = ['formatVersion', 'rootId', 'sendEpoch', 'draftSha256', 'bodySha256', 'dispatchToken', 'acknowledged'];+function validateDashboardCreate(a, where) {+ const d = a.dashboardCreate;+ closedKeys(d, DASHBOARD_CREATE_KEYS, where);+ for (const k of DASHBOARD_CREATE_KEYS) if (!Object.prototype.hasOwnProperty.call(d, k)) throw invalid(where, `has no ${k}`);+ if (d.formatVersion !== 1) throw invalid(where, 'has an unknown format');+ if (a.family !== 'dashboard') throw invalid(where, 'is kept on an attempt that is not a dashboard\'s');+ guidField(d.rootId, `${where}.rootId`);+ if (d.rootId !== a.root.id) throw invalid(where, 'names another root than its attempt');+ if (a.baseGeneration !== null || !a.expected || a.expected.baseProofSha256 !== null || a.expected.baseObservation !== null) throw invalid(where, 'is kept on an attempt that is not a create of a new root');+ if (a.phase === 'prepared') throw invalid(where, 'is kept on an attempt never marked sending');+ if (!a.sendWindow || !Number.isSafeInteger(d.sendEpoch) || d.sendEpoch < 1 || d.sendEpoch !== a.sendWindow.epoch) throw invalid(where, 'is not under its attempt\'s send epoch');+ hashOrNull(d.draftSha256, `${where}.draftSha256`, false);+ hashOrNull(d.bodySha256, `${where}.bodySha256`, false);+ if (d.dispatchToken !== null && !(typeof d.dispatchToken === 'string' && UUID_RE.test(d.dispatchToken))) throw invalid(`${where}.dispatchToken`, 'is not a dispatch token');+ if (typeof d.acknowledged !== 'boolean') throw invalid(where, 'has no acknowledged flag');+ if (d.acknowledged && d.dispatchToken === null) throw invalid(where, 'is acknowledged without a dispatch');+ // An older acknowledgement on the same attempt is only ever the receipt's own: it cannot stand beside an+ // unacknowledged receipt.+ if ((a.acknowledgedRoot || (a.savedObservation && a.savedObservation.acknowledgedRoot)) && !d.acknowledged) throw invalid(where, 'is unacknowledged under an attempt that says its root was acknowledged');+}++// The create evidence a committed dashboard root keeps (commitGroup mints it from an acknowledged receipt and keeps it+// on every later generation of the same root): { formatVersion: 1, rootId, attemptToken, draftSha256, bodySha256 }.+// Only the root record of a dashboard group, with origin `created`, may carry it.+const LOCAL_CREATE_DRAFT_KEYS = ['formatVersion', 'rootId', 'attemptToken', 'draftSha256', 'bodySha256'];+function validateLocalCreateDraft(g, rec, where) {+ const m = rec.localCreateDraft;+ closedKeys(m, LOCAL_CREATE_DRAFT_KEYS, where);+ for (const k of LOCAL_CREATE_DRAFT_KEYS) if (!Object.prototype.hasOwnProperty.call(m, k)) throw invalid(where, `has no ${k}`);+ if (m.formatVersion !== 1) throw invalid(where, 'has an unknown format');+ if (g.family !== 'dashboard' || rec.kind !== g.root.kind || rec.key !== g.root.key) throw invalid(where, 'is kept on a record that is not a dashboard root');+ if (rec.origin !== 'created') throw invalid(where, 'is kept on a root this build did not create');+ guidField(m.rootId, `${where}.rootId`);+ if (m.rootId !== g.root.id || rec.id !== g.root.id) throw invalid(where, 'names another root');+ if (typeof m.attemptToken !== 'string' || !UUID_RE.test(m.attemptToken)) throw invalid(`${where}.attemptToken`, 'is not an attempt token');+ hashOrNull(m.draftSha256, `${where}.draftSha256`, false);+ hashOrNull(m.bodySha256, `${where}.bodySha256`, false);+}+function validateAttempt(a, where) {- closedKeys(a, ['family', 'key', 'token', 'baseGeneration', 'phase', 'root', 'knownScopes', 'declarationSha256', 'declaration', 'expected', 'acknowledgedRoot', 'acknowledgedChildCreates', 'savedObservation', 'publication', 'sendWindow', 'completionReserve'], where);+ closedKeys(a, ['family', 'key', 'token', 'baseGeneration', 'phase', 'root', 'knownScopes', 'declarationSha256', 'declaration', 'expected', 'acknowledgedRoot', 'acknowledgedChildCreates', 'savedObservation', 'publication', 'sendWindow', 'completionReserve', 'dashboardCreate'], where);// The completion reservation (prepareAttempt; see COMPLETION_BASE_BYTES), e.g. { bytes: 434176, used: 1290 }. Absent// on an attempt an older build prepared: it holds nothing until a new send under it acquires one (markSending, as an// admission); an attempt already sent with none (read-only recovery, a commit) uses only unreserved bytes.@@ -622,6 +673,7 @@ function validateAttempt(a, where) {if (!Number.isSafeInteger(a.sendWindow.epoch) || a.sendWindow.epoch < 1) throw invalid(`${where}.sendWindow.epoch`, 'is not an epoch');if (a.phase === 'prepared') throw invalid(where, 'has a send window but was never marked sending');}+ if (a.dashboardCreate !== undefined) validateDashboardCreate(a, `${where}.dashboardCreate`);}// The workflow effects the attempt `a` owns.@@ -671,6 +723,9 @@ function fulfilInto(e, observedState, observedVersion) {function attemptProvenUnsent(a, effects) {if (!a || a.phase !== 'sending' || !a.expected) return false;if (a.acknowledgedRoot || a.savedObservation !== null) return false;+ // An acknowledged dashboard create landed: it never continues, whatever the counts say. A dispatched one that was not+ // acknowledged is judged by the counts like any mutation (its dispatch was counted; only a not-started answer lowers it).+ if (a.dashboardCreate && a.dashboardCreate.acknowledged) return false;const w = a.sendWindow;if (!w || w.possible !== 0) return false;return ownedEffects(a, effects).every((x) => (x.state === 'definitely-unsent' || x.state === 'fulfilled') && x.dispatchToken === null);@@ -699,8 +754,43 @@ function resumableCreate(group, a, effects) {* re-makes a committed group's vanished root under its stable id carries the committed proof as its base.*/function rootCreateAcknowledged(a) {- if (!a || !(a.acknowledgedRoot || (a.savedObservation && a.savedObservation.acknowledgedRoot))) return false;- return !!a.expected && a.expected.baseObservation === null;+ if (!a || !a.expected || a.expected.baseObservation !== null) return false;+ if (a.acknowledgedRoot || (a.savedObservation && a.savedObservation.acknowledgedRoot)) return true;+ return dashboardCreateAcknowledged(a);+}++/**+ * Did the observed transport durably receipt a successful answer to this attempt's own dashboard create+ * (noteDashboardCreateAnswer), under the attempt's current send epoch? A receipt is about the exact POST of the root it+ * names, on an attempt that creates a new root; it says the row was created, never what it holds now.+ */+function dashboardCreateAcknowledged(a) {+ const d = a && a.dashboardCreate;+ if (!isObj(d) || a.family !== 'dashboard' || d.acknowledged !== true || d.dispatchToken === null) return false;+ if (a.baseGeneration !== null || !a.expected || a.expected.baseObservation !== null || a.expected.baseProofSha256 !== null) return false;+ return d.rootId === a.root.id && !!a.sendWindow && a.sendWindow.epoch === d.sendEpoch;+}++/**+ * May the attempt take the early-receipt absence branch (runManagedFeature: a dashboard create whose answer was receipted,+ * read absent by its id in both layers, then sent again under the same root)? Only a receipted create of a new root that+ * nothing has committed or saved yet, with no owned workflow effect still open. Unlike resumableCreate it admits the+ * create's own counted send: the receipt says it landed, and the absence read says the row is gone since.+ */+function dashboardCreateResumable(group, a, effects) {+ if (group || !a || a.phase !== 'sending' || a.savedObservation !== null || a.acknowledgedRoot) return false;+ if (!dashboardCreateAcknowledged(a)) return false;+ return ownedEffects(a, effects).every((x) => x.state === 'confirmed' || x.state === 'fulfilled');+}++// What an early-receipt absence read was made against (observeDashboardCreateResume, then markSending `resumeObservation`):+// the group, the attempt and its key's workflow effects, as for a retirement (retirementObservation).+const DASHBOARD_CREATE_RESUME = /^dashboard-create-resume-v1:[0-9a-f]{64}$/;+function dashboardCreateResumeObservation(env, family, key) {+ const group = env.groups.find((x) => x.family === family && x.key === key) || null;+ const attempt = env.attempts.find((x) => x.family === family && x.key === key) || null;+ const effects = env.workflowEffects.filter((e) => e.family === family && e.key === key);+ return `dashboard-create-resume-v1:${sha256(canonicalJson({ family, key, group, attempt, effects }))}`;}// The child-create receipt of an attempt: [{ kind, key, id }], each a child its expected proof named under that same@@ -1450,14 +1540,19 @@ function openManagedBindings({ workspaceDir, environment, appUniqueName, solutio* a new obligation (every other reservation and the shared reserve kept free). A refusal (`managed-binding-store-full`)* writes nothing and comes before the send: the attempt, its phase, window, token and hold stay as they were.*/- markSending(token, expected, { observed = false, claim, completionBytes } = {}) {+ markSending(token, expected, { observed = false, claim, completionBytes, resumeObservation } = {}) {if (claim !== undefined && claim !== 'first' && claim !== 'continue' && claim !== 'resume') throw storeError(CODES.notSettled, `markSending cannot claim an attempt to "${claim}"`);+ if (resumeObservation !== undefined && (claim !== 'resume' || typeof resumeObservation !== 'string' || !DASHBOARD_CREATE_RESUME.test(resumeObservation))) {+ throw storeError(CODES.notSettled, 'markSending takes resumeObservation only with claim "resume", as observeDashboardCreateResume answered it');+ }checkCompletionBytes(completionBytes, 'markSending `completionBytes`');let epoch = null;// Written before the send, with the expected proof, so a refusal here comes before the send. An attempt whose// reservation is already adequate spends it, so content written since its prepare cannot strand it unsent.mutate((env, disk, spend, admitHere) => {const a = requireAttempt(env, disk, token);+ // Taken before anything below changes `env`: the observation is of the file as it was reread under the lease.+ const observedNow = resumeObservation !== undefined ? dashboardCreateResumeObservation(env, a.family, a.key) : null;if (a.expected !== null && canonicalJson(a.expected) !== canonicalJson(expected)) {throw storeError(CODES.completion, 'a sent attempt keeps the expected proof it was sent with');}@@ -1472,7 +1567,16 @@ function openManagedBindings({ workspaceDir, environment, appUniqueName, solutio}if (claim === 'first' && a.phase !== 'prepared') throw storeError(CODES.pending, `${name} attempt was marked sending by another run`);if (claim === 'continue' && !(observed === true && attemptProvenUnsent(a, env.workflowEffects))) throw storeError(CODES.pending, `${name} attempt no longer shows that nothing it sent was carried out; it is not sent again`);- if (claim === 'resume' && !resumableCreate(group, a, env.workflowEffects)) throw storeError(CODES.pending, `${name} attempt is no longer a create no answer acknowledged; it is not sent again`);+ if (claim === 'resume' && resumeObservation !== undefined) {+ // The early-receipt branch: a receipted dashboard create read absent in both layers since `resumeObservation`.+ // Anything that moved since (a send counted, a receipt, a commit) may have put the row back after that read.+ if (!(observed === true && dashboardCreateResumable(group, a, env.workflowEffects))) throw storeError(CODES.pending, `${name} attempt is no longer a receipted create that may be sent again; it is not sent again`);+ if (observedNow !== resumeObservation) throw storeError(CODES.conflict, `${name} changed since its root was read absent; it is not sent again in this run`);+ } else if (claim === 'resume') {+ if (!resumableCreate(group, a, env.workflowEffects)) throw storeError(CODES.pending, `${name} attempt is no longer a create no answer acknowledged; it is not sent again`);+ // A receipted create is resumed only through its fenced branch above.+ if (dashboardCreateAcknowledged(a)) throw storeError(CODES.pending, `${name} create was acknowledged; it is sent again only after a fenced absence read`);+ }const need = completionReserveFor(a.declaration, completionBytes, name);if (!a.completionReserve || a.completionReserve.bytes < need) {a.completionReserve = { bytes: need, used: a.completionReserve ? a.completionReserve.used : 0 };@@ -1486,6 +1590,9 @@ function openManagedBindings({ workspaceDir, environment, appUniqueName, solutioif (observed === true) a.sendWindow = { possible: 0, notStarted: 0, epoch: 1 };} else if ((claim === 'continue' || claim === 'resume') && a.sendWindow) {a.sendWindow.epoch += 1;+ // The receipt follows the epoch in the same write: the new send has neither dispatched nor been answered, and+ // an answer to an older epoch's POST never acknowledges it. The root and the draft and body hashes stay.+ if (a.dashboardCreate) Object.assign(a.dashboardCreate, { sendEpoch: a.sendWindow.epoch, dispatchToken: null, acknowledged: false });}epoch = a.sendWindow ? a.sendWindow.epoch : null;});@@ -1523,6 +1630,89 @@ function openManagedBindings({ workspaceDir, environment, appUniqueName, solutioa.sendWindow.notStarted += 1;});},+ /**+ * Record, before the create POST of a new dashboard root leaves, what it sends (the receipt's immutable part):+ * `rootId`, `draftSha256` (the whole local artifact the build assembled, as canonical JSON) and `bodySha256` (the+ * create request body it produces), under the send epoch markSending answered. Only for an attempt marked sending+ * with an observed window at that epoch, creating a new root (no committed group, no base). A repeated call in the+ * same epoch must name the same root and hashes; an attempt whose receipt is kept never takes other ones.+ * Refusals write nothing: `managed-settlement-pending` (another epoch), `create-completion-required` (other hashes),+ * `managed-not-settled` (not such an attempt).+ */+ noteDashboardCreateDraft(token, { sendEpoch, rootId, draftSha256, bodySha256 } = {}) {+ const root = normalizeGuid(rootId);+ if (!root || !HEX64.test(String(draftSha256)) || !HEX64.test(String(bodySha256)) || !Number.isSafeInteger(sendEpoch) || sendEpoch < 1) {+ throw storeError(CODES.notSettled, 'noteDashboardCreateDraft needs the send epoch, the root id and the draft and body hashes');+ }+ mutate((env, disk, spend) => {+ const a = requireAttempt(env, disk, token);+ spend(token);+ const name = `the managed ${a.family} "${a.key}"`;+ const group = env.groups.find((g) => g.family === a.family && g.key === a.key) || null;+ if (a.family !== 'dashboard' || group || a.baseGeneration !== null || !a.expected || a.expected.baseProofSha256 !== null || a.expected.baseObservation !== null) {+ throw storeError(CODES.notSettled, `${name} is not a create of a new dashboard root; it keeps no create receipt`);+ }+ if (a.phase !== 'sending' || a.savedObservation !== null || !a.sendWindow) throw storeError(CODES.notSettled, `${name} is not being sent under an observed window`);+ if (a.sendWindow.epoch !== sendEpoch) throw storeError(CODES.pending, `${name} attempt was claimed by another run since this send began; nothing is sent`);+ if (root !== a.root.id) throw storeError(CODES.notSettled, `${name} creates ${a.root.id}, not ${root}`);+ const d = a.dashboardCreate;+ if (d) {+ if (d.sendEpoch !== sendEpoch || d.rootId !== root || d.draftSha256 !== draftSha256 || d.bodySha256 !== bodySha256) {+ throw storeError(CODES.completion, `${name} keeps the draft and body its create was sent with; another one is not sent under it`);+ }+ return;+ }+ a.dashboardCreate = { formatVersion: 1, rootId: root, sendEpoch, draftSha256, bodySha256, dispatchToken: null, acknowledged: false };+ });+ },+ /**+ * The observed transport, synchronously before the exact create POST of the receipt leaves (createAttemptSendObserver+ * withDashboardCreateReceipt): the receipt's dispatch token, minted once per epoch and kept by a retry of that same+ * POST. Answers { dispatchToken }. Grants no acknowledgement and lowers no count. A refusal leaves the POST unsent.+ */+ noteDashboardCreateDispatch(token, { sendEpoch, bodySha256 } = {}) {+ let dispatchToken = null;+ mutate((env, disk, spend) => {+ const a = requireAttempt(env, disk, token);+ spend(token);+ const d = a.dashboardCreate;+ if (!d) throw storeError(CODES.notSettled, `the managed ${a.family} "${a.key}" keeps no create receipt to dispatch`);+ if (!a.sendWindow || a.sendWindow.epoch !== sendEpoch || d.sendEpoch !== sendEpoch) throw storeError(CODES.pending, `the managed ${a.family} "${a.key}" attempt was claimed by another run since this send began; the request is not sent`);+ if (d.bodySha256 !== bodySha256) throw storeError(CODES.completion, `the managed ${a.family} "${a.key}" create body is not the one its receipt was recorded for; it is not sent`);+ if (d.dispatchToken === null) d.dispatchToken = newToken();+ dispatchToken = d.dispatchToken;+ });+ return { dispatchToken };+ },+ /**+ * The observed transport, after a successful answer to the exact POST it dispatched (`dispatchToken`), before the+ * answer is handed back: the receipt is acknowledged. Idempotent. It is not a save: no phase, saved observation,+ * group or hold changes. A refusal (another epoch, dispatch or body) acknowledges nothing.+ */+ noteDashboardCreateAnswer(token, { sendEpoch, dispatchToken, bodySha256 } = {}) {+ mutate((env, disk, spend) => {+ const a = requireAttempt(env, disk, token);+ spend(token);+ const d = a.dashboardCreate;+ if (!d || d.dispatchToken === null || d.dispatchToken !== dispatchToken) throw storeError(CODES.notSettled, `the managed ${a.family} "${a.key}" answer is not to the create its receipt dispatched`);+ if (!a.sendWindow || a.sendWindow.epoch !== sendEpoch || d.sendEpoch !== sendEpoch) throw storeError(CODES.pending, `the managed ${a.family} "${a.key}" attempt was claimed by another run since this send began; its answer acknowledges nothing`);+ if (d.bodySha256 !== bodySha256) throw storeError(CODES.notSettled, `the managed ${a.family} "${a.key}" answer is to another create body`);+ d.acknowledged = true;+ });+ },+ /**+ * Before the early-receipt branch reads its root by id in both layers: rereads the file and answers { observation },+ * a fingerprint of the group, the attempt and the key's workflow effects. Hand it to markSending (`claim: 'resume'`,+ * `resumeObservation`), which refuses when anything changed since. As for observeRetirement: never observe again to+ * get past a refusal in the same invocation. Writes nothing.+ */+ observeDashboardCreateResume({ family, key } = {}) {+ if (family !== 'dashboard' || !nonempty(key)) throw storeError(CODES.notSettled, 'observeDashboardCreateResume needs a dashboard key');+ handle.refresh();+ const unit = usable(unitOf(state, family, key));+ if (!unit.attempt) throw storeError(CODES.notSettled, `the managed ${family} "${key}" has no attempt to resume`);+ return { observation: dashboardCreateResumeObservation(state.envelope, family, key) };+ },/*** Record what an acknowledged answer to this attempt's send proved, under its token, before anything else uses it:* proof the saved observation (feature-owned plain data);@@ -1549,6 +1739,11 @@ function openManagedBindings({ workspaceDir, environment, appUniqueName, solutioif (acknowledgedRoot === true && a.expected.baseObservation !== null) {throw storeError(CODES.notSettled, `the managed ${a.family} "${a.key}" edited an existing root; an answer to an edit never acknowledges a create`);}+ // A create sent under a receipt is acknowledged by the receipt alone: an SDK result (saved, adopted, a no-op)+ // that the observed transport did not receipt never makes the root this build's creation.+ if (acknowledgedRoot === true && a.dashboardCreate && !dashboardCreateAcknowledged(a)) {+ throw storeError(CODES.notSettled, `the managed ${a.family} "${a.key}" create has no receipt of its answer; nothing else acknowledges it`);+ }const receipt = (a.acknowledgedChildCreates || []).map((c) => ({ ...c }));try {for (const c of acknowledgedChildCreates) {@@ -1633,9 +1828,19 @@ function openManagedBindings({ workspaceDir, environment, appUniqueName, solutioif (!old && !acknowledged && adoptionApproved !== true) {throw storeError(CODES.adoptionRequired, `the managed ${a.family} "${a.key}" root was never acknowledged as created; binding it needs its adoption approval`);}+ // The create evidence of a dashboard root is the store's to mint and keep, never a caller's to propose: a record+ // read back from the group and handed in again may carry it, but only exactly as the store keeps it on that root+ // in this commit (checked below); it is set from the store's own, never from the caller's.+ const echoedMarkers = [];+ const proposed = (records || []).map((rec) => {+ if (rec.localCreateDraft === undefined) return rec;+ const { localCreateDraft, ...rest } = rec;+ echoedMarkers.push({ kind: rec.kind, key: rec.key, marker: localCreateDraft });+ return rest;+ });const merged = [];const byKey = new Map();- for (const rec of records || []) byKey.set(`${rec.kind}\u0000${rec.key}`, rec);+ for (const rec of proposed) byKey.set(`${rec.kind}\u0000${rec.key}`, rec);for (const rec of old ? old.records : []) {const k = `${rec.kind}\u0000${rec.key}`;const next = byKey.get(k);@@ -1662,6 +1867,22 @@ function openManagedBindings({ workspaceDir, environment, appUniqueName, solutio}const rootRec = merged.find((r) => r.kind === a.root.kind && r.key === a.root.key);if (!rootRec || String(rootRec.id).toLowerCase() !== a.root.id) throw storeError(CODES.completion, `the managed ${a.family} "${a.key}" root was not observed under its expected id`);+ // The created dashboard root's create evidence: minted from this attempt's acknowledged receipt, or kept from+ // the generation before for the same root. Never carried to another root, and gone with a retired group.+ const oldRoot = old ? old.records.find((r) => r.kind === a.root.kind && r.key === a.root.key) : null;+ let marker = null;+ if (oldRoot && oldRoot.localCreateDraft && String(oldRoot.id).toLowerCase() === a.root.id) marker = clone(oldRoot.localCreateDraft);+ else if (!old && dashboardCreateAcknowledged(a)) {+ const d = a.dashboardCreate;+ marker = { formatVersion: 1, rootId: a.root.id, attemptToken: a.token, draftSha256: d.draftSha256, bodySha256: d.bodySha256 };+ }+ const kept = marker && rootRec.origin === 'created' ? marker : null;+ if (kept) merged[merged.indexOf(rootRec)] = { ...rootRec, localCreateDraft: kept };+ for (const e of echoedMarkers) {+ if (!(kept && e.kind === a.root.kind && e.key === a.root.key && canonicalJson(e.marker) === canonicalJson(kept))) {+ throw storeError(CODES.groupInvalid, `a managed group commit was refused before it was written: the proposed ${e.kind} "${e.key}" carries create evidence only the store records`);+ }+ }for (const child of a.expected.children) {const got = merged.find((r) => r.kind === child.kind && r.key === child.key);if (!got || String(got.id).toLowerCase() !== String(child.id).toLowerCase()) throw storeError(CODES.completion, `the managed ${a.family} "${a.key}" lacks the expected ${child.kind} "${child.key}"`);@@ -2308,6 +2529,8 @@ module.exports = {attemptProvenUnsent,resumableCreate,rootCreateAcknowledged,+ dashboardCreateAcknowledged,+ dashboardCreateResumable,publicationRiskApproval,publicationRemedy,blockedPublication,diff --git a/plugins/model-apps/scripts/lib/managed-feature-contract.js b/plugins/model-apps/scripts/lib/managed-feature-contract.jsindex a0f31a72e..030298f7a 100644--- a/plugins/model-apps/scripts/lib/managed-feature-contract.js+++ b/plugins/model-apps/scripts/lib/managed-feature-contract.js@@ -31,8 +31,10 @@// Nothing calls this module until a declared form, dashboard, rule or process flow is wired to it.const { runWithWorkflowEffect } = require('./workflow-effect-context.js');-const { CODES, classifyPersisted, attemptProvenUnsent, resumableCreate, checkDeclaration, checkCompletionBytes, rootCreateAcknowledged, publicationRiskApproval, publicationRemedy, blockedPublication } = require('./managed-bindings.js');-const { canonicalJson } = require('./reconcile-common.js');+const { AsyncLocalStorage } = require('node:async_hooks');+const crypto = require('node:crypto');+const { CODES, classifyPersisted, attemptProvenUnsent, resumableCreate, dashboardCreateResumable, checkDeclaration, checkCompletionBytes, rootCreateAcknowledged, publicationRiskApproval, publicationRemedy, blockedPublication } = require('./managed-bindings.js');+const { canonicalJson, normalizeGuid } = require('./reconcile-common.js');const { LAYER_READERS } = require('./managed-layer-readers.js');const PUBLICATION_UNVERIFIED = 'managed-publication-unverified';@@ -62,6 +64,26 @@ const UNCERTAIN_PUBLICATION = new Set(['dispatching', 'unconfirmed']);// then owed again, and a later publish of it can stop the same way.const LAYERS_READ_APART = 'its saved layer is still the one the publish shipped, yet the published layer reads differently: either the publish did not put it live, or the platform reads this artifact\'s saved and published layers apart (seen on an adopted form whose sub-grid caption in the base language reads one way saved and another published), and no read can tell which. In the maker, compare what is published with the spec: if it matches, accept the risk with the publication-risk approval this build prints; a later publish of it can stop the same way while its two layers read apart';+// The words a LAYERS_READ_APART stop appends for the reads (`[{ family, key, captionDifferences }]`) whose reader named+// the cells and languages whose captions differ (systemform-published.js readSystemFormLayers), e.g.+// . managed form "account/main": Caption difference at cell 0f3c… (language 1033). This observation does not show …+// or '' — always '' when nothing usable can be said. The stop's message, code, remedy and data are built before this+// and never depend on it: a formatter that throws, is missing or answers anything but non-empty text adds nothing.+function captionDifferencesNote(reads, names) {+ try {+ const { formatCaptionDifferences } = require('./form-caption-diagnostics.js');+ const parts = [];+ for (const r of reads) {+ if (r.captionDifferences === undefined) continue;+ const text = formatCaptionDifferences(r.captionDifferences);+ if (typeof text === 'string' && text && text.length <= 2048) parts.push(`${names([r])}: ${text}`);+ }+ return parts.length ? `. ${parts.join(' ')}` : '';+ } catch {+ return '';+ }+}+function codedError(code, message, extra) {return Object.assign(new Error(message), { code }, extra || {});}@@ -141,7 +163,10 @@ const REQUIRED_STEPS = new Set(['preflight', 'resolve', 'plan', 'prove', 'member* (acknowledgedRoot false). The commit then records the new declaration as* `originalDeclaration` under a new generation, through the same checks, with* no effect. A no-op plan keeps the committed declaration as it is;- * apply({ token, plan, resolution, resuming?, continuing? }) send the approved change once; answers what it sent.+ * apply({ token, plan, resolution, sendEpoch, resuming?, continuing? }) send the approved change once; answers what+ * it sent. `sendEpoch` is the epoch THIS send's markSending answered (null without an+ * observer): a feature that keeps a create receipt (withDashboardCreateReceipt) records it+ * under that epoch, never under one it rereads (a newer claimant's).* With a sendObserver, every mutation it makes must go through the observed transport;* prove({ token, expected, applied, recovering, declaration }) a fresh read against `expected`; answers { savedProof,* acknowledgedRoot, acknowledgedChildCreates?, records, proof, consumerState,@@ -161,6 +186,10 @@ const REQUIRED_STEPS = new Set(['preflight', 'resolve', 'plan', 'prove', 'member* the authored input to compare against; the answered consumerState is the feature's* own derived state and is committed as answered;* ensureMembership({ root, records, recovering }) solution membership, for a clean reused root too;+ * beforeCommit?() optional: run after membership and before the commit, on a send and on every recovery.+ * A throw is a required failure (quarantined, the attempt and its hold kept, nothing+ * committed). The dashboard feature checks here that the retained local copy it worked+ * around is still the one it read (lib/dashboard-recovery-workspace.js);* sendObserver? the build's createAttemptSendObserver, already wrapped around its transport (refused* otherwise). markSending then arms the attempt's send window and `apply` runs inside it,* so an attempt whose window shows nothing carried out (a local failure before any@@ -180,6 +209,12 @@ const REQUIRED_STEPS = new Set(['preflight', 'resolve', 'plan', 'prove', 'member* the attempt recorded (root, expected proof, declaration hash, publication; otherwise* `create-completion-required`), and `apply` sends the same create under the same token.* Its failure, or any other answer, quarantines like a failed proof.+ * A dashboard create whose answer the observer receipted (dashboardCreateResumable: no+ * committed group, no saved observation) is asked too, with a send observer, after the+ * store fingerprinted the group (observeDashboardCreateResume): present is proved as+ * above, needing no adoption approval (the receipt acknowledges the create); absent sends+ * the same create again only through markSending `claim: 'resume'` with that fingerprint,+ * refused when anything changed since, and never retried with a new one in this run.* A pending attempt still `prepared` (never marked sending) met by a no-op plan is retired with* store.retireUnsentAttempt and its hold ends; a store that refuses it stops the build with the hold kept.* Answers { result, committedGroup }: result is { noop: true } or { committed: true, recovered, resumed?, continued? }.@@ -194,6 +229,8 @@ async function runManagedFeature(args) {if (typeof fn !== 'function') throw codedError(CODES.notSettled, `runManagedFeature needs ${name}`);}if ('adoptionApproved' in args && typeof args.adoptionApproved !== 'boolean') throw codedError(CODES.notSettled, 'runManagedFeature takes adoptionApproved only as a boolean the feature derives from its own adoption approval');+ if (args.beforeCommit !== undefined && typeof args.beforeCommit !== 'function') throw codedError(CODES.notSettled, 'runManagedFeature takes beforeCommit only as a function');+ const beforeCommit = args.beforeCommit || null;const adoptionApproved = args.adoptionApproved === true;if (!store || typeof store.readGroup !== 'function') throw codedError(CODES.notSettled, 'runManagedFeature needs the managed binding store');// A send observer that is not on the transport would arm windows nothing counts in, and an unsent-looking window is@@ -334,7 +371,22 @@ async function runManagedFeature(args) {const out = await sendAgain(committed, pending, 'continuing', 'was declared differently since its change was prepared; it is not sent');return { result: { committed: true, recovered: true, continued: true }, committedGroup: out };}- if (typeof args.resumeCreate === 'function' && resumableCreate(committed, pending, effects)) {+ // A dashboard create whose answer the observer durably receipted: its own branch, ahead of resumableCreate, which+ // stays the rule for creates no answer acknowledged. The store is fingerprinted BEFORE the root is read by id, and+ // markSending admits the resend only against that fingerprint, under its lease: a run that raced this one, or a+ // receipt that changed, is refused there and not observed again in this invocation.+ if (family === 'dashboard' && observer && typeof args.resumeCreate === 'function' && dashboardCreateResumable(committed, pending, effects)) {+ step = 'resume';+ const { observation } = store.observeDashboardCreateResume({ family, key });+ const seen = await args.resumeCreate({ token, pending, expected: pending.expected });+ const root = seen && seen.root;+ if (root !== 'absent' && root !== 'present') throw codedError(CODES.notSettled, `${label}: resumeCreate answered neither "absent" nor "present" for its root`);+ if (root === 'absent') {+ const out = await sendAgain(committed, pending, 'resuming', 'was declared differently since its create was sent; it is not resent', { resumeObservation: observation });+ return { result: { committed: true, recovered: true, resumed: true }, committedGroup: out };+ }+ // Present: proved below; the receipt is the acknowledgement requireAdoptionConsent reads.+ } else if (typeof args.resumeCreate === 'function' && resumableCreate(committed, pending, effects)) {step = 'resume';const seen = await args.resumeCreate({ token, pending, expected: pending.expected });const root = seen && seen.root;@@ -350,6 +402,7 @@ async function runManagedFeature(args) {requireAdoptionConsent(!!committed);step = 'membership';await ensureMembership({ root: pending.root, records: proved.records, recovering: true });+ if (beforeCommit) await beforeCommit();step = 'commit';const group = commit(store, token, pending.baseGeneration, proved, adoptionApproved);barrier.release(token);@@ -357,7 +410,7 @@ async function runManagedFeature(args) {}// Resolve and plan again under `flag` ('continuing' / 'resuming'), require the plan the attempt recorded, send it.- async function sendAgain(committed, pending, flag, differs) {+ async function sendAgain(committed, pending, flag, differs, claimExtra = {}) {// The attempt was planned against the committed generation it recorded; anything else committed since is a// different base, and the change is not sent over it.step = 'resolve';@@ -367,21 +420,26 @@ async function runManagedFeature(args) {const planned = await plan({ resolution, committed, [flag]: true });if (!samePlan(planned, pending)) throw codedError(CODES.completion, `${label} ${differs}`);checkCompletionBytes(planned.completionBytes, `${label}: plan \`completionBytes\``);- return send(planned, resolution, pending.baseGeneration, flag);+ return send(planned, resolution, pending.baseGeneration, flag, claimExtra);}// Persist the expected proof, send once, prove from a fresh read, ensure membership, commit, end the hold. With a send// observer, markSending arms the attempt's send window and `apply` runs inside it: every mutation that reaches the// transport is counted on the attempt before it leaves, so a later run can tell a send that never left from one that// may have landed (recoverManagedAttempt).- async function send(planned, resolution, baseGeneration, flag = null) {+ async function send(planned, resolution, baseGeneration, flag = null, { resumeObservation } = {}) {step = 'send';// The claim on the attempt's sends, made against the record the store rereads under its lease: a second run on the// same attempt, or one whose zero went stale while it resolved and planned, is refused here, before anything leaves.const claim = flag === 'continuing' ? 'continue' : flag === 'resuming' ? 'resume' : 'first';// The plan's estimate goes with the claim: an attempt whose reservation is smaller (or absent, an older build's)// acquires the rest here, admitted under the lease, or the send is refused before anything leaves.- const marked = store.markSending(token, planned.expected, { observed: !!observer, claim, ...(planned.completionBytes !== undefined ? { completionBytes: planned.completionBytes } : {}) });+ const marked = store.markSending(token, planned.expected, {+ observed: !!observer, claim,+ ...(planned.completionBytes !== undefined ? { completionBytes: planned.completionBytes } : {}),+ ...(resumeObservation !== undefined ? { resumeObservation } : {}),+ });+ const sendEpoch = marked && Number.isSafeInteger(marked.epoch) ? marked.epoch : null;// The declaration the attempt recorded before this send (prepareAttempt), as the store now holds it: the one prove// is given (the store commits it as the group's originalDeclaration). An attempt an earlier build prepared recorded// none; prove is then given the plan's.@@ -390,7 +448,7 @@ async function runManagedFeature(args) {const window = observer ? observer.open(store, token, marked && marked.epoch !== undefined ? marked.epoch : null) : null;let applied;try {- applied = await apply({ token, plan: planned, resolution, ...(flag ? { [flag]: true } : {}) });+ applied = await apply({ token, plan: planned, resolution, sendEpoch, ...(flag ? { [flag]: true } : {}) });} finally {// Trailing, not ended: a request `apply` left in flight, or a re-send of one, is still counted on the attempt.if (window) window.close();@@ -406,6 +464,7 @@ async function runManagedFeature(args) {requireAdoptionConsent(baseGeneration !== null);step = 'membership';await ensureMembership({ root: planned.root, records: proved.records, recovering: false });+ if (beforeCommit) await beforeCommit();step = 'commit';const group = commit(store, token, baseGeneration, proved, adoptionApproved);// The attempt is gone from the store: nothing of it is left to count.@@ -577,6 +636,67 @@ function notStartedAnswer(req, res) {return NOT_STARTED_WITH_CODE.has(res.statusCode) && dataverseErrorCode(res.body) !== null;}+// --- dashboard create receipts (withDashboardCreateReceipt) ---------------------------------------------------------------+const plainGuid = (value) => normalizeGuid(value) || null;+const sha256Hex = (text) => crypto.createHash('sha256').update(text, 'utf8').digest('hex');++// A request or answer body as a JSON object, or null: makeRequest carries text (a string or a Buffer); an object is taken+// as it is. An array, a scalar or text that does not parse is null.+function jsonObjectOf(body) {+ let value = body;+ try {+ if (Buffer.isBuffer(body)) value = JSON.parse(body.toString('utf8'));+ else if (typeof body === 'string') value = JSON.parse(body);+ } catch {+ return null;+ }+ return value && typeof value === 'object' && !Array.isArray(value) && !Buffer.isBuffer(value) ? value : null;+}++// Is `req` the receipt's own create? Only a direct POST to the systemforms collection (no `$batch`, the path read as the+// service reads it: canonicalOperationPath) whose body names the root in `formid` and hashes to the recorded body, e.g.+// POST https://contoso.crm.dynamics.com/api/data/v9.2/systemforms+// {"formid":"0b7c…","name":"Declared Dashboard","type":0,"objecttypecode":"none","formxml":"<form …>",…}+function receiptOwns(scope, req) {+ const path = canonicalOperationPath(req && req.url);+ if (path === null || /\$batch/i.test(path) || !/\/systemforms\/?$/i.test(path)) return false;+ const body = jsonObjectOf(req.body);+ if (!body || plainGuid(body.formid) !== scope.rootId) return false;+ return sha256Hex(canonicalJson(body)) === scope.bodySha256;+}++// Did the service answer the create as made? The raw transport's answer (makeRequest: { statusCode, headers, body }, with+// `error` / `incompleteResponse` on a cut-off one): 200, 201 or 204, complete; an empty body, or a JSON object with no+// `error` whose `formid`, if any, is the root; an `OData-EntityId` header, if any, naming the root, e.g.+// OData-EntityId: https://contoso.crm.dynamics.com/api/data/v9.2/systemforms(0b7c…)+// Anything else — a 202, a duplicate key, a timeout, another row's id — acknowledges nothing.+function createAnswered(res, rootId) {+ if (!res || res.error || res.incompleteResponse || ![200, 201, 204].includes(res.statusCode)) return false;+ const raw = res.body;+ const empty = raw === undefined || raw === null || raw === '' || (Buffer.isBuffer(raw) && raw.length === 0);+ if (!empty) {+ const body = jsonObjectOf(raw);+ if (!body || body.error !== undefined) return false;+ if (body.formid !== undefined && plainGuid(body.formid) !== rootId) return false;+ }+ const entityId = headerOf(res.headers, 'odata-entityid');+ if (entityId !== undefined) {+ const m = /\/systemforms\((\{?[0-9a-f-]{36}\}?)\)\/?$/i.exec(String(entityId).trim());+ if (!m || plainGuid(m[1]) !== rootId) return false;+ }+ return true;+}++// The local answer to a receipt's create that is not sent: a final status (lib/retry-policy.js), so the client does not+// send it again, in the barrier's refusal shape (lib/publication-barrier.js).+function receiptRefused(message) {+ return {+ statusCode: 409,+ headers: { 'content-type': 'application/json; charset=utf-8' },+ body: JSON.stringify({ error: { code: 'dashboard-create-receipt-refused', message: `the dashboard create was not sent: ${message}` } }),+ };+}+/*** The send observer of managed attempts: the build's transport, wrapped so that a mutation sent while an attempt's* window is open is recorded on that attempt before it leaves (recoverManagedAttempt reads the record). Install it@@ -600,7 +720,53 @@ function notStartedAnswer(req, res) {*/function createAttemptSendObserver() {const windows = new Set();+ // The create receipt in force for the async context of one dashboard create push (withDashboardCreateReceipt). Its own+ // instance per observer, so an observer never reads another's scope.+ const receipts = new AsyncLocalStorage();let installed = false;+ // Count `req` on every window now open or trailing, before it leaves. Answers the windows open at that moment.+ const countOnWindows = () => {+ const counted = [...windows];+ for (const w of counted) w.store.noteAttemptDispatch(w.token, w.epoch);+ return counted.filter((w) => w.state === 'open');+ };+ const noteNotStarted = (openAtSend, req, res) => {+ if (!notStartedAnswer(req, res)) return;+ for (const w of openAtSend) {+ if (w.state !== 'open') continue;+ // A failed write leaves this mutation counted as possibly applied: the record may overstate, never understate.+ try { w.store.noteAttemptNotStarted(w.token, w.epoch); } catch { /* stays possibly applied */ }+ }+ };+ // The exact create of a receipt's root (withDashboardCreateReceipt). Its dispatch is recorded first and the request is+ // counted on the windows as any mutation; a store that refuses either sends nothing. A client re-send of the same POST+ // (a transient answer, a refreshed token) keeps the receipt's one dispatch token and is counted again.+ const receiptedCreate = async (scope, req, transport) => {+ // A receipt write that already failed in this push: nothing more of it is sent.+ if (scope.error) return receiptRefused('an earlier write of its create receipt failed');+ let dispatchToken;+ let openAtSend;+ try {+ ({ dispatchToken } = scope.store.noteDashboardCreateDispatch(scope.token, { sendEpoch: scope.sendEpoch, bodySha256: scope.bodySha256 }));+ openAtSend = countOnWindows();+ } catch (err) {+ scope.error = err;+ return receiptRefused(err && err.message ? err.message : String(err));+ }+ const res = await transport(req);+ if (createAnswered(res, scope.rootId)) {+ try {+ scope.store.noteDashboardCreateAnswer(scope.token, { sendEpoch: scope.sendEpoch, dispatchToken, bodySha256: scope.bodySha256 });+ } catch (err) {+ // Never a network failure the client would retry: the real answer goes back as it came, the create is not sent+ // again, and the store's error stops the build once the push returns. The answer may have landed, so nothing+ // here says it did not start.+ if (!scope.error) scope.error = err;+ }+ }+ noteNotStarted(openAtSend, req, res);+ return res;+ };return {get installed() { return installed; },wrap(transport = require('./dataverse-auth.js').makeRequest) {@@ -608,23 +774,57 @@ function createAttemptSendObserver() {installed = true;return async function observedRequest(req) {const method = String((req && req.method) || 'GET').toUpperCase();+ const scope = receipts.getStore();+ if (scope && method === 'POST' && receiptOwns(scope, req)) return receiptedCreate(scope, req, transport);if (!windows.size || method === 'GET' || method === 'HEAD') return transport(req);- const counted = [...windows];- for (const w of counted) w.store.noteAttemptDispatch(w.token, w.epoch);// Which windows were open when the request left: only those may record its not-started answer, and only if they- // are still open when the answer arrives (checked below).- const openAtSend = counted.filter((w) => w.state === 'open');+ // are still open when the answer arrives (noteNotStarted).+ const openAtSend = countOnWindows();const res = await transport(req);- if (notStartedAnswer(req, res)) {- for (const w of openAtSend) {- if (w.state !== 'open') continue;- // A failed write leaves this mutation counted as possibly applied: the record may overstate, never understate.- try { w.store.noteAttemptNotStarted(w.token, w.epoch); } catch { /* stays possibly applied */ }- }- }+ noteNotStarted(openAtSend, req, res);return res;};},+ /**+ * Run `fn` — the one push of a new dashboard's create — with its durable create receipt (store+ * noteDashboardCreateDraft already recorded it, under the attempt `token` and the send epoch `sendEpoch` its+ * markSending answered). Only the exact create is the receipt's: a direct POST to the systemforms collection, not a+ * `$batch`, whose JSON body names `rootId` in `formid` and whose canonical hash is `bodySha256`. For that request:+ * 1. before it leaves, the receipt's dispatch is recorded (store.noteDashboardCreateDispatch), then it is counted on+ * every window as any mutation is; a refusal of either sends nothing and answers a local final 409+ * (`dashboard-create-receipt-refused`, read as final by lib/retry-policy.js, so the client does not send again);+ * 2. a success — 200, 201 or 204, a complete answer, any body a JSON object with no error, any `formid` or+ * `OData-EntityId` naming the root — is acknowledged (store.noteDashboardCreateAnswer) BEFORE the answer is+ * handed back. A refusal of that write still hands back the real answer, unchanged: a replaced answer would+ * make the client send the create again;+ * 3. any other answer acknowledges nothing; a not-started answer is recorded on the windows as for any request.+ * Every other request inside `fn` passes as without a receipt. A store error met in 1 or 2 is kept, and thrown here+ * once `fn` has returned or thrown — after the push, so the push's own error handling never turns a store failure+ * into an unknown write. Answers what `fn` answers.+ */+ withDashboardCreateReceipt({ store, token, sendEpoch, rootId, bodySha256 } = {}, fn) {+ if (!installed) throw codedError(CODES.notSettled, 'a dashboard create receipt needs the send observer installed on the build\'s transport');+ const root = plainGuid(rootId);+ if (!store || typeof store.noteDashboardCreateDispatch !== 'function' || typeof store.noteDashboardCreateAnswer !== 'function'+ || typeof token !== 'string' || !token || !Number.isSafeInteger(sendEpoch) || sendEpoch < 1 || !root+ || typeof bodySha256 !== 'string' || !/^[0-9a-f]{64}$/.test(bodySha256) || typeof fn !== 'function') {+ throw new TypeError('withDashboardCreateReceipt: a store, the attempt token, its send epoch, the root id, the body hash and the push are required');+ }+ const scope = { store, token, sendEpoch, rootId: root, bodySha256, error: null };+ const rethrow = () => { if (scope.error) throw scope.error; };+ return receipts.run(scope, async () => {+ let out;+ try {+ out = await fn();+ } catch (err) {+ // The store's refusal is what stopped the push: it is the error the build reports, with its own code.+ rethrow();+ throw err;+ }+ rethrow();+ return out;+ });+ },/*** Open the send window of the attempt `token` in `store`, under the `epoch` its markSending answered (fenced: a* count under an epoch the store has moved past is refused unsent). close() stops it recording not-started answers@@ -791,6 +991,7 @@ async function confirmUncertainPublication({ store, barrier, scope, client, readfor (const [token, list] of dispatches) {let code = null;let apart = false;+ const apartReads = [];const proofs = [];if (corrupt.length) code = CODES.groupInvalid;else if (typeof token !== 'string' || !token) code = PUBLICATION_UNCONFIRMED;@@ -807,7 +1008,12 @@ async function confirmUncertainPublication({ store, barrier, scope, client, readlet read;try { read = await reader(client, o.group); } catch { code = PUBLICATION_UNVERIFIED; break; }if (!read || typeof read.publishedSha256 !== 'string') { code = PUBLICATION_UNVERIFIED; break; }- if (read.publishedSha256 !== shipped) { code = PUBLICATION_UNCONFIRMED; apart = read.savedSha256 === shipped; break; }+ if (read.publishedSha256 !== shipped) {+ code = PUBLICATION_UNCONFIRMED;+ apart = read.savedSha256 === shipped;+ if (apart && read.captionDifferences !== undefined) apartReads.push({ family: o.family, key: o.key, captionDifferences: read.captionDifferences });+ break;+ }proofs.push({ family: o.family, key: o.key, publishedSha256: read.publishedSha256, generation: o.group.generation });}if (!code) {@@ -824,7 +1030,8 @@ async function confirmUncertainPublication({ store, barrier, scope, client, readunconfirmed.push(...list.map(({ family, key }) => ({ family, key, code })));const remedy = typeof token === 'string' && token ? `; ${publicationRemedy(scope, token)}` : '';const found = apart ? `: ${LAYERS_READ_APART}` : '';- gate.blockScope(scope, `${list.map((g) => `managed ${g.family} "${g.key}"`).join(', ')} (its publish may have been sent and a fresh read did not prove it ended${found}${remedy})`);+ const note = apart ? captionDifferencesNote(apartReads, (l) => l.map((g) => `managed ${g.family} "${g.key}"`).join(', ')) : '';+ gate.blockScope(scope, `${list.map((g) => `managed ${g.family} "${g.key}"`).join(', ')} (its publish may have been sent and a fresh read did not prove it ended${found}${remedy}${note})`);}return { confirmed, unconfirmed };}@@ -1013,7 +1220,10 @@ async function publishManagedScope({ store, barrier, scope, groups, client, readconst savedEqual = typeof desired === 'string' && read.savedSha256 === desired;// Owed debt ships only its own saved layer. Anything else may stay as it is live, or be what it last desired.const safe = o.group.publication.state === 'owed' ? savedEqual : savedEqual || read.savedSha256 === read.publishedSha256;- out.push({ ...o, savedSha256: read.savedSha256, publishedSha256: read.publishedSha256, equal: read.publishedSha256 === desired, safe });+ // A reader's caption diagnostic (systemform-published.js readSystemFormLayers) rides beside the hashes for the+ // message of a stop only: no decision below reads it, and every store write projects its own fields.+ const diagnostic = read.captionDifferences !== undefined ? { captionDifferences: read.captionDifferences } : {};+ out.push({ ...o, savedSha256: read.savedSha256, publishedSha256: read.publishedSha256, equal: read.publishedSha256 === desired, safe, ...diagnostic });}return out;};@@ -1166,7 +1376,8 @@ async function publishManagedScope({ store, barrier, scope, groups, client, readconst sent = carriedReads.find((c) => c.family === o.family && c.key === o.key);return o.savedSha256 === (sent ? sent.savedSha256 : o.group.publication.desiredSha256);});- throw codedError(PUBLICATION_UNCONFIRMED, `the publish was sent and the published layer does not show what it shipped${stillSaved ? `: ${names(unshown)} ${LAYERS_READ_APART}` : ''}`, journaled());+ const message = `the publish was sent and the published layer does not show what it shipped${stillSaved ? `: ${names(unshown)} ${LAYERS_READ_APART}` : ''}`;+ throw codedError(PUBLICATION_UNCONFIRMED, stillSaved ? message + captionDifferencesNote(unshown, names) : message, journaled());}// One atomic write settles the whole send, so no run can see some of it confirmed and not the rest. `answered`:// this invocation dispatched the publish and it answered success, which a later run can never claim.diff --git a/plugins/model-apps/scripts/lib/managed-fragments.js b/plugins/model-apps/scripts/lib/managed-fragments.jsnew file mode 100644index 000000000..465591528--- /dev/null+++ b/plugins/model-apps/scripts/lib/managed-fragments.js@@ -0,0 +1,169 @@+'use strict';+/**+ * The fragments file of an explicit managed download (download-model-app.js --include-managed --managed-manifest <store>).+ *+ * The managed restore (lib/declared-form-io.js restoreManagedForms, lib/declared-bpf-io.js restoreManagedBpfs) proves a+ * declared form or process flow against the environment and then has to leave some of them out of app-spec.json: the+ * declaration is proved, but it names something the download could not bring with it (the script library a form handler+ * calls, the persona a flow's securityRoles name), and a spec that names what it does not declare does not validate. Before+ * this file such an item was only named on stderr, and the maker had to rebuild the declaration from the spec it was built+ * from. Now each one is written here, ready to paste, with what it still needs.+ *+ * An item is written only when its declaration is PROVED and the dependency is its only blocker: the caller validates the+ * downloaded spec with the declaration and a stub for each missing dependency (see `stubWebResource` and `stubPersona`). The+ * stubs are never written anywhere. An item that is pending, unusable, unread, changed or invalid for any other reason gets+ * no fragment, because nothing proved it.+ *+ * The file: <out>/.maker-workspace/managed-fragments-<UTC time>-<random>.json, e.g. managed-fragments-20261103T171412Z-3fa9c2.json+ * (the tool-owned folder the download's baseline is written to)+ * { "kind": "model-apps.managed-download-fragments", "formatVersion": 1, "app": "<app unique name>", "note": "...",+ * "items": [ { "family": "form" | "bpf", "key": "<store key>", "reason": "<why it was left out>",+ * "needs": [ { "webResource": "<name>" } | { "persona": "<name>" } ],+ * "paste": { "forms": [ <declaration> ] } | { "businessProcessFlows": [ <declaration> ] } } ] }+ * The items are sorted by family, then key, so two downloads of the same app write the same bytes. No environment, tenant or+ * user value is written: a declaration holds table, column and form names and ids that app-spec.json already holds.+ *+ * Ownership. WHY a new name every time: the folder is the maker's app folder, so any name in it may hold a file the download did+ * not write, or come to hold one while the download runs. Replacing or removing a file there safely needs the file system to+ * say "this is still the file I looked at" at the moment of the change, and no portable call does (rename replaces, a hard+ * link needs support the folder may lack, and a check before the move is always a step behind). So the download never+ * replaces, renames over, removes or links anything here. It only ever CREATES a file, once per download, under a name it has+ * never used, with an exclusive create (open `wx`: O_CREAT|O_EXCL, CREATE_NEW on Windows), which the file system itself refuses+ * when a file or folder already has that name. A name that holds anything (a link too, which Windows would otherwise follow when+ * its target is missing; see createExclusive) is left exactly as it is and another name is tried. With nothing due nothing is+ * written and nothing is removed.+ * - Files from earlier downloads stay; each is the record of the download that wrote it, and the result and the WARNING name+ * the one this download wrote. Deleting them is the maker's choice.+ * - It is called after the restore and the validation and BEFORE the download publishes anything (download-model-app.js main+ * stages the page tree and writes it, the spec and the baseline only after this), so a failure here leaves every output that+ * was there as it was.+ */+const crypto = require('crypto');+const fs = require('fs');+const path = require('path');+const { assertSafeOutputDir } = require('./safe-fs.js');+const { redactFileData } = require('./output-redaction.js');++const FRAGMENTS_KIND = 'model-apps.managed-download-fragments';+const FRAGMENTS_FORMAT = 1;+const WORKSPACE_DIR = '.maker-workspace';+// Names tried before giving up: each is new (time and 24 random bits), so a second one is needed only when something took the+// first between two downloads in the same second, or a maker made a file of that very name.+const MAX_ATTEMPTS = 8;+const NOTE = 'Managed items the download proved but left out of app-spec.json for what it could not bring. Add each "paste" entry to the same array in app-spec.json, together with what its "needs" lists (from the spec it was built from), then build.';++function codeError(code, message) {+ const e = new Error(message);+ e.code = code;+ return e;+}++// 2026-11-03T17:14:12.667Z -> 20261103T171412Z (ISO 8601 basic format, UTC, to the second).+const utcStamp = (date) => date.toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z');+const fragmentsName = (date, suffix) => `managed-fragments-${utcStamp(date)}-${suffix}.json`;++const byFamilyThenKey = (a, b) => (a.family < b.family ? -1 : a.family > b.family ? 1 : a.key < b.key ? -1 : a.key > b.key ? 1 : 0);++// The file's text: LF, 2-space indent, items sorted.+function fragmentsText(app, items) {+ const sorted = [...items].sort(byFamilyThenKey);+ return `${JSON.stringify({ kind: FRAGMENTS_KIND, formatVersion: FRAGMENTS_FORMAT, app: app || '', note: NOTE, items: sorted }, null, 2)}\n`;+}++// Creates `file` with `text`, exclusively. Answers 'taken' when the name exists (nothing there is touched); throws the failure to+// create; answers { partial: error } when the file was created but writing it failed (it is the download's own, half-written).+// WHY the lstat before and the identity check after the open: on Windows an exclusive create (CREATE_NEW) FOLLOWS a symbolic+// link whose target does not exist and creates the target, where POSIX O_EXCL refuses any link. So a name holding anything,+// a dangling link included, is passed over first; and a link put there between that look and the open (it would have to guess+// the random name) is caught by comparing what was opened with what the name holds, before a byte is written.+// `shownFile` names the file in the error text only (see settleFragments); every operation goes through `file`.+function createExclusive(file, text, shownFile = file) {+ try {+ fs.lstatSync(file);+ return 'taken';+ } catch (e) {+ if (!e || e.code !== 'ENOENT') throw e;+ }+ let fd;+ try {+ fd = fs.openSync(file, 'wx');+ } catch (e) {+ if (e && e.code === 'EEXIST') return 'taken';+ throw e;+ }+ try {+ const opened = fs.fstatSync(fd, { bigint: true });+ const named = fs.lstatSync(file, { bigint: true });+ // ino only: on Windows lstat reports dev 0 while fstat reports the volume serial, and both names are in one folder (one volume).+ if (!named.isFile() || named.ino !== opened.ino) {+ throw codeError('managed-fragments-unwritable', `the managed fragments file could not be made at ${shownFile}: a link or another file took the name while it was made, so nothing was written to it (if it was a link, an empty file may have been made where it points). No other output was written.`);+ }+ // Through redactFileData like every guarded writer (lib/safe-fs.js writeFileSafe, which this file wrote through before): a+ // declaration holds no token, but the file is written raw through its descriptor, so the guard is applied here.+ fs.writeFileSync(fd, redactFileData(text));+ fs.fsyncSync(fd);+ } catch (e) {+ if (e && e.code === 'managed-fragments-unwritable') throw e;+ return { partial: e };+ } finally {+ try { fs.closeSync(fd); } catch { /* the write's own outcome is what is reported */ }+ }+ return null;+}++function unwritableError(where, e, extra = '') {+ return codeError('managed-fragments-unwritable', `the managed fragments file could not be written in ${where} (${(e && e.message) || (e && e.code) || e}).${extra} No other output was written.`);+}++/**+ * Writes `items` to a NEW fragments file (see the header: created exclusively, never over anything). Called after the spec+ * validated and before the download publishes anything, so a failure here leaves every other output as it was.+ * Answers { file, keys: [{ family, key }] } when items were written, or null when there were none (nothing written, nothing+ * removed). Throws `managed-fragments-unwritable` when .maker-workspace is not a plain folder in <out> (a link, a junction, a+ * file) or no new file could be made there. `now` and `suffix` are seams for the tests.+ */+function settleFragments(outDir, { app, items, now = () => new Date(), suffix = () => crypto.randomBytes(3).toString('hex') } = {}) {+ const list = Array.isArray(items) ? items : [];+ if (!list.length) return null;+ // Two forms of one folder. Every filesystem operation (the create, the link and identity checks) goes through `dir`, the real+ // path assertSafeOutputDir answers for the folder it actually checked: a parent junction or symlink retargeted after that+ // check cannot move the write into a folder nobody checked. `shown` is the same folder in the form of the <out> the caller+ // gave (a parent link kept, an 8.3 short name such as C:\Users\RUNNER~1 not expanded), as every other output of the+ // download is reported; it is used ONLY for what is reported (the result, the warning, the error text), never for I/O.+ const shown = path.join(path.resolve(outDir), WORKSPACE_DIR);+ let dir;+ try {+ // Created when missing; refused when it is a link or junction (a write there would land outside <out>) or not a folder.+ dir = assertSafeOutputDir(shown, { create: true });+ } catch (e) {+ throw unwritableError(shown, e);+ }+ const text = fragmentsText(app, list);+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) {+ const name = fragmentsName(now(), suffix());+ let outcome;+ try {+ outcome = createExclusive(path.join(dir, name), text, path.join(shown, name));+ } catch (e) {+ throw e && e.code === 'managed-fragments-unwritable' ? e : unwritableError(shown, e);+ }+ if (outcome === 'taken') continue;+ const file = path.join(shown, name);+ if (outcome && outcome.partial) throw unwritableError(shown, outcome.partial, ` A partial file was left at ${file}; delete it.`);+ return { file, keys: [...list].sort(byFamilyThenKey).map((i) => ({ family: i.family, key: i.key })) };+ }+ throw unwritableError(shown, `every name tried (${MAX_ATTEMPTS}) was taken`);+}++// The stand-ins a proof validates with: shape only, never written.+const stubWebResource = (name) => ({ name, type: 'js', content: '' });+const stubPersona = (name, entity) => ({ persona: name, jobs: [{ name: 'stub', privileges: [{ entity: String(entity || 'account').toLowerCase(), access: ['read'] }] }] });++module.exports = {+ FRAGMENTS_KIND,+ FRAGMENTS_FORMAT,+ settleFragments,+ fragmentsText,+ stubWebResource,+ stubPersona,+};diff --git a/plugins/model-apps/scripts/lib/persona-restore.js b/plugins/model-apps/scripts/lib/persona-restore.jsnew file mode 100644index 000000000..c63b5d6f7--- /dev/null+++ b/plugins/model-apps/scripts/lib/persona-restore.js@@ -0,0 +1,279 @@+'use strict';+// The explicit managed download's persona proof (download-model-app.js --include-managed --managed-manifest <file>): a persona a+// restored declared process flow's `securityRoles` name, read back from the role a build made for it — written only when a+// rebuild of the downloaded spec provably leaves that role EXACTLY as it is.+//+// WHY exactness, not a best guess. `personas[]` is not a reference to a role: a build OWNS the persona's role. It reuses the+// unmanaged role carrying the SDK marker in the persona's business unit and REPLACES its privileges with the persona's compiled+// set (ReplacePrivilegesRole, vendored SDK createPersonaRole), associates or dissociates the app per `appAccess`, adds the role+// to the solution, and then ADDS the flow grants (sdk-build.js security phase, BPF_ROLE_ACCESS on the backing table). A persona+// that compiles to anything but what the role holds now would silently change who can do what on the next build. So every+// persona is proved, all or nothing, and the download refuses (and names why) on anything it cannot prove:+// a. role: exactly one role of that name in the ROOT business unit (a written persona carries no businessUnitId, so the build+// looks there), unmanaged (`ismanaged === false`, strictly) and carrying SDK_ROLE_MARKER. Any other row of the name there+// would make the build refuse the persona; more than one marked row, likewise. A lookup cut short proves neither.+// b. solution: the role is in the app's solution (solutioncomponent type 20), or a build would add it.+// c. app: whether the role is associated with the app (appmodules(<id>)/appmoduleroles_association, every page, each row+// naming a role; a malformed or incomplete answer refuses) is `appAccess`.+// d. privileges: every privilege the role holds (roleprivileges, paged to the end, depth from privilegedepthmask) maps to a+// table, and to an access a persona can declare, through the table metadata. A privilege no table carries (e.g.+// prvExportToExcel) cannot be declared, so a build would remove it: refused.+// e. exactness: the candidate persona, mapped through personaRoleSpecFor (which adds the appmodule read unless appAccess is+// false) and compiled as the SDK compiles it (role-privileges.js compileRolePrivileges), must equal the held set both+// ways: the same privileges at the same depths.+// f. flow grants (per flow, flowGrantsMissing): the role holds create/read/write/delete at Global on the flow's backing table,+// or a build would add them.+// The candidate holds every privilege the role holds, flow grants included, so the build's later additive grant changes nothing.+//+// Read-only: every read goes through the download's own throwaway SDK, and nothing here writes. Reads are memoised per run, so+// a persona several flows name, and the metadata several personas share, are read once.+const { odataLit } = require('./odata.js');+const { SDK_ROLE_MARKER, BPF_ROLE_ACCESS } = require('./app-spec.js');+const { depthFromMask, compileRolePrivileges, SCOPE_DEPTH, ACCESS_TYPE, DEPTH_RANK } = require('./role-privileges.js');+const { appRoleIdsComplete } = require('./app-roles.js');+const { readSolutionMembers } = require('./solution-membership.js');+const { hasMoreOf } = require('./query-completeness.js');++// sdk-build.js owns personaRoleSpecFor and the role business-unit scoping verify and teardown use; the download loads it already.+const build = () => require('./sdk-build.js');++// The one job a persona read from a role carries: the role says what it may do, not which job each privilege serves.+const JOB_NAME = 'Privileges read from the environment';+// solutioncomponent `componenttype` of a security role.+// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/solutioncomponent+const ROLE_COMPONENT = 20;+// Every table with the privileges it exposes, in one metadata read: what maps a held privilege id back to its table. A row:+// { "LogicalName": "account", "Privileges": [ { "PrivilegeId": "<guid>", "Name": "prvReadAccount", "PrivilegeType": "Read", … } ] }+// Metadata is answered whole (no paging); an answer that says otherwise is not trusted.+// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query-metadata-web-api+const TABLES_PATH = '/EntityDefinitions?$select=LogicalName,Privileges';++const GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;+const lc = (v) => String(v == null ? '' : v).trim().toLowerCase();+const bare = (v) => lc(v).replace(/[{}]/g, '');+const messageOf = (e) => String((e && e.message) || e).slice(0, 200);+const listed = (items) => (items.length > 3 ? `${items.slice(0, 3).join(', ')} and ${items.length - 3} more` : items.join(', '));+const rank = (depth) => DEPTH_RANK[lc(depth)] || 0;+// Dataverse depth name -> App Spec scope, and PrivilegeType -> App Spec access token (the SDK's spelling, `appendTo`).+const DEPTH_SCOPE = Object.fromEntries(Object.entries(SCOPE_DEPTH).map(([scope, depth]) => [depth, scope]));+const TYPE_ACCESS = Object.fromEntries(Object.entries(ACCESS_TYPE).map(([access, type]) => [type, access === 'appendto' ? 'appendTo' : access]));+const ACCESS_ORDER = ['create', 'read', 'write', 'delete', 'append', 'appendTo', 'assign', 'share'];+const SCOPE_ORDER = ['user', 'businessUnit', 'parentChild', 'organization'];++/**+ * A prover over the download's SDK for the app `appUniqueName` in solution `solutionUniqueName`:+ * prove(name) -> { ok: true, name, persona, roleId, held } | { ok: false, why }+ * flowGrantsMissing(proof, table) -> null when the proved role holds the flow grants on `table`, else why not+ * `persona` is the spec entry to write; `held` is Map<privilegeId, depth name>. A read that fails is a refusal, never a pass.+ */+function createPersonaProver({ sdk, appUniqueName, solutionUniqueName }) {+ const memos = new Map();+ const memo = (key, fn) => {+ if (!memos.has(key)) memos.set(key, fn());+ return memos.get(key);+ };+ const query = (table, options) => sdk.queryRecords(table, options);+ const buCache = {};+ const tablePrivileges = (table) => memo(`table:${table}`, async () => {+ const rows = await sdk.getEntityPrivileges(table);+ if (!Array.isArray(rows) || !rows.length) throw new Error('no privileges were answered');+ return rows;+ });+ const privilegeTables = () => memo('tables', async () => {+ if (!sdk.dataverse || typeof sdk.dataverse.get !== 'function') throw new Error('the SDK has no metadata reader');+ const res = await sdk.dataverse.get(TABLES_PATH);+ if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);+ const body = res.body || {};+ if (!Array.isArray(body.value)) throw new Error('the answer carries no list of tables');+ if (body['@odata.nextLink']) throw new Error('the answer says more tables exist');+ const out = new Map();+ for (const t of body.value) {+ const table = lc(t && t.LogicalName);+ if (!table) continue;+ for (const p of (Array.isArray(t.Privileges) ? t.Privileges : [])) {+ const id = bare(p && p.PrivilegeId);+ if (!GUID_RE.test(id)) continue;+ if (!out.has(id)) out.set(id, []);+ out.get(id).push(table);+ }+ }+ // A privilege several tables share (the activity tables do) is declared on the first in this order; the exactness gate+ // proves the choice compiles back to the same privilege.+ for (const list of out.values()) list.sort();+ return out;+ });+ const members = () => memo('members', async () => {+ try { return await readSolutionMembers(sdk, solutionUniqueName, [ROLE_COMPONENT]); } catch { return null; }+ });+ // Strict on purpose (app-roles.js appRoleIdsComplete): an id missing from this answer is written as `appAccess: false`, which+ // a build turns into a dissociation, so only every page, each row naming a role, is an answer.+ const appRoles = () => memo('app', () => appRoleIdsComplete(sdk, appUniqueName));+ // Names for a refusal: best effort, the ids stand in when the names cannot be read.+ async function privilegeNames(ids) {+ const shown = ids.slice(0, 3);+ let names = new Map();+ try {+ const rows = await query('privilege', { select: ['privilegeid', 'name'], filter: shown.map((id) => `privilegeid eq ${id}`).join(' or ') });+ names = new Map((Array.isArray(rows) ? rows : []).map((r) => [bare(r && r.privilegeid), r && r.name]));+ } catch { /* the ids are named instead */ }+ return ids.map((id) => names.get(id) || id);+ }++ async function proveRole(name) {+ const refuse = (why) => ({ ok: false, why });+ const bu = await build().resolveRoleBusinessUnit(query, undefined, buCache);+ if (!bu) return refuse('the root business unit could not be read');+ let rows;+ try {+ rows = await query('role', { select: ['roleid', 'name', 'description', 'ismanaged'], filter: `name eq '${odataLit(name)}'${build().roleBuClause(bu)}`, top: 5 });+ } catch (e) {+ return refuse(`its role could not be read (${messageOf(e)})`);+ }+ if (!Array.isArray(rows)) return refuse('its role could not be read');+ // The lookup reads `top: 5`; a server that names a next link has more roles of that name than were read+ // (query-completeness.js hasMoreOf, judged on the SDK's own array before anything copies it), so the rows read prove+ // neither that the role is the only one nor that none of the others would make the build refuse.+ if (hasMoreOf(rows) === true) return refuse(`its role lookup was cut short, so it is not known to be the only role named '${name}' in the root business unit`);+ if (!rows.length) return refuse(`no role named '${name}' is in the root business unit`);+ if (rows.some((r) => !r || r.description !== SDK_ROLE_MARKER || r.ismanaged === true)) {+ return refuse(`a role named '${name}' in the root business unit is managed or was not made by a build, and a build refuses to change it`);+ }+ if (rows.some((r) => r.ismanaged !== false)) return refuse('whether its role is managed is not known');+ if (rows.length > 1) return refuse(`more than one role made by a build is named '${name}' in the root business unit`);+ const roleId = bare(rows[0].roleid);+ if (!GUID_RE.test(roleId)) return refuse('its role row carries no id');+ const roleName = typeof rows[0].name === 'string' && rows[0].name.trim() ? rows[0].name.trim() : name;++ const held = await members();+ if (!held) return refuse(`whether its role is in solution '${solutionUniqueName}' could not be read`);+ if (!held.members.has(`${ROLE_COMPONENT}:${roleId}`)) return refuse(`its role is not in solution '${solutionUniqueName}', so a build would add it`);+ const app = await appRoles();+ if (!app || !app.ok) return refuse(`whether the app is associated with its role could not be read (${(app && app.reason) || 'no answer'})`);+ const appAccess = app.roleIds.includes(roleId);++ // roleprivileges rows: { "privilegeid": "<guid>", "privilegedepthmask": 8 } — the mask is a bitmask (depthFromMask).+ let privRows;+ try {+ privRows = await query('roleprivileges', { select: ['privilegeid', 'privilegedepthmask'], filter: `roleid eq ${roleId}`, paginate: true });+ } catch (e) {+ return refuse(`the privileges of its role could not be read (${messageOf(e)})`);+ }+ if (!Array.isArray(privRows)) return refuse('the privileges of its role could not be read');+ const depths = new Map();+ for (const r of privRows) {+ const id = bare(r && r.privilegeid);+ const depth = depthFromMask(r && r.privilegedepthmask);+ if (!GUID_RE.test(id) || !depth) return refuse('a privilege row of its role could not be read');+ if (!depths.has(id) || rank(depth) > rank(depths.get(id))) depths.set(id, depth);+ }++ let tablesOf;+ try {+ tablesOf = await privilegeTables();+ } catch (e) {+ return refuse(`which table each privilege of its role belongs to could not be read (${messageOf(e)})`);+ }+ const unmapped = [...depths.keys()].filter((id) => !tablesOf.has(id));+ if (unmapped.length) {+ return refuse(`its role holds ${unmapped.length} privilege(s) no table carries (${listed(await privilegeNames(unmapped))}); a persona declares table privileges only, so a build would remove them`);+ }+ const nameOf = new Map();+ const readTable = async (table) => {+ try {+ const privs = await tablePrivileges(table);+ for (const p of privs) if (p && p.privilegeId) nameOf.set(bare(p.privilegeId), p.name);+ return { privs };+ } catch (e) {+ return { why: `the privileges of table '${table}' could not be read (${messageOf(e)})` };+ }+ };+ // With appAccess the build adds the appmodule read itself (personaRoleSpecFor), so the job leaves it out; at a depth other+ // than Global it is then a difference the exactness gate names.+ let appRead = null;+ if (appAccess) {+ const t = await readTable('appmodule');+ if (t.why) return refuse(t.why);+ const p = t.privs.find((x) => x && x.privilegeType === ACCESS_TYPE.read);+ appRead = p ? bare(p.privilegeId) : null;+ }+ const groups = new Map(); // "<table>|<scope>" -> { entity, scope, access: Set }+ for (const [id, depth] of depths) {+ if (id === appRead) continue;+ const table = tablesOf.get(id)[0];+ const t = await readTable(table);+ if (t.why) return refuse(t.why);+ const p = t.privs.find((x) => x && bare(x.privilegeId) === id);+ const access = p && TYPE_ACCESS[p.privilegeType];+ if (!access) return refuse(`its privilege ${(p && p.name) || id} on '${table}' is not one a persona can declare`);+ const scope = DEPTH_SCOPE[depth];+ const key = `${table}|${scope}`;+ if (!groups.has(key)) groups.set(key, { entity: table, scope, access: new Set() });+ groups.get(key).access.add(access);+ }+ const privileges = [...groups.values()]+ .sort((a, b) => (a.entity < b.entity ? -1 : a.entity > b.entity ? 1 : SCOPE_ORDER.indexOf(a.scope) - SCOPE_ORDER.indexOf(b.scope)))+ .map((g) => ({ entity: g.entity, access: ACCESS_ORDER.filter((a) => g.access.has(a)), scope: g.scope }));+ if (!privileges.length) return refuse('its role holds no privilege a job could declare');+ const persona = { persona: roleName, ...(appAccess ? {} : { appAccess: false }), jobs: [{ name: JOB_NAME, privileges }] };++ const roleSpec = build().personaRoleSpecFor(persona);+ // Flattened as the SDK's createPersonaRole flattens a PersonaRoleSpec before it compiles it.+ const requests = [...roleSpec.jobs.flatMap((j) => j.privileges || []), ...(roleSpec.additionalPrivileges || [])];+ const entityPrivileges = new Map();+ for (const r of requests) {+ if (entityPrivileges.has(r.entity)) continue;+ const t = await readTable(r.entity);+ if (t.why) return refuse(t.why);+ entityPrivileges.set(r.entity, t.privs);+ }+ let compiled;+ try {+ compiled = compileRolePrivileges(requests, entityPrivileges);+ } catch (e) {+ return refuse(`its privileges cannot be declared as a persona (${messageOf(e)})`);+ }+ const diffs = [];+ for (const [id, depth] of depths) {+ const c = compiled.get(id);+ const label = nameOf.get(id) || id;+ if (!c) diffs.push(`it holds ${label} at ${depth}, which a build would remove`);+ else if (c.depth !== depth) diffs.push(`it holds ${label} at ${depth}, which a build would set to ${c.depth}`);+ }+ for (const [id, c] of compiled) if (!depths.has(id)) diffs.push(`a build would add ${c.name || id} at ${c.depth}`);+ if (diffs.length) return refuse(`a persona read from its role would not rebuild it exactly (${listed(diffs)})`);+ return { ok: true, name: roleName, persona, roleId, held: depths };+ }++ async function prove(name) {+ return memo(`persona:${lc(name)}`, async () => {+ try {+ return await proveRole(String(name).trim());+ } catch (e) {+ return { ok: false, why: `its role could not be read (${messageOf(e)})` };+ }+ });+ }++ // The build grants BPF_ROLE_ACCESS at organization scope on the flow's backing table to every persona the flow names, after+ // it converges the role; a grant the role lacks now would be ADDED, so the role would change.+ async function flowGrantsMissing(proof, backing) {+ const table = lc(backing);+ if (!table) return 'the backing table of the flow is not known';+ let privs;+ try {+ privs = await tablePrivileges(table);+ } catch (e) {+ return `the privileges of the flow's backing table '${table}' could not be read (${messageOf(e)})`;+ }+ const missing = [];+ for (const access of BPF_ROLE_ACCESS) {+ const p = privs.find((x) => x && x.privilegeType === ACCESS_TYPE[access]);+ if (!p || proof.held.get(bare(p.privilegeId)) !== SCOPE_DEPTH.organization) missing.push(p ? p.name : `${access} on '${table}'`);+ }+ return missing.length ? `its role does not hold ${listed(missing)} at organization scope on the flow's backing table '${table}', which a build would grant` : null;+ }++ return { prove, flowGrantsMissing };+}++module.exports = { createPersonaProver, JOB_NAME };diff --git a/plugins/model-apps/scripts/lib/quick-find.js b/plugins/model-apps/scripts/lib/quick-find.jsindex c1e597c8d..9ab374191 100644--- a/plugins/model-apps/scripts/lib/quick-find.js+++ b/plugins/model-apps/scripts/lib/quick-find.js@@ -28,6 +28,7 @@ const {emptyResult,operation,refusal,+ readFailure,isAuthorized,pushIfChanged,commitPublication,@@ -122,8 +123,9 @@ async function planQuickFind({ entity, quickFind, sdk }, ctx = {}) {let listed;try {listed = await sdk.fetchArtifactList('view', { entityLogicalName: entity });- } catch {- plan.unknown.push(refusal(key, 'quick-find-views-unreadable', 'the table\'s views could not be listed, so its Quick Find view could not be found'));+ } catch (err) {+ // The read's own failure is kept with the finding (sdk-build.js tells the lag of a table it just created by it).+ plan.unknown.push(readFailure(key, 'quick-find-views-unreadable', 'the table\'s views could not be listed, so its Quick Find view could not be found', err));return plan;}const mine = (listed || []).filter((v) => v && String(v.entityLogicalName || entity).toLowerCase() === entity.toLowerCase());@@ -148,8 +150,8 @@ async function planQuickFind({ entity, quickFind, sdk }, ctx = {}) {try {await sdk.fetchArtifact('view', plan.viewId);view = await sdk.getArtifact('view', plan.viewId);- } catch {- plan.unknown.push(refusal(key, 'quick-find-view-unreadable', 'the Quick Find view could not be read'));+ } catch (err) {+ plan.unknown.push(readFailure(key, 'quick-find-view-unreadable', 'the Quick Find view could not be read', err));return plan;}if (!view || !Array.isArray(view.findColumns)) {diff --git a/plugins/model-apps/scripts/lib/reconcile-common.js b/plugins/model-apps/scripts/lib/reconcile-common.jsindex a7580ab77..a3171ed9a 100644--- a/plugins/model-apps/scripts/lib/reconcile-common.js+++ b/plugins/model-apps/scripts/lib/reconcile-common.js@@ -59,6 +59,17 @@ function refusal(key, code, message) {return { key, code, message };}+/**+ * An unknown outcome of a read (`refusal(key, code, message)`) that keeps the read's own failure as `cause`, so the build can+ * tell the metadata-cache lag of a table it has only just created from a real failure (retry-policy.js isFreshTableReadLag).+ * The cause is not enumerable: the finding is still exactly { key, code, message } wherever it is copied, reported or stored.+ */+function readFailure(key, code, message, cause) {+ const out = refusal(key, code, message);+ if (cause !== undefined) Object.defineProperty(out, 'cause', { value: cause, enumerable: false, configurable: true, writable: true });+ return out;+}+function isAuthorized(flag, key) {if (flag === true) return true;if (flag instanceof Set) return flag.has(key);@@ -449,6 +460,7 @@ module.exports = {mergeResults,operation,refusal,+ readFailure,isAuthorized,approvalKey,isApproved,diff --git a/plugins/model-apps/scripts/lib/retry-policy.js b/plugins/model-apps/scripts/lib/retry-policy.jsindex cd75eb2de..d2464c24f 100644--- a/plugins/model-apps/scripts/lib/retry-policy.js+++ b/plugins/model-apps/scripts/lib/retry-policy.js@@ -343,6 +343,31 @@ function isFreshTableLag(error, fresh) {return Boolean(named && named[1].toLowerCase() === fresh);}+// Whether anywhere along its chain the error carries the lag above for the table it was marked with (markFreshTable): what a READ of a table this invocation created meets in the same window — a view or chart+// looked up by name, a process flow's or a rule's identity read, a form looked up by name (#796). The build reads such a read again IN PLACE, drawing on the one retry allowance of the invocation+// (build-model-app.js, retryFreshRead), so nothing it already saved or published is sent again. The classification is the one above: there is no second list of words. A read whose error the reader keeps by+// value (a planner's "could not be read" finding) is checked through this, so the stop it raises is told from a real refusal by the same rule.+function isFreshTableReadLag(error) {+ const chain = causeChain(error);+ const fresh = freshTableOf(chain);+ return Boolean(fresh) && chain.some((e) => isFreshTableLag(e, fresh));+}++// The service's answer behind that lag, as one line for the maker — the status, the code and the platform's words, e.g.+// HTTP 400 0x80041102: The entity with a name = 'contoso_ticket' with namemapping = 'Logical' was not found in the MetadataCache.LazyDynamicMetadataCache with version 9495075 and timestamp 9495075+// — or null when the chain carries no such lag. A stop that wraps the read in words of its own (a declared flow's or rule's create-identity-unverified) keeps the answer only in its cause chain, which the+// CLI does not print (dataverse-auth.js emitResult prints the message), so the stop quotes it from here. The words are the service's and are printed through the same redaction as any other output.+function freshTableLagAnswer(error) {+ const chain = causeChain(error);+ const fresh = freshTableOf(chain);+ const lag = fresh ? chain.find((e) => isFreshTableLag(e, fresh)) : null;+ if (!lag) return null;+ const answered = answeredErrorOf(lag) || {};+ const status = chain.flatMap(statusesOf)[0];+ const code = answered.code ? `${answered.code}: ` : '';+ return `${status ? `HTTP ${status} ` : ''}${code}${String(answered.message || lag.message || '').replace(/\s+/g, ' ').trim()}`;+}+// Whether the error is the plugin's own stop before a default view of the freshly created table `fresh` that names no table was sent (DEFAULT_VIEW_NO_TABLE_CODE, see above): the code AND the table it names.function isUnsentFreshTableView(error, fresh) {return Boolean(fresh) && typedCode(error) === DEFAULT_VIEW_NO_TABLE_CODE && typeof error.table === 'string' && error.table.toLowerCase() === fresh;@@ -435,7 +460,7 @@ function throttleAskOf(error) {}module.exports = {- RETRY, TRANSIENT_STATUSES, TRANSIENT_SERVICE_CODES, TRANSPORT_CODES, isTransientStatus, refusal, neverRetry, serviceFailure, withCause, judgeFailure, retryPolicyFor, retryFrom, throttleAskOf, markFreshTable,+ RETRY, TRANSIENT_STATUSES, TRANSIENT_SERVICE_CODES, TRANSPORT_CODES, isTransientStatus, refusal, neverRetry, serviceFailure, withCause, judgeFailure, retryPolicyFor, retryFrom, throttleAskOf, markFreshTable, isFreshTableReadLag, freshTableLagAnswer,// The code of the build's stop before a default view whose copy names no table, and the error it stops with (sdk-build.js, guardDefaultViewCopies).DEFAULT_VIEW_NO_TABLE_CODE, unsentDefaultView,// Also the reader of an answer's code for lib/entity-provision.js, which recognises an "already exists" refusal by it (isAlreadyExists).diff --git a/plugins/model-apps/scripts/lib/role-privileges.js b/plugins/model-apps/scripts/lib/role-privileges.jsindex 549548eb0..64a582154 100644--- a/plugins/model-apps/scripts/lib/role-privileges.js+++ b/plugins/model-apps/scripts/lib/role-privileges.js@@ -121,4 +121,51 @@ function compareRolePrivileges(declared, entityPrivileges, actualByPrivilegeId)return { ok: missing.length === 0, missing };}-module.exports = { declaredPrivileges, compareRolePrivileges, depthFromMask, SCOPE_DEPTH, ACCESS_TYPE, DEPTH_RANK };+// The privilege set a role holds after the SDK writes `requests` into it — EXACTLY, not as a subset: what the explicit managed+// download proves before it writes a persona read from a role (lib/persona-restore.js), because a build REPLACES a persona+// role's privileges with this set (ReplacePrivilegesRole), so a persona that compiles to anything else changes the role.+// `requests`: [{ entity, access: [...], scope? }] — a PersonaRoleSpec's job privileges and additionalPrivileges, flattened+// as the SDK flattens them (createPersonaRole).+// `entityPrivileges`: Map<entityLogical, [{ name, privilegeId, privilegeType, scopes }]> — the SDK's own+// `getEntityPrivileges` answer, whose `scopes` lists the App Spec scopes the privilege's CanBe* flags allow.+// Returns Map<privilegeId(lowercased, unbraced), { name, depth }> with `depth` the Dataverse depth name.+//+// Mirrors the vendored SDK's resolver (scripts/vendor/cds-maker-sdk.cjs, the function createSecurityRole compiles with)+// rule for rule, and THROWS where it throws, so a set it would refuse is never called exact:+// * a missing scope is `user`; an unknown scope, an empty access list, an unknown access or one the table does not+// expose is refused;+// * a scope the privilege's CanBe* flag forbids is refused;+// * one entry per PrivilegeId. The same scope again joins the entity to it. A different scope is allowed only when+// the entry so far came from this one entity, and then the higher scope wins; distinct entities sharing a+// privilege at different scopes are refused (a role holds one depth per privilege).+// Access tokens are matched through ACCESS_TYPE (lower-cased keys), so `appendto` is read as `appendTo` here where the+// SDK would refuse it; the App Spec validator and the download only ever produce the SDK's own spelling.+function compileRolePrivileges(requests, entityPrivileges) {+ const byId = new Map();+ for (const r of requests || []) {+ const entity = String((r && r.entity) || '');+ if (!r || !Array.isArray(r.access) || !r.access.length) throw new Error(`'${entity}' asks for no access`);+ const scope = r.scope === undefined || r.scope === null ? 'user' : r.scope;+ if (!Object.prototype.hasOwnProperty.call(SCOPE_DEPTH, scope)) throw new Error(`unknown scope '${scope}' for '${entity}'`);+ const privs = entityPrivileges.get(entity);+ if (!Array.isArray(privs) || !privs.length) throw new Error(`the privileges of '${entity}' are not known`);+ for (const a of r.access) {+ const type = Object.prototype.hasOwnProperty.call(ACCESS_TYPE, String(a).toLowerCase()) ? ACCESS_TYPE[String(a).toLowerCase()] : undefined;+ if (!type) throw new Error(`unknown access '${a}' for '${entity}'`);+ const p = privs.find((x) => x && x.privilegeType === type);+ if (!p) throw new Error(`'${entity}' does not support '${a}' access`);+ if (!Array.isArray(p.scopes) || !p.scopes.includes(scope)) throw new Error(`privilege '${p.name}' on '${entity}' does not support the '${scope}' scope`);+ const id = String(p.privilegeId || '').replace(/[{}]/g, '').trim().toLowerCase();+ const prev = byId.get(id);+ if (!prev) { byId.set(id, { name: p.name, scope, entities: new Set([entity]) }); continue; }+ if (prev.scope === scope) { prev.entities.add(entity); continue; }+ if (!(prev.entities.size === 1 && prev.entities.has(entity))) {+ throw new Error(`'${[...prev.entities].sort().join(', ')}' and '${entity}' share the privilege '${p.name}' at different scopes`);+ }+ if (rankOf(SCOPE_DEPTH[scope]) > rankOf(SCOPE_DEPTH[prev.scope])) prev.scope = scope;+ }+ }+ return new Map([...byId].map(([id, v]) => [id, { name: v.name, depth: SCOPE_DEPTH[v.scope] }]));+}++module.exports = { declaredPrivileges, compareRolePrivileges, compileRolePrivileges, depthFromMask, SCOPE_DEPTH, ACCESS_TYPE, DEPTH_RANK };diff --git a/plugins/model-apps/scripts/lib/rule-settlement.js b/plugins/model-apps/scripts/lib/rule-settlement.jsindex 45264a9d6..6d16f9bdc 100644--- a/plugins/model-apps/scripts/lib/rule-settlement.js+++ b/plugins/model-apps/scripts/lib/rule-settlement.js@@ -50,6 +50,7 @@ const { HTTP_SEND_HISTORY } = require('./sdk-http-client.js');const { createWorkflowDriver, createCopyGuard, answeredRefusal, causeChain, leavesOutcomeOpen, coded, completionBytesFor, completionWithin, HASH_BOUND, ACTIVE, DRAFT } = require('./workflow-drive.js');// sdk-build is required lazily: it is the module that will call this one, so a top-level require would be a cycle.+const { markFreshTable, isFreshTableReadLag } = require('./retry-policy.js');const sdkBuild = () => require('./sdk-build.js');// ---------------------------------------------------------------------------------------------------------------@@ -629,7 +630,7 @@ function isAvailabilityRefusal(err) {* @returns {{ committed?: true, recovered?: boolean, noop?: true, skipped?: 'unavailable', id?: string, cause?: Error }}*/async function settleDeclaredRule(input) {- const { rule, sdk, store, catalog, approvals = null, opts = {}, halt, phase = 'business-rules', barrier, httpClient = null, instanceUrl = null, sendObserver = null } = input || {};+ const { rule, sdk, store, catalog, approvals = null, opts = {}, halt, phase = 'business-rules', barrier, httpClient = null, instanceUrl = null, sendObserver = null, freshTable = null, retryFreshRead = null } = input || {};const ensureMembership = (input && input.ensureMembership) || (async () => {});if (!isDeclaredRule(rule)) throw coded(CODES.notSettled, 'settleDeclaredRule takes a rule with reconcile: "declared"');if (!store || typeof store.snapshot !== 'function') throw coded(CODES.notSettled, 'settleDeclaredRule needs the managed binding store');@@ -893,11 +894,18 @@ async function settleDeclaredRule(input) {const { id } = identityFor('businessRule', key, { catalog });let sameName;let atId;- try {- sameName = await sdk.queryRecords('workflow', { select: ['workflowid'], filter: sdkBuild().businessRuleFilter(rule.name, table), paginate: true });- atId = await readVersion(id);- } catch (err) {- throw coded('create-identity-unverified', `${label}: whether the rule already exists could not be read, so it is neither created nor adopted`, { cause: err });+ for (;;) {+ try {+ sameName = await sdk.queryRecords('workflow', { select: ['workflowid'], filter: sdkBuild().businessRuleFilter(rule.name, table), paginate: true });+ atId = await readVersion(id);+ break;+ } catch (err) {+ // As for a process flow (bpf-settlement.js resolveNew): the metadata-cache lag of a table this invocation created is+ // read again here while the build's one retry allowance lasts; nothing was sent, and any other failure stays final.+ if (freshTable) markFreshTable(err, freshTable);+ if (freshTable && typeof retryFreshRead === 'function' && isFreshTableReadLag(err) && (await retryFreshRead(err, freshTable)) === true) continue;+ throw coded('create-identity-unverified', `${label}: whether the rule already exists could not be read, so it is neither created nor adopted`, { cause: err });+ }}if (!Array.isArray(sameName)) throw coded('create-identity-unverified', `${label}: the read of its name answered no list`);const ids = sameName.map((r) => normalizeGuid(r.workflowid));diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.jsindex abc5dd79f..3777f0a64 100644--- a/plugins/model-apps/scripts/lib/sdk-build.js+++ b/plugins/model-apps/scripts/lib/sdk-build.js@@ -93,6 +93,7 @@ const {findExistingColumns,relationshipExists,localizedLabelLcidsInSpec,+ checkLocalizedLabelLanguages,lookupsWithDefaultLabel,relationshipsInCreateOrder,} = require('./entity-provision.js');@@ -166,7 +167,7 @@ const { isAppTextMap, appTextKind, localizedAppText } = require('./app-header-te// service's words, never a message that quotes what the maker named. tests/halt-retry-policy.test.js enumerates the halts in this file and holds each to a table.const { securedBeforeSeed, planFieldSecurity, applyFieldSecurity, assignFieldSecurity } = require('./field-security.js');const { declaredTableFlags } = require('./schema-feature-contract.js');-const { RETRY, isTransientStatus, judgeFailure, retryPolicyFor, retryFrom, refusal, serviceFailure, withCause, markFreshTable, unsentDefaultView } = require('./retry-policy.js');+const { RETRY, isTransientStatus, judgeFailure, retryPolicyFor, retryFrom, refusal, serviceFailure, withCause, markFreshTable, isFreshTableReadLag, freshTableLagAnswer, unsentDefaultView } = require('./retry-policy.js');const { createPublicationBarrier, describeWithheld, describeWithheldApp } = require('./publication-barrier.js');const { createFeatureSettlement, refusal: featureRefusal, isAuthorized, approvalKey } = require('./reconcile-common.js');const { createPassthroughCreates } = require('./creates-passthrough.js');@@ -191,6 +192,7 @@ const { reconcileDeclaredForm, declaredHostsOf, formLayoutKey, formCatalogIntent// Declared dashboards (dashboards[].reconcile "declared", lib/dashboard-reconcile.js) the same way: only while their flag is on. With it// off, validation refuses `reconcile` on a dashboard, and every dashboard takes the build's own create-or-reuse path below.const isDeclaredDashboardOn = (d) => declaredFeatureOn('dashboards') && !!d && d.reconcile === 'declared';+const { withDashboardWorkspaceScope } = require('./dashboard-recovery-workspace.js');const { settleDeclaredDashboard, publishDeclaredDashboard, dashboardKey: declaredDashboardKey } = require('./dashboard-reconcile.js');// The create identity each retired declared key takes when it is declared again (managed-bindings.js incarnations()), handed to// every declared family's create catalog: a key whose root was proved gone and retired is created again under a fresh id, never@@ -1358,7 +1360,7 @@ function guardDefaultViewCopies(provision, table) {// matches ONLY the Main form; same-named Quick View / Card siblings never block it. >1 match (two forms// share entity+type+name) throws an ACTIONABLE error telling the author to pin forms[].formId — we// refuse to guess rather than reconcile an arbitrary form (fail-closed).-async function resolveExistingFormId(provision, def) {+async function resolveExistingFormId(provision, def, { tableNotInCache = 'absent' } = {}) {if (def.formId) {if (!FORM_GUID_RE.test(String(def.formId))) throw refusal(`form "${def.name}": formId '${def.formId}' is not a valid GUID`);const rows = await provision.queryRecords('systemform', { select: ['formid', 'objecttypecode', 'type', 'name'], filter: `formid eq ${def.formId}`, top: 1 });@@ -1403,7 +1405,18 @@ async function resolveExistingFormId(provision, def) {// which swallowed it. This must NOT swallow a transient/real failure: re-throw anything else so the// fail-closed preflight still refuses to write when it truly can't verify safety.// Dataverse error shape: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/compose-http-requests-handle-errors#parse-errors-from-the-response- if (err && /not found in the MetadataCache/i.test(String(err.message || ''))) return null;+ // But the same answer (code 0x80041102) is also the platform's metadata-cache LAG on a table that exists and was created moments+ // ago (#796), so the answer alone never proves the table, and with it the form, absent. `tableNotInCache` says what the caller makes+ // of it:+ // 'absent' (the default): null, as above — for a caller that only reads and writes nothing on a miss (verify, teardown);+ // 'fail': the failure as it came — the build's form step, where a null would create a second form of the same name;+ // a function: the caller's own proof that the table is absent (`await tableNotInCache(err)` answers true) — the preflight,+ // which must not skip its removal gate for a form that is there; anything but a proof of absence keeps the failure.+ if (err && /not found in the MetadataCache/i.test(String(err.message || ''))) {+ if (tableNotInCache === 'absent') return null;+ if (typeof tableNotInCache === 'function' && (await tableNotInCache(err)) === true) return null;+ throw err;+ }throw err;}if (!rows || !rows.length) return null;@@ -3005,7 +3018,9 @@ async function annotateLivePlan(plan, { spec, provision, warn } = {}) {// `--preview-push`, at no extra read.const artifactPresent = async (kind, def) => {if (kind === 'form') {- const id = await resolveExistingFormId(provision, def);+ // The table was read present before this is asked, so a MetadataCache answer here is the table's lag, not its absence (#796):+ // it is thrown, and the item is `unknown` with the service's words rather than a confident `create`.+ const id = await resolveExistingFormId(provision, def, { tableNotInCache: 'fail' });return id ? { id } : false;}if ((kind === 'view' || kind === 'chart') && typeof provision.findArtifact === 'function') {@@ -3106,8 +3121,8 @@ async function annotateLivePlan(plan, { spec, provision, warn } = {}) {// a confident `+ create` for every view and form on it — and the apply never gets that far:// findExistingTable raises BuildHalt for exactly this state, outside any runner.run, so the// build aborts in `data-model`. The form arm is the worst of the three, because- // resolveExistingFormId deliberately swallows the MetadataCache 400 and returns null, which- // `!!` then flattens into a confident "absent".+ // resolveExistingFormId by default swallows the MetadataCache 400 and returns null, which+ // would then flatten into a confident "absent" (artifactPresent asks it not to).if (t.found === null) { item.state = 'unknown'; item.stateWhy = t.why; continue; }const present = await artifactPresent(k.kind, { name: k.name, entityLogicalName: String(k.entity).toLowerCase(), formType: k.formType, formId: k.formId, uniqueName: k.uniqueName });item.state = present === null ? 'unknown' : (present ? 'reuse' : 'create');@@ -3636,6 +3651,12 @@ async function runSdkBuildPhases(spec, opts, owed) {// the attempt (bindingReads): the pages phase judges a navigation target it finds it has to make by the same reads, and reads only a name this check did not.const bindingReadsOfAttempt = bindingReads();await checkPageBindingsBeforeWriting(spec, { provision, phases, changedOnly: opts.changedOnly, warn: opts.warn, seen: bindingReadsOfAttempt });+ // A localized label in a language the organization has not provisioned stops the build here too, before the solution phase can create+ // the publisher and the solution, rather than at the data-model phase after them. Same check, halt and fail-soft policy as there+ // (entity-provision.js checkLocalizedLabelLanguages); the data-model phase is told it ran (localizedLabelsChecked), so the list is read once.+ // Only a run with the data-model phase: the labels are its to write.+ const checkLabelLanguagesEarly = has('data-model');+ if (checkLabelLanguagesEarly) await checkLocalizedLabelLanguages(spec, opts.provisionedLanguages);runner.stopIfRefused('preflight');const createdFormsThisRun = new Set();@@ -3830,10 +3851,20 @@ async function runSdkBuildPhases(spec, opts, owed) {// (create-completion-required). So its prose never counts as an approval to give, whatever flags it names, and the footer sends the// maker through the steps. The flag is data on the finding or cause, not a pattern in its text, so rewording the advice cannot flip it.const approvalNamed = items.some((i) => !i.ordered && /--authorize \S|--allow-destructive/.test(i.text));+ // The one stop a run again may clear by itself: an identity read of a table this invocation created that met the+ // table's metadata-cache lag (retry-policy.js isFreshTableReadLag, #796; the settlement marks it, nothing was sent).+ // The settlement has already read it again in place for as long as the build's one retry allowance lasted, so the stop+ // quotes the service's answer (freshTableLagAnswer): wrapped in the settlement's own words it would otherwise reach the+ // maker only through the cause chain, which the CLI does not print. Every other stop stays RETRY.NEVER.+ const freshLag = isFreshTableReadLag(cause);const next = approvalNamed ? 'Fix the cause (or give the approval named above) and run the build again': items.some((i) => i.ordered) ? 'Follow the steps above, then run the build again': 'Do what the message above says, then run the build again';- const err = new BuildHalt(`${label}: ${said.length ? said.join('; ') : stopCode} — this declared artifact did not settle, and nothing more was written for it. ${next}; it is not retried automatically.`, { phase, code: stopCode, recoverable: false, retry: RETRY.NEVER, cause });+ const lagAnswer = freshLag ? freshTableLagAnswer(cause) : null;+ const tail = freshLag+ ? `The table was created moments ago and is still not readable${lagAnswer ? ` (the service answered ${lagAnswer})` : ''}; run the build again in a minute.`+ : `${next}; it is not retried automatically.`;+ const err = new BuildHalt(`${label}: ${said.length ? said.join('; ') : stopCode} — this declared artifact did not settle, and nothing more was written for it. ${tail}`, { phase, code: stopCode, recoverable: false, retry: freshLag ? RETRY.SERVICE : RETRY.NEVER, cause });Object.defineProperty(err, 'findings', { value: findings, enumerable: false, configurable: true });return err;};@@ -4638,8 +4669,54 @@ async function runSdkBuildPhases(spec, opts, owed) {let dataModel = { entities: {}, globalChoiceIds: {}, statusReasonValues: {}, columns: {}, relationships: [], lookupLabels: {} };// The tables this BUILD created: the caller's set when it retries the whole build (build-model-app.js), so an attempt that finds a table an earlier one created still knows it is that build's; else this run's own.const createdTables = opts.createdTables instanceof Set ? opts.createdTables : new Set();+ // #796: a READ of a table this invocation created can meet the table's metadata-cache lag for a while after the create, e.g.+ // HTTP 400 {"error":{"code":"0x80041102","message":"The entity with a name = 'contoso_task' with namemapping = 'Logical' was not found in the MetadataCache.LazyDynamicMetadataCache with version 9495075 and timestamp 9495075"}}+ // Such a read's failure is marked with its table (markFreshTable) and the read is made again WHERE IT FAILED, through the caller's+ // `retryFreshRead(err, table)` (build-model-app.js), which waits and answers true while the invocation's one retry allowance lasts+ // (the same count, and backoff, as the whole-build retry), and false once it is spent. Only the read is repeated: re-running the whole+ // build instead would resend every save and publish this attempt had already made. A table the build did not create keeps the failure+ // final (its answer is not lag), and so does an answer naming another table, or any other code (retry-policy.js isFreshTableLag+ // decides, by table). With no `retryFreshRead` (a caller that runs one attempt) the marked failure is thrown as it is.+ const retryFreshRead = typeof opts.retryFreshRead === 'function' ? opts.retryFreshRead : null;+ const freshMark = (err, table) => {+ const logical = typeof table === 'string' ? table.toLowerCase() : '';+ return logical && createdTables.has(logical) ? markFreshTable(err, logical) : err;+ };+ const readAgain = async (err, table) => Boolean(retryFreshRead) && isFreshTableReadLag(err) && (await retryFreshRead(err, String(table).toLowerCase())) === true;+ const readFresh = async (table, read) => {+ for (;;) {+ try {+ return await read();+ } catch (err) {+ const marked = freshMark(err, table);+ if (!(await readAgain(marked, table))) throw marked;+ }+ }+ };+ // A planner keeps a failed read by value, as an `unknown` finding whose (non-enumerable) cause is the read's own failure+ // (reconcile-common.js readFailure); a plan holding one sends nothing when applied. `planFresh` plans again, in place, while that+ // failure is the lag of a table this invocation created and the allowance lasts; once it is spent the plan is returned as it is, and+ // `throwFreshLag` throws that failure after the (empty) apply instead of settling the finding — settled, it would be a final stop+ // that hides the service's answer. Any other unknown settles exactly as before.+ const freshLagOf = (table, r) => {+ for (const u of (r && r.unknown) || []) {+ if (u && u.cause && isFreshTableReadLag(freshMark(u.cause, table))) return u.cause;+ }+ return null;+ };+ const planFresh = async (table, plan) => {+ for (;;) {+ const p = await plan();+ const lag = freshLagOf(table, p);+ if (!lag || !(await readAgain(lag, table))) return p;+ }+ };+ const throwFreshLag = (table, r) => {+ const lag = freshLagOf(table, r);+ if (lag) throw lag;+ };if (has('data-model')) {- dataModel = await provisionDataModel({ sdk, provision, runner, spec, apply, languageCode: opts.languageCode, warn: opts.warn, provisionedLanguages: opts.provisionedLanguages, preResolvedLanguageCode: opts.preResolvedLanguageCode, reconcileLookupLabels: true, owedLengths: owed.lengths, createdTables, dateBehaviorPreflight: true, authorizedDestructive: opts.authorizedDestructive, publicationBarrier: owed.barrier });+ dataModel = await provisionDataModel({ sdk, provision, runner, spec, apply, languageCode: opts.languageCode, warn: opts.warn, provisionedLanguages: opts.provisionedLanguages, preResolvedLanguageCode: opts.preResolvedLanguageCode, reconcileLookupLabels: true, owedLengths: owed.lengths, createdTables, dateBehaviorPreflight: true, authorizedDestructive: opts.authorizedDestructive, publicationBarrier: owed.barrier, localizedLabelsChecked: checkLabelLanguagesEarly });Object.assign(result.created.entities, dataModel.entities);}// The field security profiles, after the columns are secured and before any sample data (provisionFieldSecurityProfiles). A spec@@ -6835,7 +6912,12 @@ async function runSdkBuildPhases(spec, opts, owed) {// table must keep one main form), so reconciling onto it would attach the spec's subgrids +// parent lookups to an un-deletable form and strand references that block teardown. Gap 2 is// instead handled by making our form the entity's default (see promoteDefaultForm below).- const existingId = await resolveExistingFormId(provision, def);+ // #796: a lookup that FAILED is never "no form": only an answer with no row is. The stock Main form the platform makes with+ // every table is named "Information", and an earlier attempt may have made the spec's form, so taking a failure for a miss+ // creates a second form of the same name. On a table this invocation created, the metadata-cache lag is read again in place+ // (readFresh); any other failure — the same answer for a table that was there before, another table's, another code — stops+ // the step with the service's answer, and nothing is created.+ const existingId = await readFresh(def.entityLogicalName, () => resolveExistingFormId(provision, def, { tableNotInCache: 'fail' }));if (existingId) return await reconcileForm(existingId, def);} else if (type === 'view') {if (meta && meta.declared) {@@ -6843,7 +6925,7 @@ async function runSdkBuildPhases(spec, opts, owed) {// edited by its helper; it never falls through to the create below, which would bypass the port.const planArgs = { view: meta.specView, sdk: provision, resolveValue: meta.resolveValue, primaryName: meta.primaryName };const stableKey = declaredViewKey(meta.specView);- const planView = () => planStable(stableKey, () => planViewReconcile(planArgs, stableCtx));+ const planView = () => planStable(stableKey, () => planFresh(def.entityLogicalName, () => planViewReconcile(planArgs, stableCtx)));if (stable && stable.settle && stable.protects('view', stableKey)) {// With a store: settled as one managed group (lib/creates-stable-build.js settle), whose membership is made before// the commit, and whose table publish is paid through the managed coverage protocol.@@ -6860,6 +6942,7 @@ async function runSdkBuildPhases(spec, opts, owed) {? provision.addSolutionComponent({ componentId: id, componentType: COMPONENT_TYPE.view, solutionUniqueName: sol.uniqueName }): ensureInSolution(id, COMPONENT_TYPE.view, def.entityLogicalName)),});+ throwFreshLag(def.entityLogicalName, out.r);const { ok } = settleStableResult('views', `view ${out.plan.key}`, out.r);if (!out.managed) await resetUnsettledCopy('view', out.plan.viewId, out.plan, out.r);if (!ok) return null;@@ -6872,6 +6955,7 @@ async function runSdkBuildPhases(spec, opts, owed) {const firstPlan = await planView();const plan = await refuseUnsentCopy('view', 'view', approvalKey('view', firstPlan.key), firstPlan.viewId, firstPlan, planView);const r = await applyViewReconcile(plan, { sdk: provision }, stableCtx);+ throwFreshLag(def.entityLogicalName, r);const { ok } = settleStableResult('views', `view ${plan.key}`, r);await resetUnsettledCopy('view', plan.viewId, plan, r);const created = r.saved.find((s) => s.created);@@ -6883,7 +6967,7 @@ async function runSdkBuildPhases(spec, opts, owed) {await commitSettledPublishes();return created ? created.id : plan.viewId;}- const existingId = await provision.findArtifact('view', { name: def.name, entity: def.entityLogicalName });+ const existingId = await readFresh(def.entityLogicalName, () => provision.findArtifact('view', { name: def.name, entity: def.entityLogicalName }));if (existingId) return await reconcileView(existingId, def, !!(meta && meta.authoredQuery));}// A form cannot be created from a full authored definition (the adapter's createDefault@@ -6939,9 +7023,11 @@ async function runSdkBuildPhases(spec, opts, owed) {const name = e.schemaName.toLowerCase();await runner.run('views', `Quick Find for ${name}`, async () => {const planArgs = { entity: name, quickFind: e.quickFind, sdk: provision };- const firstPlan = await planQuickFind(planArgs, featureCtx);- const plan = await refuseUnsentCopy('view', 'Quick Find view', approvalKey('quickfind', name), firstPlan.viewId, firstPlan, () => planQuickFind(planArgs, featureCtx));+ const planQf = () => planFresh(name, () => planQuickFind(planArgs, featureCtx));+ const firstPlan = await planQf();+ const plan = await refuseUnsentCopy('view', 'Quick Find view', approvalKey('quickfind', name), firstPlan.viewId, firstPlan, planQf);const r = await applyQuickFind(plan, { sdk: provision }, featureCtx);+ throwFreshLag(name, r);settleFeatureResult('views', `Quick Find on ${name}`, r);await resetUnsettledCopy('view', plan.viewId, plan, r);await commitSettledPublishes();@@ -7044,7 +7130,7 @@ async function runSdkBuildPhases(spec, opts, owed) {return runner.run('charts', `chart "${def.name}"`, async () => {const planArgs = { chart: c, sdk: provision, chartArtifact: def };const stableKey = declaredChartKey(c);- const planChart = () => planStable(stableKey, () => planChartReconcile(planArgs, stableCtx));+ const planChart = () => planStable(stableKey, () => planFresh(def.entityLogicalName, () => planChartReconcile(planArgs, stableCtx)));if (stable && stable.settle && stable.protects('chart', stableKey)) {// As for a declared view: one managed group, membership before the commit.const out = await stable.settle({@@ -7060,6 +7146,7 @@ async function runSdkBuildPhases(spec, opts, owed) {? provision.addSolutionComponent({ componentId: id, componentType: COMPONENT_TYPE.chart, solutionUniqueName: sol.uniqueName }): ensureInSolution(id, COMPONENT_TYPE.chart, def.entityLogicalName)),});+ throwFreshLag(def.entityLogicalName, out.r);const { ok } = settleStableResult('charts', `chart ${out.plan.key}`, out.r);if (!out.managed) await resetUnsettledCopy('chart', out.plan.chartId, out.plan, out.r);if (!ok) return null;@@ -7072,6 +7159,7 @@ async function runSdkBuildPhases(spec, opts, owed) {const firstPlan = await planChart();const plan = await refuseUnsentCopy('chart', 'chart', approvalKey('chart', firstPlan.key), firstPlan.chartId, firstPlan, planChart);const r = await applyChartReconcile(plan, { sdk: provision }, stableCtx);+ throwFreshLag(def.entityLogicalName, r);const { ok } = settleStableResult('charts', `chart ${plan.key}`, r);await resetUnsettledCopy('chart', plan.chartId, plan, r);const created = r.saved.find((s) => s.created);@@ -7083,7 +7171,8 @@ async function runSdkBuildPhases(spec, opts, owed) {return created ? created.id : plan.chartId;});}- const existingId = await provision.findArtifact('chart', { name: def.name, entity: def.entityLogicalName });+ // Read through readFresh: this lookup runs outside runner.run, so its failure reaches the build's retry check as it is.+ const existingId = await readFresh(def.entityLogicalName, () => provision.findArtifact('chart', { name: def.name, entity: def.entityLogicalName }));if (existingId) {// The chart DEFINITION is still not reconciled — but its description is (#496), because a// description is the one thing an AI agent inspecting this app later reads, and it reached@@ -7185,7 +7274,7 @@ async function runSdkBuildPhases(spec, opts, owed) {const relationshipName = subgridRelationshipName(spec, f.entity, sg.childEntity);if (!relationshipName) continue;const childLogical = sg.childEntity.toLowerCase();- const viewId = await subgridViewId(provision, result.created.views, spec, sg, childLogical);+ const viewId = await readFresh(childLogical, () => subgridViewId(provision, result.created.views, spec, sg, childLogical));// Every sub-grid needs a concrete view id (the SDK embeds it in the control XML). If the// child entity has neither an explicit nor a built view AND no default public view can be// found, skip the sub-grid rather than crash the whole forms phase.@@ -7255,7 +7344,9 @@ async function runSdkBuildPhases(spec, opts, owed) {sdk: provision,hosts: declaredHostsOf(f, def, { quickViewFormIdOf: (target, name) => quickViewIds[`${String(target).toLowerCase()}|${name}`] || '' }),events: f.events || [],- resolveExisting: () => resolveExistingFormId(provision, def),+ // A failed lookup is never "no form" (#796, as for the build's own form step): the lag of a table this invocation+ // created is read again in place, and any other failure refuses the form with the service's answer, creating nothing.+ resolveExisting: () => readFresh(table, () => resolveExistingFormId(provision, def, { tableNotInCache: 'fail' })),}, {store: bindingGroups && bindingGroups.store,barrier: owed.barrier,@@ -7854,10 +7945,15 @@ async function runSdkBuildPhases(spec, opts, owed) {httpClient: provision.dataverse && provision.dataverse.httpClient,instanceUrl: opts.env,sendObserver: opts.sendObserver || null,+ // #796: the rule's table when this invocation created it, so an identity read that meets the table's metadata-cache lag+ // is read again in place within the build's one retry allowance (`retryFreshRead`) rather than stopping it.+ freshTable: createdTables.has(String(rule.entity).toLowerCase()) ? String(rule.entity).toLowerCase() : null,+ retryFreshRead,});} catch (err) {- // Every stop of a declared rule is final for this run: a refusal (workflow-edit-refused, rule-drift, …) or a held- // attempt is never retried by the runner and never read as a match. The helper's own halts already are.+ // Every stop of a declared rule is final for this run — a refusal (workflow-edit-refused, rule-drift, …) or a held+ // attempt is never retried by the runner and never read as a match — save the identity read that met the metadata-cache+ // lag of a table this invocation created (managedStop: RETRY.SERVICE). The helper's own halts already are.if (err instanceof BuildHalt) throw err;throw halt('business-rules', label, (err && typeof err.code === 'string' && err.code) || 'managed-not-settled', { cause: err });}@@ -7913,7 +8009,8 @@ async function runSdkBuildPhases(spec, opts, owed) {runner.skip('business-rules', `business rule "${rule.name}" on ${rule.entity} (not read, created or changed: declared rule "${fencedBy}" still has a change waiting to be proved under this table and name, and its row may not be visible yet)`);continue;}- const existing = await provision.queryRecords('workflow', {+ // Through readFresh (#796): on a table this invocation created the read can meet its metadata-cache lag.+ const existing = await readFresh(entityLogical, () => provision.queryRecords('workflow', {select: ['workflowid', 'statecode', 'createdon'],// Definition rows only — see businessRuleFilter. Scoped to the entity as well as the name so// a same-named rule on a DIFFERENT table is not mistaken for this one.@@ -7922,7 +8019,7 @@ async function runSdkBuildPhases(spec, opts, owed) {// names all pre-existing same-name rows; their names do not make them disposable.orderBy: 'createdon asc',paginate: true,- });+ }));const existingId = existing && existing[0] && existing[0].workflowid;const heldBy = existingId ? ruleHold.heldRow((existing || []).map((w) => w.workflowid)) : undefined;if (heldBy) {@@ -8158,10 +8255,15 @@ async function runSdkBuildPhases(spec, opts, owed) {httpClient: provision.dataverse && provision.dataverse.httpClient,instanceUrl: opts.env,sendObserver: opts.sendObserver || null,+ // #796: as for a declared rule, the flow's table when this invocation created it (an identity read that meets its+ // metadata-cache lag is read again in place within the build's one retry allowance).+ freshTable: createdTables.has(String(flow.entity).toLowerCase()) ? String(flow.entity).toLowerCase() : null,+ retryFreshRead,});} catch (err) {// Every stop of a declared flow is final for this run (bpf-structure-refused, workflow-edit-refused, bpf-drift, a held- // attempt, …): never retried by the runner and never read as a match. The helper's own halts already are.+ // attempt, …): never retried by the runner and never read as a match — save the identity read that met the metadata-cache+ // lag of a table this invocation created (managedStop: RETRY.SERVICE). The helper's own halts already are.if (err instanceof BuildHalt) throw err;throw halt('business-process-flows', label, (err && typeof err.code === 'string' && err.code) || 'managed-not-settled', { cause: err });}@@ -8208,7 +8310,8 @@ async function runSdkBuildPhases(spec, opts, owed) {runner.skip('business-process-flows', `business process flow "${flow.name}" on ${flow.entity} (not read, created or changed: declared flow "${fencedBy}" still has a change waiting to be proved under this table and name, and its row may not be visible yet)`);continue;}- const existing = await provision.queryRecords('workflow', {+ // Through readFresh (#796): on a table this invocation created the read can meet its metadata-cache lag.+ const existing = await readFresh(entityLogical, () => provision.queryRecords('workflow', {// `uniquename` is selected, not derived. Activation creates the flow's backing TABLE with// exactly this name, and the security phase grants privileges on that table. For a flow this// build created, `bpfUniqueName(flow.name)` IS the deployed value — but a REUSED flow may@@ -8223,7 +8326,7 @@ async function runSdkBuildPhases(spec, opts, owed) {// ARBITRARY row, and seeing more than one is the only way to report a pre-existing duplicate.orderBy: 'createdon asc',top: 50,- });+ }));const existingId = existing && existing[0] && existing[0].workflowid;const heldBpfBy = existingId ? bpfHold.heldRow((existing || []).map((w) => w.workflowid)) : undefined;if (heldBpfBy) {@@ -8501,56 +8604,62 @@ async function runSdkBuildPhases(spec, opts, owed) {}}}- const out = await settleDeclaredDashboard({- dashboard: dash,- catalog: dashboardCatalog,- sdk: provision,- store,- barrier: owed.barrier,- halt: declaredDashboardStop,- resolveTile: (tile) => dashboardTileOpts(spec, tile, result),- toComponent: dashboardComponent,- // A tile the settle creates is sent with its caption in every language of the organization, read with this- // (readProvisionedLanguages); without it such a send stops before it is made.- provisionedLanguages: opts.provisionedLanguages,- retainedCreationIds: creations.idsOf(dash.name) || [],- resolvedId,- // The run's typed approvals: only `dashboard:<key>` (and `dashboard:<key>/<tile>` for one tile's overwrite) approve- // this dashboard; --allow-destructive is what clears its description.- approvals: { adopt: featureCtx.authorizedAdoption, overwrite: featureCtx.authorizedOverwrite, destructive: featureCtx.authorizedDestructive },- // Solution membership of the bound dashboard, an adopted one included: read once per run (solutionMembers) and added unless proved.- ensureMembership: async ({ root }) => { if (root && root.id) await ensureInSolution(root.id, COMPONENT_TYPE.dashboard); },- sendObserver: opts.sendObserver || null,- // The records are written for the app and environment the store is bound to (as the forms helper writes them), so- // the identity the store checks each record against is the one it holds, never a caller's copy.- ctx: (() => {- const envelope = store && typeof store.snapshot === 'function' ? store.snapshot().envelope : null;- return envelope ? { appUniqueName: envelope.appUniqueName, environmentFingerprint: envelope.environmentFingerprint } : {};- })(),- });- // A read-only inspection (a match nobody approved adopting, already as declared) binds nothing and owes nothing; the- // publish below then has no group to pay. The app still names the row it found.- const id = out.id || resolvedId;- let pub;- try {- // opts.publicationSettle paces the read-back after the publish (publishManagedScope `settle`); only a test sets it.- pub = await publishDeclaredDashboard({ store, barrier: owed.barrier, sdk: provision, key, id, settle: opts.publicationSettle });- } catch (err) {- // The refusal keeps its cause: a blocked uncertain publication carries its dispatch as data there (build-model-app.js- // blockedPublicationOf reads err.cause), never in the message.- const code = (err && err.code) || 'managed-publication-failed';- throw managedStop('dashboards', label, code, { cause: err, findings: [{ key, code, message: String((err && err.message) || err).replace(/\s+/g, ' ') }] });- }- if (pub && pub.withheld) {- markIncomplete({- phase: 'dashboards',- code: pub.held ? 'managed-publication-unverified' : 'managed-publication-owed',- message: pub.held- ? `${label}: its saved and published layers could not be read, so it was not published in this run; the change is saved, re-run the build to publish it`- : `${label}: its publish is owed to the managed binding store and was not sent in this run; the change is saved, re-run the build to publish it`,+ // The settle and its publish share one dashboard workspace scope (dashboard-recovery-workspace.js): when the+ // workspace copy is exactly this build's own acknowledged create draft, both work in an isolated workspace over the+ // same connection and the copy is left as it is. Otherwise `scope.currentSdk` is `provision` itself.+ await withDashboardWorkspaceScope({ sourceSdk: provision }, async (workspaceScope) => {+ const out = await settleDeclaredDashboard({+ dashboard: dash,+ catalog: dashboardCatalog,+ sdk: provision,+ workspaceScope,+ store,+ barrier: owed.barrier,+ halt: declaredDashboardStop,+ resolveTile: (tile) => dashboardTileOpts(spec, tile, result),+ toComponent: dashboardComponent,+ // A tile the settle creates is sent with its caption in every language of the organization, read with this+ // (readProvisionedLanguages); without it such a send stops before it is made.+ provisionedLanguages: opts.provisionedLanguages,+ retainedCreationIds: creations.idsOf(dash.name) || [],+ resolvedId,+ // The run's typed approvals: only `dashboard:<key>` (and `dashboard:<key>/<tile>` for one tile's overwrite) approve+ // this dashboard; --allow-destructive is what clears its description.+ approvals: { adopt: featureCtx.authorizedAdoption, overwrite: featureCtx.authorizedOverwrite, destructive: featureCtx.authorizedDestructive },+ // Solution membership of the bound dashboard, an adopted one included: read once per run (solutionMembers) and added unless proved.+ ensureMembership: async ({ root }) => { if (root && root.id) await ensureInSolution(root.id, COMPONENT_TYPE.dashboard); },+ sendObserver: opts.sendObserver || null,+ // The records are written for the app and environment the store is bound to (as the forms helper writes them), so+ // the identity the store checks each record against is the one it holds, never a caller's copy.+ ctx: (() => {+ const envelope = store && typeof store.snapshot === 'function' ? store.snapshot().envelope : null;+ return envelope ? { appUniqueName: envelope.appUniqueName, environmentFingerprint: envelope.environmentFingerprint } : {};+ })(),});- }- if (id) result.created.dashboards[dash.name] = id;+ // A read-only inspection (a match nobody approved adopting, already as declared) binds nothing and owes nothing; the+ // publish below then has no group to pay. The app still names the row it found.+ const id = out.id || resolvedId;+ let pub;+ try {+ // opts.publicationSettle paces the read-back after the publish (publishManagedScope `settle`); only a test sets it.+ pub = await publishDeclaredDashboard({ store, barrier: owed.barrier, sdk: workspaceScope.currentSdk, key, id, settle: opts.publicationSettle });+ } catch (err) {+ // The refusal keeps its cause: a blocked uncertain publication carries its dispatch as data there (build-model-app.js+ // blockedPublicationOf reads err.cause), never in the message.+ const code = (err && err.code) || 'managed-publication-failed';+ throw managedStop('dashboards', label, code, { cause: err, findings: [{ key, code, message: String((err && err.message) || err).replace(/\s+/g, ' ') }] });+ }+ if (pub && pub.withheld) {+ markIncomplete({+ phase: 'dashboards',+ code: pub.held ? 'managed-publication-unverified' : 'managed-publication-owed',+ message: pub.held+ ? `${label}: its saved and published layers could not be read, so it was not published in this run; the change is saved, re-run the build to publish it`+ : `${label}: its publish is owed to the managed binding store and was not sent in this run; the change is saved, re-run the build to publish it`,+ });+ }+ if (id) result.created.dashboards[dash.name] = id;+ });});};// Stored dashboard groups this run does not settle (the spec no longer declares them, or declares them with the build pathdiff --git a/plugins/model-apps/scripts/lib/sdk-teardown.js b/plugins/model-apps/scripts/lib/sdk-teardown.jsindex 8c64515ba..e2373116e 100644--- a/plugins/model-apps/scripts/lib/sdk-teardown.js+++ b/plugins/model-apps/scripts/lib/sdk-teardown.js@@ -71,6 +71,7 @@ const { selectSummaryTables } = require('./ai-candidates.js');const { specOptsIntoAi } = require('./ai-app-settings.js');const { savedPageRows, currentLayerRow } = require('./app-components.js');const { isRestrictedSolution } = require('./system-solutions.js');+const { readSystemFormRootPresence } = require('./systemform-published.js');const { unreadableAnswer } = require('./collection-answers.js');const { fetchSitemap, navigationProof } = require('./sitemap-pages.js');const { unescapePacName } = require('./genpage-sdk.js');@@ -167,6 +168,20 @@ async function deleteFlowResendingLostTransaction(sdk, item) {}}+// The refusal of a form delete that would leave its table with no active Main form: HTTP 400, whose body is+// {"error":{"code":"0x8004F661","message":"This operation can’t be completed. You must have at least one active Main form."}}+// (the apostrophe is U+2019; the SDK words the error `HTTP 400 from https://contoso.crm.dynamics.com/api/data/v9.0/systemforms(<formid>): <message>` and keeps the body in `cause`).+// The code is the platform's FallbackFormDeactivation:+// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/web-service-error-codes+// A table the build created holds only its default Main form, which the build owns, so the explicit delete of that form is refused; the table's own delete, a few steps later,+// removes the form with it. The refusal is recognised by its status and its CODE only, never by its words: the message is localized, and a validation rule or plug-in can quote+// the same words under another code, which is another failure. A body with no code, or another code — including the related FallbackFormDeletion (0x8004F654), which is out of scope —+// stays the failure it is. serviceCodeOf returns the code lower-cased.+const LAST_MAIN_FORM_CODE = '0x8004f661';+function isLastMainFormRefusal(err) {+ return httpStatus(err) === 400 && serviceCodeOf(err) === LAST_MAIN_FORM_CODE;+}+// Marks an error FAIL-CLOSED: what the step could not prove is itself the failure, so deleteStep passes it on before any of its shortcuts. Those read// an error's WORDS and status — "not found", "referenced by", "system-managed", a 404 — and the words of such an error can be a maker's (an app named// "System Managed Ops") or a proxy's ("Resource not found for the segment …"): read as a shortcut, it turned the refusal of a live app into an@@ -1051,7 +1066,13 @@ const KIND_HANDLERS = {// A main form the build promoted to default can't be deleted until a stock form is restored// as the active default (reverse of Gap 2's promote) — otherwise Dataverse blocks the delete.if (item.isMain) await restoreStockMainForm(sdk, item.entity, item.id);- await sdk.deleteRemoteArtifact('form', item.id);+ try {+ await sdk.deleteRemoteArtifact('form', item.id);+ } catch (err) {+ // Tagged, not swallowed: the error still reaches the step as the failure it is, and runTeardownSteps decides whether the table's delete settles it.+ if (isLastMainFormRefusal(err)) err.lastMainFormRefusal = { id: item.id, entity: item.entity };+ throw err;+ }},},chart: {@@ -1906,9 +1927,42 @@ async function runTeardownSteps(spec, opts, deps, deferredResetPublishes) {// that step, which comes before every step it can hold (the plan's `heldBy`: web resources, global choices and relationships to// themselves all follow the tables). What the platform would refuse while such a table exists is not sent.const keptTables = new Map();+ // A form whose delete the platform refused because it is the last active Main form of its table (isLastMainFormRefusal) is not yet a failure: the table's own delete,+ // which comes later, removes the form with it. Each is recorded with the error entry it provisionally adds, and settled once the tables step is over+ // (settleDeferredForms): the entry stands unless this run deleted the form's table AND a fresh read of the form's exact id shows it gone.+ const deferredForms = [];+ // The tables this run deleted, or found already gone: lower-cased logical names.+ const tablesGone = new Set();+ const settleDeferredForms = async () => {+ let cleared = false;+ for (const d of deferredForms.splice(0)) {+ let removed = false;+ if (tablesGone.has(d.entity)) {+ try {+ // Both layers of the row, each answered 404 with the missing-row code (lib/systemform-published.js); any other answer, or a read that cannot be made, proves nothing.+ removed = (await readSystemFormRootPresence(sdk.dataverse, d.id)) === 'absent';+ } catch {+ removed = false;+ }+ }+ if (removed) {+ const at = result.errors.indexOf(d.entry);+ if (at >= 0) result.errors.splice(at, 1);+ (result.deleted.form = result.deleted.form || []).push(d.id);+ cleared = true;+ emit({ phase: d.step.phase, status: 'ok', label: `${d.step.label} (1 deleted — removed with its table ${d.entity})`, n: d.n, total });+ } else {+ emit({ phase: d.step.phase, status: 'error', label: d.step.label, n: d.n, total, detail: d.entry.message });+ }+ }+ if (cleared && !result.errors.length) result.ok = true;+ };+ // The tables step ends with the last table of the plan; a plan with none settles at the step after the form.+ const stepsBeforeTablesEnd = plan.reduce((last, p, i) => (p.kind === 'table' ? i + 1 : last), 0);let n = 0;for (const step of plan) {const myN = (n += 1);+ if (deferredForms.length && myN > stepsBeforeTablesEnd) await settleDeferredForms();// The barrier for the batched default-view resets: nothing past the resets may run before they are// published (the relationship deletes that follow them are what the resets unblock).if (step.kind !== 'resetDefaultViews') await settleDeferredResetPublishes(sdk, deferredResetPublishes);@@ -1995,6 +2049,7 @@ async function runTeardownSteps(spec, opts, deps, deferredResetPublishes) {continue;}const { deletedIds, absentIds, skipped } = await deleteStep(sdk, handler, items, step.kind === 'resetDefaultViews' || step.kind === 'genpage' || step.kind === 'app' ? deferredResetPublishes : undefined);+ if (step.kind === 'table' && (deletedIds.length || absentIds.length)) tablesGone.add(String(step.target.logical).toLowerCase());// A removal that looked for its artifact itself and found none is a step that found nothing — the line and the counts a resolver that finds none gets — and not a deletion.if (!deletedIds.length && !skipped.length && absentIds.length) {result.skipped.push(step.label);@@ -2037,8 +2092,14 @@ async function runTeardownSteps(spec, opts, deps, deferredResetPublishes) {} catch (err) {result.ok = false;const message = errMsg(err);- result.errors.push({ step: step.label, message });- emit({ phase: step.phase, status: 'error', label: step.label, n: myN, total, detail: message });+ const entry = { step: step.label, message };+ result.errors.push(entry);+ // The last Main form of a table: reported once the tables step has decided (settleDeferredForms), not as a failure now.+ if (step.kind === 'form' && err && err.lastMainFormRefusal) {+ deferredForms.push({ step, n: myN, id: err.lastMainFormRefusal.id, entity: String(err.lastMainFormRefusal.entity).toLowerCase(), entry });+ } else {+ emit({ phase: step.phase, status: 'error', label: step.label, n: myN, total, detail: message });+ }if (step.kind === 'genpage') pagesFailed = true;if (step.kind === 'businessRules') {// Whichever read or delete failed, the rule may still have an activated copy, and that copy@@ -2067,6 +2128,7 @@ async function runTeardownSteps(spec, opts, deps, deferredResetPublishes) {}}}+ if (deferredForms.length) await settleDeferredForms();return result;}diff --git a/plugins/model-apps/scripts/lib/systemform-published.js b/plugins/model-apps/scripts/lib/systemform-published.jsindex 6d84103a2..9f4482a6f 100644--- a/plugins/model-apps/scripts/lib/systemform-published.js+++ b/plugins/model-apps/scripts/lib/systemform-published.js@@ -141,14 +141,67 @@ function systemFormRootLayerSha256(layer) {// What a never-published row's published layer reads as: a hash no layer has, so it equals no desired or saved hash.const NEVER_PUBLISHED_SHA256 = intentSha256({ neverPublished: true });+// The most cells a caption diagnostic names (form-caption-diagnostics.js MAX_CAPTION_DIFFERENCES), repeated here so+// that the check of its answer does not depend on the module it checks.+const CAPTION_DIFFERENCES_MAX = 8;++// A caption diagnostic answer as plain data, copied field by field, or null for anything else: one to+// CAPTION_DIFFERENCES_MAX entries, each a normalized GUID cell id and a whole-number language code, no pair twice, and a+// non-negative whole omitted count. Nothing of the answer is spread or kept by reference.+function usableCaptionDifferences(value) {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const { entries, omittedCount } = value;+ if (!Array.isArray(entries) || entries.length < 1 || entries.length > CAPTION_DIFFERENCES_MAX) return null;+ if (!Number.isSafeInteger(omittedCount) || omittedCount < 0) return null;+ const seen = new Set();+ const out = [];+ for (const e of entries) {+ if (!e || typeof e !== 'object') return null;+ const cellId = e.cellId;+ const languageCode = e.languageCode;+ if (typeof cellId !== 'string' || normalizeGuid(cellId) !== cellId) return null;+ if (!Number.isSafeInteger(languageCode) || languageCode < 1000 || languageCode > 99999) return null;+ const k = `${cellId}\u0000${languageCode}`;+ if (seen.has(k)) return null;+ seen.add(k);+ out.push({ cellId, languageCode });+ }+ return { entries: out, omittedCount };+}++// The caption diagnostic of an ADOPTED managed form whose layers differ (form-caption-diagnostics.js), or null. A form+// the build created is not diagnosed: its captions are the build's own. Only XML text is passed to the helper.+function adoptedFormCaptionDifferences(group, read) {+ if (read.state !== 'differs' || !read.published) return null;+ const root = group && group.root;+ const records = group && Array.isArray(group.records) ? group.records : [];+ const rootRecord = root ? records.find((r) => r && r.kind === root.kind && r.key === root.key) : null;+ if (!rootRecord || rootRecord.origin !== 'adopted') return null;+ const { cellCaptionDifferences } = require('./form-caption-diagnostics.js');+ return usableCaptionDifferences(cellCaptionDifferences(String(read.savedCompared.formxml), String(read.published.formxml)));+}+/*** The layer reader of a managed systemform group (lib/managed-layer-readers.js): both layers of the group's root row, as* { savedSha256, publishedSha256 } hashed by systemFormLayerSha256. Throws `managed-publication-unverified` as* readSystemFormPublication does.+ *+ * For an adopted form whose layers differ, the answer may also carry `captionDifferences` ({ entries: [{ cellId,+ * languageCode }], omittedCount }): the cells whose caption reads differently in the two layers, for the message of a+ * stop. It is a diagnostic, never a proof: no caller decides anything by it, and nothing writes it to the store. It is+ * computed only AFTER the two hashes, in its own guard: a helper that throws, is missing or answers anything unusable+ * leaves the answer exactly the two hashes, so a diagnostic can never change a hash, a read failure or a stop.*/async function readSystemFormLayers(client, group) {const r = await readSystemFormPublication(client, group && group.root && group.root.id);- return { savedSha256: systemFormLayerSha256(r.savedCompared), publishedSha256: r.published ? systemFormLayerSha256(r.published) : NEVER_PUBLISHED_SHA256 };+ const out = { savedSha256: systemFormLayerSha256(r.savedCompared), publishedSha256: r.published ? systemFormLayerSha256(r.published) : NEVER_PUBLISHED_SHA256 };+ try {+ const captionDifferences = adoptedFormCaptionDifferences(group, r);+ if (captionDifferences) out.captionDifferences = captionDifferences;+ } catch {+ // A diagnostic only: its failure is dropped whole, and the answer stays the two hashes.+ }+ return out;}/**diff --git a/plugins/model-apps/scripts/lib/view-reconcile.js b/plugins/model-apps/scripts/lib/view-reconcile.jsindex 8e759635a..2fe71b67c 100644--- a/plugins/model-apps/scripts/lib/view-reconcile.js+++ b/plugins/model-apps/scripts/lib/view-reconcile.js@@ -45,6 +45,7 @@ const {emptyResult,operation,refusal,+ readFailure,isAuthorized,approvalKey,isApproved,@@ -349,8 +350,8 @@ async function planViewReconcile({ view, sdk, resolveValue, primaryName }, ctx =if (!id && !binding && ctx.managed && typeof ctx.managed.observe === 'function') {try {id = normalizeGuid(await ctx.managed.observe('view', key)) || '';- } catch {- plan.unknown.push(refusal(key, 'view-lookup-unreadable', 'whether the view exists could not be read'));+ } catch (err) {+ plan.unknown.push(readFailure(key, 'view-lookup-unreadable', 'whether the view exists could not be read', err));return plan;}}@@ -359,9 +360,11 @@ async function planViewReconcile({ view, sdk, resolveValue, primaryName }, ctx =id = normalizeGuid(await sdk.findArtifact('view', { name: intent.name, entity: intent.entity }));} catch (err) {// The SDK refuses a name two rows share (AMBIGUOUS_ARTIFACT): choosing one would edit a row the spec- // may not mean, so the maker names it instead. Any other failure leaves existence unknown.+ // may not mean, so the maker names it instead. Any other failure leaves existence unknown; the read's own failure is+ // kept with it, so the build can tell a table it has only just created, not yet in the metadata cache, from a real+ // failure (sdk-build.js, freshLagOf).if (err && err.code === 'AMBIGUOUS_ARTIFACT') plan.refused.push(refusal(key, 'view-name-ambiguous', 'several views on the table have this name; rename or remove the extra one before it can be managed'));- else plan.unknown.push(refusal(key, 'view-lookup-unreadable', 'whether the view exists could not be read'));+ else plan.unknown.push(readFailure(key, 'view-lookup-unreadable', 'whether the view exists could not be read', err));return plan;}}diff --git a/plugins/model-apps/scripts/lint-app-spec.js b/plugins/model-apps/scripts/lint-app-spec.jsindex e3fd43883..5e8326283 100644--- a/plugins/model-apps/scripts/lint-app-spec.js+++ b/plugins/model-apps/scripts/lint-app-spec.js@@ -20,7 +20,8 @@//// Exit codes: 0 when there are no errors from either step (warnings alone do not fail, so a CI job// can gate on correctness without being blocked by advice), 1 otherwise. `--strict` also fails on-// warnings, for a pipeline that wants them treated as errors.+// warnings, for a pipeline that wants them treated as errors — which includes the warning for an unknown key on a view or one of its+// filters (a misspelled `filters` would otherwise be built without its filter, #799).//// `--profile` selects validateAppSpec's strictness and DEFAULTS TO `plan`, not `deploy`. The deploy// profile requires every generative page to be IMPLEMENTED (`source.kind: 'tsx'` with a codeFile),diff --git a/plugins/model-apps/scripts/provision-entities.js b/plugins/model-apps/scripts/provision-entities.jsindex 6bde71799..81cb711d9 100644--- a/plugins/model-apps/scripts/provision-entities.js+++ b/plugins/model-apps/scripts/provision-entities.js@@ -8,7 +8,7 @@const fs = require('node:fs');const path = require('node:path');const { validateProvisionInput } = require('./lib/provision-input.js');-const { makeRunner, provisionSolution, provisionDataModel, provisionSampleData, relationshipsInCreateOrder } = require('./lib/entity-provision.js');+const { makeRunner, provisionSolution, provisionDataModel, provisionSampleData, relationshipsInCreateOrder, checkLocalizedLabelLanguages } = require('./lib/entity-provision.js');const { quickCreateEnabledFor, normalizeLanguageCode, askedPrimaryNameLength, keyWaitsForNameLength } = require('./lib/app-spec.js');const { createAzHttpClient } = require('./lib/sdk-http-client.js');const { parseArgs, validateFlags, readAliasedFlag, readJsonArg, emitResult, readProvisionedLanguages } = require('./lib/dataverse-auth.js');@@ -188,6 +188,11 @@ async function provisionEntities(input, opts = {}, deps = {}) {...(input.languageCode !== undefined ? { languageCode: input.languageCode } : {}),};+ // A localized label in a language the organization has not provisioned stops here, before the publisher and the+ // solution are created, rather than in the data-model phase after them (same check and halt as there; an+ // unreadable language list does not stop the build). The data-model phase is told, so the list is read once.+ await checkLocalizedLabelLanguages(spec, deps.provisionedLanguages);+// Provision solutionawait provisionSolution({ sdk, provision, runner, solution: spec.solution });@@ -207,6 +212,7 @@ async function provisionEntities(input, opts = {}, deps = {}) {// before any write, rather than half-succeeding (labels silently coerced to the base language,// then a hard 400 on the first DateTime/Memo column).provisionedLanguages: deps.provisionedLanguages,+ localizedLabelsChecked: true,warn,});diff --git a/plugins/model-apps/scripts/tests/app-spec-keys.test.js b/plugins/model-apps/scripts/tests/app-spec-keys.test.jsindex ef38e8a9f..c2349f789 100644--- a/plugins/model-apps/scripts/tests/app-spec-keys.test.js+++ b/plugins/model-apps/scripts/tests/app-spec-keys.test.js@@ -905,4 +905,56 @@ test('minimumPluginVersion refuses a spec that needs a newer plugin than the onefs.readFileSync = realRead;delete require.cache[require.resolve('../lib/app-spec.js')];}+});++// #799: a `views[]` key the build does not read used to validate clean and be dropped, so a view written with `filter` was built without its filter.+const withViews = (views) => Object.assign(base(), { views });+const viewWarnings = (views, opts = { profile: 'plan' }) => validateAppSpec(withViews(views), opts).warnings.filter((w) => /unknown key/.test(w));++test('#799: a view written with `filter` warns and names `filters`; the spec still validates', () => {+ const r = validateAppSpec(withViews([{ entity: 'contoso_order', name: 'High Priority', filter: [{ column: 'contoso_priority', operator: 'eq', value: 5 }] }]), { profile: 'plan' });+ assert.strictEqual(r.ok, true, `a warning must not fail a spec that validated before; got ${JSON.stringify(r.errors)}`);+ const w = r.warnings.filter((x) => /unknown key 'filter'/.test(x));+ assert.strictEqual(w.length, 1, `expected one warning for 'filter'; got ${JSON.stringify(r.warnings)}`);+ assert.match(w[0], /view 'High Priority'/);+ assert.match(w[0], /did you mean 'filters'\?/);+});++test('#799: a filter item written with `column` and `operator` warns and names `attr` and `op`', () => {+ const warnings = viewWarnings([{ entity: 'contoso_order', name: 'High Priority', filters: [{ column: 'contoso_priority', operator: 'eq', value: 5 }] }]);+ const column = warnings.find((x) => /unknown key 'column'/.test(x));+ const operator = warnings.find((x) => /unknown key 'operator'/.test(x));+ assert.ok(column && /filters\[0\]/.test(column) && /did you mean 'attr'\?/.test(column), `got ${JSON.stringify(warnings)}`);+ assert.ok(operator && /did you mean 'op'\?/.test(operator), `got ${JSON.stringify(warnings)}`);+});++test('#799: a view key that is one edit from a supported one is matched; `type`, which older docs showed, is still accepted silently', () => {+ const warnings = viewWarnings([{ entity: 'contoso_order', name: 'Mine', column: ['contoso_name'], activeonly: false, type: 'main' }]);+ assert.ok(warnings.some((x) => /unknown key 'column'.*did you mean 'columns'\?/.test(x)), JSON.stringify(warnings));+ assert.ok(warnings.some((x) => /unknown key 'activeonly'.*did you mean 'activeOnly'\?/.test(x)), JSON.stringify(warnings));+ assert.deepStrictEqual(warnings.filter((x) => /'type'/.test(x)), [], 'a spec written from the older docs must not start to warn');+ assert.deepStrictEqual(viewWarnings([{ entity: 'contoso_order', name: 'Mine', type: 'main' }]), []);+});++test('#799: every key the build reads on a view and its filters stays warning-free', () => {+ const views = [+ { entity: 'contoso_order', name: 'Plain', description: 'd', columns: ['contoso_name'], sort: [{ attr: 'contoso_name', dir: 'asc' }], activeOnly: false,+ filters: [{ attr: 'contoso_priority', op: 'eq', value: 5 }, { attr: 'contoso_priority', op: 'not-in', values: [1, 2] }, { attr: 'ownerid', op: 'eq-userid' }] },+ { entity: 'contoso_order', name: 'Joined', reconcile: 'declared', key: 'joined', viewId: '11111111-1111-1111-1111-111111111111', columns: ['contoso_name'],+ linkEntities: [{ name: 'contact', from: 'contactid', to: 'primarycontactid', alias: 'c', linkType: 'outer', filters: [{ attr: 'lastname', op: 'eq', value: 'Smith' }] }],+ filters: [{ attr: 'lastname', relatedEntity: 'c', op: 'eq', value: 'Smith' }] },+ ];+ for (const profile of ['plan', 'deploy', 'structural']) {+ const r = validateAppSpec(withViews(views), { profile });+ assert.deepStrictEqual(r.warnings.filter((x) => /unknown key/.test(x)), [], `profile ${profile}`);+ assert.deepStrictEqual(r.errors.filter((x) => /view '/.test(x)), [], `profile ${profile}`);+ }+});++test('#799: an unknown key on a join filter warns; a hint key that collides with Object.prototype leaks nothing; non-object filters do not crash', () => {+ const warnings = viewWarnings([{ entity: 'contoso_order', name: 'Joined', reconcile: 'declared', columns: ['contoso_name'], constructor: 1, toString: 2,+ linkEntities: [{ name: 'contact', from: 'contactid', to: 'primarycontactid', alias: 'c', filters: [{ column: 'lastname', op: 'eq', value: 'Smith' }] }] }]);+ assert.ok(warnings.some((x) => /linkEntities\[0\]\.filters\[0\]: unknown key 'column'/.test(x)), JSON.stringify(warnings));+ assert.ok(warnings.every((x) => !/native code/.test(x)), JSON.stringify(warnings));+ assert.doesNotThrow(() => validateAppSpec(withViews([{ entity: 'contoso_order', name: 'Odd', filters: ['x', null, 3] }]), { profile: 'plan' }));});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/authoring-flow-offers-docs.test.js b/plugins/model-apps/scripts/tests/authoring-flow-offers-docs.test.jsnew file mode 100644index 000000000..8970de254--- /dev/null+++ b/plugins/model-apps/scripts/tests/authoring-flow-offers-docs.test.js@@ -0,0 +1,79 @@+'use strict';+// The /app-builder authoring flow OFFERS its optional capabilities (branding, configuration items, declared rules and flows,+// declared form and dashboard layouts) and never turns one on by default. No offline harness records a conversation, so the+// behaviour is pinned here as the instruction the flow gives the model: what is offered, when, and what happens on a yes, a+// "no" and an explicit request.++const { test } = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');++const FLOW = path.join(__dirname, '..', '..', 'references', 'authoring-flow.md');+const SKILL = path.join(__dirname, '..', '..', 'skills', 'app-builder', 'SKILL.md');+// Line breaks and indentation are layout, not wording: compare each text with whitespace collapsed.+const squash = (text) => text.replace(/\r\n/g, '\n').replace(/\s+/g, ' ');+const flow = fs.readFileSync(FLOW, 'utf8').replace(/\r\n/g, '\n');++// A level runs from its "### " heading to the next one; the "#### " subsections inside it do not end it.+function level(heading) {+ const start = flow.indexOf(`\n${heading}`);+ assert.notEqual(start, -1, `authoring-flow.md has no '${heading}' section`);+ const end = flow.indexOf('\n### ', start + 1);+ return squash(flow.slice(start, end < 0 ? undefined : end));+}++test('Level (a0) offers branding to every new app, and configuration items, duplicate detection, Custom APIs, rules and flows when the app needs them - none of it by default', () => {+ const a0 = level('### Level (a0)');+ assert.match(a0, /Offer each optional capability that applies — once, as a question, never as a default\./);+ assert.match(a0, /Ask even when the maker has not mentioned it/);+ assert.match(a0, /\*\*Branding\*\* — for every new app, ask whether it should be branded[^.]*\. If yes, add `app\.theme`/);+ assert.match(a0, /when the app calls an outside service or a value differs per environment[^.]*\), offer configuration items: environment variables and connection references/);+ assert.match(a0, /when the jobs include a validation or a guided process[^.]*\), offer a declared business rule or business process flow/);+ assert.match(a0, /Each one stays off unless the maker says yes or asks for it; a "no" or silence adds nothing to the spec/);+});++test('Level (a0): duplicate-detection rules and Custom APIs have their own triggers, not the outside-service one', () => {+ const a0 = level('### Level (a0)');+ // A self-contained intake app whose jobs identify duplicates, and an internal operation, call for these with no outside service+ // and no per-environment value.+ assert.match(a0, /\*\*Duplicate records\*\* — when the jobs identify duplicate records[^.]*\), offer a duplicate-detection rule on that table, even when the app uses no outside service/);+ assert.match(a0, /\*\*A reusable server-side operation\*\* — when the app needs an operation that several surfaces, flows or pages call, or that must run on the server[^.]*\), offer a Custom API, even when nothing outside Dataverse is involved/);+ const outside = a0.slice(a0.indexOf('**Outside services and per-environment values**'), a0.indexOf('**Duplicate records**'));+ assert.doesNotMatch(outside, /Custom API|duplicate-detection/);+});++test('Level (a0): the offers are not held back until the maker hints at them', () => {+ // An offer made only when the jobs or the maker's words already point to a capability never reaches a maker who does not know it exists.+ const a0 = level('### Level (a0)');+ assert.doesNotMatch(a0, /Ask only when the jobs or the maker's words point to it/);+ assert.doesNotMatch(a0, /Offer the optional capabilities the jobs point to/);+});++test('Level (b) offers declared layouts whenever forms or dashboards are proposed; a yes or an explicit request writes them and a "no" writes nothing declared', () => {+ const b = level('### Level (b)');+ assert.match(b, /Offer declared layouts, once, as a question — never as a default\./);+ assert.match(b, /Whenever you propose forms or dashboards, ask whether the maker wants the layout of any of them to stay as the spec says on every rebuild; if yes, write `reconcile: "declared"`/);+ // The declined path.+ assert.match(b, /Without a yes and without an explicit request, write nothing declared; forms stay `layout: "auto"`/);+ // The explicit-request path: it is the yes, so it is authored, and it must not be listed among the reasons to write nothing.+ assert.match(b, /A maker who already asked for a fixed layout is not asked again: their request is the yes/);+ assert.doesNotMatch(b, /Without a yes \(or when the maker already asked\), write nothing declared/);+ // Existing adoption approvals still apply.+ assert.match(b, /binding one that already exists needs an `--authorize adopt:` approval/);+});++test('Level (a0): an explicit request for a capability is acceptance, so it is not asked again', () => {+ const a0 = level('### Level (a0)');+ assert.match(a0, /skip an offer only for a capability the maker already asked for: an explicit request counts as acceptance/);+});++test('the skill names the offer as a way to a yes for each capability, and still adds none by default', () => {+ const skill = squash(fs.readFileSync(SKILL, 'utf8'));+ assert.match(skill, /says yes to the branding question you ask of every new app at the personas step/);+ assert.match(skill, /an ordinary app gets \*\*no\*\* `app\.theme` without one of those/);+ assert.match(skill, /or said yes when you offered it at Level \(b\)/);+ assert.match(skill, /Declared business rules[^]*?the offer at the personas step, or their own ask/);+ assert.match(skill, /Declared business process flows[^]*?the offer at the personas step, or their own ask/);+ assert.match(skill, /accepts your offer at the personas step/);+});diff --git a/plugins/model-apps/scripts/tests/bpf-settlement.test.js b/plugins/model-apps/scripts/tests/bpf-settlement.test.jsindex 9f5469087..ae07d2ef8 100644--- a/plugins/model-apps/scripts/tests/bpf-settlement.test.js+++ b/plugins/model-apps/scripts/tests/bpf-settlement.test.js@@ -196,6 +196,49 @@ test('a create whose answer is lost is not sent again: a read at the reserved idassert.equal(out.membership.length, 1);});+// #796: the identity read of a flow on a table the build has only just created can meet the table's metadata-cache lag, live:+// GET workflows?$filter=… -> HTTP 400 {"error":{"code":"0x80041102","message":"The entity with a name = 'account' with namemapping = 'Logical' was not found in the MetadataCache…"}}+// With the caller's `freshTable`, that read's failure is marked so the stop is one the build's bounded retry may ride out (retryPolicyFor: SERVICE); nothing is sent, and the next settlement creates the flow once.+// Without it, for another table's answer and for any other answer, the stop stays final.+const notInCache = (table) => `The entity with a name = '${table}' with namemapping = 'Logical' was not found in the MetadataCache.LazyDynamicMetadataCache with version 9495075 and timestamp 9495075`;+const nameRead = (e) => e.method === 'GET' && e.path === 'workflows';+const answer400 = (code, message) => ({ statusCode: 400, body: { error: { code, message } } });++test('an identity read that meets the metadata-cache lag of a table the build just created stops as the retry may ride out, sends nothing, and the next settlement creates once', async () => {+ const { retryPolicyFor, isFreshTableReadLag } = require('../lib/retry-policy.js');+ const wire = createWorkflowWire();+ const dir = makeTempDir('bpf-settle-');+ wire.script(nameRead, answer400('0x80041102', notInCache('account')));+ const first = await settle(wire, dir, FLOW, { freshTable: 'account' });+ assert.equal(first.error && first.error.cause && first.error.cause.code, 'create-identity-unverified');+ assert.equal(retryPolicyFor(first.error.cause), RETRY.SERVICE, 'the lag of a table this invocation created');+ assert.equal(isFreshTableReadLag(first.error.cause), true);+ assert.deepEqual(writesSince(wire, first.from), [], 'nothing is sent');+ const again = await settle(wire, dir, FLOW, { freshTable: 'account' });+ assert.ifError(again.error);+ assert.deepEqual(writeLines(wire, again.from).filter((l) => l === 'POST workflows'), ['POST workflows'], 'one create');+ assert.equal(wire.rows.size, 1);+});++test('an identity read that fails for a table the build did not create, for another table, or with any other answer stays final', async () => {+ const { retryPolicyFor, isFreshTableReadLag } = require('../lib/retry-policy.js');+ for (const [label, answer, freshTable] of [+ ['no freshTable', answer400('0x80041102', notInCache('account')), undefined],+ ['the answer names another table', answer400('0x80041102', notInCache('contoso_other')), 'account'],+ ['an unrelated 400', answer400('0x80040265', 'The value of the attribute is not valid'), 'account'],+ ['the cache words under another code', answer400('0x80040220', notInCache('account')), 'account'],+ ]) {+ const wire = createWorkflowWire();+ const dir = makeTempDir('bpf-settle-');+ wire.script(nameRead, answer);+ const out = await settle(wire, dir, FLOW, freshTable ? { freshTable } : {});+ assert.equal(out.error && out.error.cause && out.error.cause.code, 'create-identity-unverified', label);+ assert.equal(retryPolicyFor(out.error.cause), RETRY.NEVER, label);+ assert.equal(isFreshTableReadLag(out.error.cause), false, label);+ assert.deepEqual(writesSince(wire, out.from), [], `${label}: nothing is sent`);+ }+});+test('a create the service stored with another stage id is never bound, acknowledged or not, and nothing is sent after it', async () => {for (const lost of [false, true]) {const wire = createWorkflowWire();@@ -482,10 +525,12 @@ test('a local copy with an edit no run sent stops every path before any requestawait p.sdk.updateElement('bpf', id, '/stages/0/name', 'Edited by hand');const [file] = flowCopy(dir, id);const bytes = fs.readFileSync(file);- for (const [flow, extra] of [[FLOW, {}], [GROWN, { opts: SWITCH }], [{ ...FLOW, status: 'Draft' }, { opts: SWITCH }], [FLOW, {}]]) {+ for (const [flow, extra] of [[FLOW, {}], [GROWN, { opts: SWITCH }], [{ ...FLOW, status: 'Draft' }, { opts: SWITCH }], [FLOW, {}], [FLOW, { freshTable: 'account' }]]) {const out = await settle(wire, dir, flow, extra);assert.equal(out.error && out.error.code, 'create-completion-required');assert.equal(causeCategory(out.error), 'workspace-copy-unsent-edits');+ // A table the build just created changes nothing here (#796): the stop is the local copy's, never the lag's.+ assert.equal(require('../lib/retry-policy.js').isFreshTableReadLag(out.error), false);assert.deepEqual(wire.log.slice(out.from), [], 'no request at all');assert.deepEqual(fs.readFileSync(file), bytes, 'the local copy is kept');}diff --git a/plugins/model-apps/scripts/tests/build-model-app.test.js b/plugins/model-apps/scripts/tests/build-model-app.test.jsindex 4092e5a44..9e212f753 100644--- a/plugins/model-apps/scripts/tests/build-model-app.test.js+++ b/plugins/model-apps/scripts/tests/build-model-app.test.js@@ -533,7 +533,10 @@ const NO_TABLE_WORDS = 'Saved Query cannot have returnedTypeCode of 0 and a nonconst notInCache = (table) => `The entity with a name = '${table}' with namemapping = 'Logical' was not found in the MetadataCache.LazyDynamicMetadataCache with version 9495075 and timestamp 9495075`;// A build against a stateful organization: a create acknowledges a table once and `findTables` finds it from then on (as the real one does), so the build's second attempt REUSES the table — it is not "created"// again. `existing` names tables that were there before the build started. The default-view enrichment fails as `answers(table, n)` says, n counting that table's tries across all attempts.-const freshTableBuild = async ({ answers, existing = [], publish = false, retryDelayMs = 0 }) => {+// With `lookups(kind, table, n, name)` (#796), the SDK's lookup of a view or chart by name fails as it says, n counting that artifact's lookups across all attempts, and the organization keeps what the build creates, so a later+// attempt's lookup finds a view or chart an earlier one made (as the real one does) and nothing is created twice. `formLookups(table, n)` does the same for the build's lookup of a spec-named form. `spec` replaces the+// support-desk sample.+const freshTableBuild = async ({ answers = () => null, lookups = null, formLookups = null, existing = [], publish = false, retryDelayMs = 0, spec = desk }) => {const { sdk, calls } = mockSdk();const tables = new Map(existing.map((logical) => [logical, { logicalName: logical, entitySetName: `${logical}s` }]));const create = sdk.createTable;@@ -562,15 +565,47 @@ const freshTableBuild = async ({ answers, existing = [], publish = false, retryDif (failure) throw failure;return enrich(logical, ...rest);};+ const lookupTries = {};+ const formTries = {};+ if (lookups || formLookups) {+ const made = new Map();+ const createArtifact = sdk.createArtifact;+ sdk.createArtifact = (t, def) => {+ const art = createArtifact(t, def);+ made.set(`${t}|${String(def.entityLogicalName).toLowerCase()}|${def.name}`, art.id);+ return art;+ };+ sdk.findArtifact = async (kind, identity) => {+ const table = String(identity.entity).toLowerCase();+ const key = `${kind}|${table}|${identity.name}`;+ lookupTries[key] = (lookupTries[key] || 0) + 1;+ const failure = lookups ? lookups(kind, table, lookupTries[key], identity.name) : null;+ if (failure) throw failure;+ return made.get(key) || null;+ };+ // The build's own lookup of a spec-named form (sdk-build.js resolveExistingFormId), whose filter is+ // objecttypecode eq 'new_ticket' and name eq 'Ticket' and type eq 2+ const query = sdk.queryRecords;+ sdk.queryRecords = async (entity, q, ...rest) => {+ const named = entity === 'systemform' && /objecttypecode eq '([^']+)' and name eq '((?:[^']|'')*)'/.exec((q && q.filter) || '');+ if (!named) return query(entity, q, ...rest);+ const table = named[1];+ const key = `form|${table}|${named[2].replace(/''/g, "'")}`;+ formTries[key] = (formTries[key] || 0) + 1;+ const failure = formLookups ? formLookups(table, formTries[key]) : null;+ if (failure) throw failure;+ return made.has(key) ? [{ formid: made.get(key) }] : [];+ };+ }const events = [];const journal = { path: 'x', record: (e) => events.push(e), close: () => {} };let result = null;let halt = null;try {- result = await buildModelApp(desk, { apply: true, env: 'https://x', ...(publish ? { publish: true } : {}), retryDelayMs }, { sdk, journal });+ result = await buildModelApp(spec, { apply: true, env: 'https://x', ...(publish ? { publish: true } : {}), retryDelayMs }, { sdk, journal });} catch (err) { halt = err; }const creates = (logical) => calls.filter((c) => c[0] === 'createTable' && String(c[1].schemaName).toLowerCase() === logical).length;- return { result, halt, events, tries, calls, creates };+ return { result, halt, events, tries, calls, creates, lookupTries, formTries };};const noTable = (code = '0x80040203') => lagAnswer(NO_TABLE_WORDS, code);@@ -630,6 +665,177 @@ test('isTransientHalt: the lag of a created table is read only where the build massert.strictEqual(isTransientHalt(lagAnswer(LAG_WORDS), { spec: desk }), true);});+// #796: a READ of a table the build has only just created meets the same metadata-cache lag — live, the lookup of a view by name on a new table answered 400 `0x80041102` and the build stopped, to be run again by hand.+// The read is made again where it failed, only for a table this invocation created, and each time from the invocation's one retry allowance (build-model-app.js retryFreshRead), so nothing already sent is sent again;+// a lookup that answered is never replayed as a create.+test('transient auto-retry (#796): a view or chart looked up on a table the build just created is read again in place, and the build completes with each created once', async () => {+ const table = 'new_ticket';+ const lagged = { view: 'Active Tickets', chart: 'Tickets by Priority' };+ for (const kind of ['view', 'chart']) {+ const { result, halt, events, creates, calls, lookupTries } = await freshTableBuild({+ lookups: (k, t, n, name) => (k === kind && t === table && name === lagged[kind] && n <= 2 ? lagAnswer(notInCache(table), '0x80041102') : null),+ });+ assert.strictEqual(halt, null, `${kind}: no halt (${halt && halt.message})`);+ assert.strictEqual(result.ok, true, kind);+ assert.strictEqual(events.filter((e) => e.status === 'retry').length, 2, `${kind}: two retries were journaled`);+ assert.strictEqual(creates(table), 1, `${kind}: the table was created once`);+ assert.strictEqual(lookupTries[`${kind}|${table}|${lagged[kind]}`], 3, `${kind}: the third lookup answered`);+ // Each view and chart of the sample is created exactly once, and nothing else was looked up again.+ assert.strictEqual(calls.filter((c) => c[0] === 'createArtifact' && c[1] === 'view').length, 3, `${kind}: three views, each created once`);+ assert.strictEqual(calls.filter((c) => c[0] === 'createArtifact' && c[1] === 'chart').length, 2, `${kind}: two charts, each created once`);+ assert.ok(Object.entries(lookupTries).every(([k, n]) => k === `${kind}|${table}|${lagged[kind]}` || !/^(view|chart)\|/.test(k) || n === 1), `${kind}: every other view and chart looked up once`);+ }+});++test('transient auto-retry (#796): a lookup on a just-created table that never answers spends the invocation\'s three retries, not three for each lookup, and surfaces the platform\'s answer', async () => {+ const table = 'new_ticket';+ for (const kind of ['view', 'chart']) {+ const { halt, events, creates, lookupTries } = await freshTableBuild({ lookups: (k, t) => (k === kind && t === table ? lagAnswer(notInCache(table), '0x80041102') : null) });+ assert.ok(halt, `${kind}: the build halted`);+ assert.match(String(halt.message) + String(halt.cause && halt.cause.message), /not found in the MetadataCache/, kind);+ assert.strictEqual(events.filter((e) => e.status === 'retry').length, 3, `${kind}: three retries, then the halt`);+ // Every lookup of the kind on the table is lagged (one view; two charts, which may be read side by side): one read each, and the three retries between them.+ const tried = Object.entries(lookupTries).filter(([k]) => k.startsWith(`${kind}|${table}|`)).map(([, n]) => n);+ assert.strictEqual(tried.reduce((a, b) => a + b, 0), tried.length + 3, `${kind}: ${tried.length} lookups and three retries in all`);+ assert.strictEqual(creates(table), 1, `${kind}: one create`);+ }+});++test('transient auto-retry (#796): a lookup answer for a table the build did not create, for another table, or of any other kind halts at once', async () => {+ const table = 'new_ticket';+ const ambiguous = () => Object.assign(new Error('2 views named "Active Tickets" on new_ticket'), { code: 'AMBIGUOUS_ARTIFACT' });+ const final = async (label, kind, answer, existing = []) => {+ const { halt, events, lookupTries } = await freshTableBuild({ existing, lookups: (k, t) => (k === kind && t === table ? answer() : null) });+ assert.ok(halt, `${label}: the build halted`);+ assert.strictEqual(events.filter((e) => e.status === 'retry').length, 0, `${label}: no retry`);+ const tried = Object.entries(lookupTries).filter(([k]) => k.startsWith(`${kind}|${table}|`)).map(([, n]) => n);+ assert.strictEqual(Math.max(...tried), 1, `${label}: one lookup only`);+ };+ for (const kind of ['view', 'chart']) {+ await final(`${kind}: a table that was there before the build`, kind, () => lagAnswer(notInCache(table), '0x80041102'), [table]);+ await final(`${kind}: the cache answer names another table`, kind, () => lagAnswer(notInCache('new_elsewhere'), '0x80041102'));+ await final(`${kind}: the cache words under another code`, kind, () => lagAnswer(notInCache(table), '0x80040220'));+ await final(`${kind}: an unrelated 400`, kind, () => lagAnswer('The value of the attribute is not valid', '0x80040265'));+ await final(`${kind}: two rows share the name`, kind, ambiguous);+ }+});++test('transient auto-retry (#796): with no lag, each view and chart is looked up once and nothing is retried', async () => {+ const { result, halt, events, lookupTries } = await freshTableBuild({ lookups: () => null });+ assert.strictEqual(halt, null, halt && halt.message);+ assert.strictEqual(result.ok, true);+ assert.strictEqual(events.filter((e) => e.status === 'retry').length, 0);+ assert.deepStrictEqual(Object.fromEntries(Object.entries(lookupTries).filter(([k]) => /^(view|chart)\|/.test(k))), {+ 'view|new_customer|Active Customers': 1, 'view|new_ticket|Active Tickets': 1, 'view|new_comment|Active Comments': 1,+ 'chart|new_ticket|Tickets by Priority': 1, 'chart|new_ticket|Tickets by Status': 1,+ });+});++// A declared view (views[].reconcile "declared") keeps a failed lookup as an "unknown" finding, which settles as a stop. On a table the build just created, the finding's own read failure is the lag above,+// so the view is planned again in place within the build's retries (and, once they are spent, the step throws that failure); on any other table, or for any other failure, the finding settles as before and the build stops with it.+const declaredDesk = () => {+ const spec = jclone(desk);+ spec.views.find((v) => v.entity === 'new_ticket').reconcile = 'declared';+ return spec;+};+test('transient auto-retry (#796): a declared view whose lookup meets the lag of a just-created table is planned again in place; any other unread lookup still stops the build', async () => {+ const table = 'new_ticket';+ const lag = () => lagAnswer(notInCache(table), '0x80041102');+ const ok = await freshTableBuild({ spec: declaredDesk(), lookups: (k, t, n) => (k === 'view' && t === table && n <= 2 ? lag() : null) });+ assert.strictEqual(ok.events.filter((e) => e.status === 'retry').length, 2, 'two retries');+ assert.strictEqual(ok.lookupTries[`view|${table}|Active Tickets`], 3, 'the third lookup answered');+ // This double has no creation port for a declared view, so the third attempt's create is refused: the step went past the lookup, which is what is pinned here.+ assert.ok(ok.halt, 'the double refuses the declared create');+ assert.doesNotMatch(String(ok.halt.message), /view-lookup-unreadable/);+ assert.match(String(ok.halt.message), /view-create-refused/);+ for (const [label, answer, existing] of [+ ['a table that was there before the build', lag, [table]],+ ['the cache answer names another table', () => lagAnswer(notInCache('new_elsewhere'), '0x80041102'), []],+ ['an unrelated 400', () => lagAnswer('The value of the attribute is not valid', '0x80040265'), []],+ ]) {+ const { halt, events, lookupTries } = await freshTableBuild({ spec: declaredDesk(), existing, lookups: (k, t) => (k === 'view' && t === table ? answer() : null) });+ assert.ok(halt, `${label}: the build halted`);+ assert.match(String(halt.message), /view-lookup-unreadable/, `${label}: the finding settles as it always did`);+ assert.strictEqual(events.filter((e) => e.status === 'retry').length, 0, `${label}: no retry`);+ assert.strictEqual(lookupTries[`view|${table}|Active Tickets`], 1, `${label}: one lookup`);+ }+});++// A form looked up by name on a new table meets the same lag. A failed lookup is never "no form": the platform makes a stock "Information" Main form with every table, and an earlier attempt may have+// made the spec's form, so either miss would create a second form of the same name. On a table this invocation created the read is made again in place, whichever attempt meets it; on a table that was+// there before, the build stops with the service's answer and creates nothing.+test('transient auto-retry (#796): a form lookup that meets the lag on a table the build created is read again rather than create the form twice; on a table that was there before it stops the build', async () => {+ const table = 'new_ticket';+ const lag = () => lagAnswer(notInCache(table), '0x80041102');+ const forms = (r) => r.calls.filter((c) => c[0] === 'createArtifact' && c[1] === 'form').length;+ // The app is looked up after the forms: its first lookup fails as the service can (a 503), so the build runs a second attempt, whose first form lookup on the table meets the lag.+ const appOnce = (k, t, n) => (k === 'app' && n === 1 ? lagAnswer('The service is unavailable.', null, 503) : null);+ const later = await freshTableBuild({ lookups: appOnce, formLookups: (t, n) => (t === table && n === 2 ? lag() : null) });+ assert.strictEqual(later.halt, null, later.halt && later.halt.message);+ assert.strictEqual(later.events.filter((e) => e.status === 'retry').length, 2, 'the 503, then the lag');+ assert.strictEqual(later.formTries[`form|${table}|Ticket`], 3, 'the third lookup found the form the first attempt made');+ assert.strictEqual(forms(later), 3, 'three forms, each created once');+ const first = await freshTableBuild({ lookups: () => null, formLookups: (t, n) => (t === table && n === 1 ? lag() : null) });+ assert.strictEqual(first.halt, null, first.halt && first.halt.message);+ assert.strictEqual(first.events.filter((e) => e.status === 'retry').length, 1, 'the attempt that created the table reads it again too');+ assert.strictEqual(first.formTries[`form|${table}|Ticket`], 2);+ assert.strictEqual(forms(first), 3);+ const existing = await freshTableBuild({ existing: [table], lookups: appOnce, formLookups: (t, n) => (t === table && n === 2 ? lag() : null) });+ assert.ok(existing.halt, 'a table the build did not create: the lag is not read as "no form", and the build stops');+ assert.match(String(existing.halt.message) + String(existing.halt.cause && existing.halt.cause.message), /not found in the MetadataCache/);+ assert.strictEqual(existing.events.filter((e) => e.status === 'retry').length, 1, 'only the 503 was retried');+ assert.strictEqual(existing.formTries[`form|${table}|Ticket`], 2, 'read once in each attempt');+ assert.strictEqual(forms(existing), 3, 'the forms of the first attempt, and none in the second');+});++// The preflight gate (discoverOpDiffState) reads each explicit-layout form to see what a prune would remove. Its lookup's MetadataCache answer proves "no form" only when the table itself reads absent:+// on a table that is there it is the lag, and skipping the form would skip the gate's check of what the build then removes from it.+test('discoverOpDiffState (#796): a form lookup that meets the MetadataCache answer is "not deployed" only when its table reads absent', async () => {+ const spec = { solution: { uniqueName: 'Desk' }, app: { name: 'Desk' }, entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns: [] }],+ forms: [{ entity: 'new_ticket', name: 'Ticket', layout: 'explicit', tabs: [{ label: 'General', sections: [{ label: 'A', fields: ['new_name'] }] }] }] };+ const env = (tablePresent) => {+ const probes = [];+ return {+ probes,+ provision: {+ queryRecords: async (set) => {+ if (set !== 'systemform') return [];+ throw Object.assign(new Error("The entity with a name = 'new_ticket' with namemapping = 'Logical' was not found in the MetadataCache.LazyDynamicMetadataCache"), { statusCode: 400 });+ },+ // The table probe, `/EntityDefinitions(LogicalName='new_ticket')?$select=LogicalName,EntitySetName`: 200 with the table, or 404.+ dataverse: { get: async (url) => { probes.push(url); return tablePresent ? { status: 200, body: { LogicalName: 'new_ticket', EntitySetName: 'new_tickets' } } : { status: 404 }; } },+ },+ };+ };+ const absent = env(false);+ const out = await discoverOpDiffState(spec, absent.provision);+ assert.deepStrictEqual(out.forms, [], 'the table reads absent: no form to check');+ assert.strictEqual(absent.probes.length, 1);+ const present = env(true);+ await assert.rejects(() => discoverOpDiffState(spec, present.provision), /not found in the MetadataCache/, 'the table is there: the gate stops rather than skip the form');++ // A table whose labels are localized is asked about as the data-model step asks: an inconclusive narrow read is read again, and the broad,+ // label-bearing table list — which ahead of a localized create keeps only the base-language label — is never the answer.+ const localized = { ...spec, entities: [{ ...spec.entities[0], displayName: { 1033: 'Ticket', 3082: 'Entrada' } }] };+ const flaky = env(false);+ let listReads = 0;+ let narrowReads = 0;+ let stuck = false;+ flaky.provision.findTables = async () => { listReads += 1; return []; };+ flaky.provision.dataverse.get = async () => ((narrowReads++ === 0 || stuck) ? { status: 503, body: {} } : { status: 404 });+ assert.deepStrictEqual((await discoverOpDiffState(localized, flaky.provision)).forms, []);+ assert.strictEqual(narrowReads, 2, 'the narrow read is read again');+ assert.strictEqual(listReads, 0, 'and never settled by the table list');+ stuck = true;+ await assert.rejects(() => discoverOpDiffState(localized, flaky.provision), (e) => e.code === 'table-probe-inconclusive', 'still inconclusive: the gate stops');+ assert.strictEqual(listReads, 0);+ // A plain table keeps the old fallback: one narrow read, then the list.+ stuck = false;+ narrowReads = 0;+ assert.deepStrictEqual((await discoverOpDiffState(spec, flaky.provision)).forms, []);+ assert.strictEqual(listReads, 1);+});+test('transient auto-retry: a transient halt is retried and then succeeds', async () => {const { sdk, calls } = mockSdk();let firstTable = true;diff --git a/plugins/model-apps/scripts/tests/creates-port.test.js b/plugins/model-apps/scripts/tests/creates-port.test.jsindex 400bdf846..e37062b6e 100644--- a/plugins/model-apps/scripts/tests/creates-port.test.js+++ b/plugins/model-apps/scripts/tests/creates-port.test.js@@ -230,9 +230,12 @@ test('the spec decides the mode: no createIdentity and no new feature intents is// (businessRules[].reconcile "declared") or a declared process flow (businessProcessFlows[].reconcile "declared"), the only places a build without createIdentity takes ids from a catalog. The business-rule// helper (rule-settlement.js) loads the catalog itself, so the engine's, the spec gate's and the rule reader's (declared-rule-io.js,// for verify and the managed download) requires of it are gated edges too. The process-flow helper (bpf-settlement.js) does the same,-// so the engine's, the spec gate's and the flow reader's (declared-bpf-io.js) requires of it are gated edges as well. Apart+// so the engine's, the spec gate's and the flow reader's (declared-bpf-io.js) requires of it are gated edges as well. The+// dashboard helper (dashboard-reconcile.js) derives its seed cell ids with creates-identity.js only on a declared dashboard's+// create, and its workspace scope (dashboard-recovery-workspace.js) reads a retained create copy with creates-local.js only for+// a declared dashboard; each through one lazy accessor, so those edges are gated too. Apart// from those gated edges the default build must load none of the new modules, and must still hand the engine the plain pass-through.-const GATED_EDGES = [['sdk-build.js', 'creates-stable-build.js'], ['sdk-build.js', 'creates-catalog.js'], ['sdk-build.js', 'rule-settlement.js'], ['app-spec.js', 'rule-settlement.js'], ['declared-rule-io.js', 'rule-settlement.js'], ['sdk-build.js', 'bpf-settlement.js'], ['app-spec.js', 'bpf-settlement.js'], ['declared-bpf-io.js', 'bpf-settlement.js']];+const GATED_EDGES = [['sdk-build.js', 'creates-stable-build.js'], ['sdk-build.js', 'creates-catalog.js'], ['sdk-build.js', 'rule-settlement.js'], ['app-spec.js', 'rule-settlement.js'], ['declared-rule-io.js', 'rule-settlement.js'], ['sdk-build.js', 'bpf-settlement.js'], ['app-spec.js', 'bpf-settlement.js'], ['declared-bpf-io.js', 'bpf-settlement.js'], ['dashboard-reconcile.js', 'creates-identity.js'], ['dashboard-recovery-workspace.js', 'creates-local.js']];const SCRIPTS = path.join(__dirname, '..');const NEW_MODULES = ['creates-identity.js', 'creates-capabilities.js', 'creates-port.js', 'creates-catalog.js'].map((f) => path.join(SCRIPTS, 'lib', f));function requireGraph(entry, { gated = false } = {}) {@@ -278,6 +281,13 @@ test('the default build loads none of the stable-identity modules and still wire// The flow reader likewise, through one lazy accessor called only for a committed flow group.assert.match(fs.readFileSync(path.join(SCRIPTS, 'lib', 'declared-bpf-io.js'), 'utf8'), /^const settlement = \(\) => require\('\.\/bpf-settlement\.js'\);$/m);assert.equal(fs.readFileSync(path.join(SCRIPTS, 'lib', 'declared-bpf-io.js'), 'utf8').match(/require\('\.\/bpf-settlement\.js'\)/g).length, 1);+ // The dashboard helper likewise, through one lazy accessor that only a declared dashboard's create calls.+ const dashboardHelper = fs.readFileSync(path.join(SCRIPTS, 'lib', 'dashboard-reconcile.js'), 'utf8');+ assert.match(dashboardHelper, /^const identity = \(\) => require\('\.\/creates-identity\.js'\);$/m);+ assert.equal(dashboardHelper.match(/require\('\.\/creates-identity\.js'\)/g).length, 1);+ const dashboardScope = fs.readFileSync(path.join(SCRIPTS, 'lib', 'dashboard-recovery-workspace.js'), 'utf8');+ assert.match(dashboardScope, /^const createsLocal = \(\) => require\('\.\/creates-local\.js'\);$/m);+ assert.equal(dashboardScope.match(/require\('\.\/creates-local\.js'\)/g).length, 1);assert.ok(graph.has(path.join(SCRIPTS, 'lib', 'creates-passthrough.js')));for (const m of NEW_MODULES) assert.ok(!graph.has(m), `${path.basename(m)} is not reachable from a default build`);const build = fs.readFileSync(path.join(SCRIPTS, 'build-model-app.js'), 'utf8');diff --git a/plugins/model-apps/scripts/tests/dashboard-settlement-real-bundle.test.js b/plugins/model-apps/scripts/tests/dashboard-settlement-real-bundle.test.jsindex 959587fe8..6bff8593c 100644--- a/plugins/model-apps/scripts/tests/dashboard-settlement-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/dashboard-settlement-real-bundle.test.js@@ -4,41 +4,30 @@// published layer per systemform row (helpers/managed-wire.js). Each test counts what reaches the wire: the content// writes (POST/PATCH systemforms) and the PublishXml requests, by dashboard id.const fs = require('node:fs');+const path = require('node:path');+const { spawnSync } = require('node:child_process');const test = require('node:test');const assert = require('node:assert/strict');const { makeTempDir } = require('./helpers/temp-dirs.js');const { createManagedWire, sdkOver, clientOver } = require('./helpers/managed-wire.js');+const { canonicalJson } = require('../lib/reconcile-common.js');const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');const X = require('./helpers/dashboard-formxml.js');const { openManagedContext } = require('../lib/managed-bindings.js');const { writeFileAtomic } = require('../lib/apply-snapshot-store.js');const { createPublicationBarrier } = require('../lib/publication-barrier.js');-const { createIntentCatalog } = require('../lib/creates-catalog.js');-const { environmentFingerprint } = require('../lib/page-ownership-records.js');-const { dashboardTileOpts, dashboardComponent } = require('../lib/sdk-build.js');-const { settleDeclaredDashboard, publishDeclaredDashboard, dashboardKey, projectDashboard, preservationMatches, committedProjectionInput, committedDeclaration, canonicalDeclaration, validateDeclaredDashboard } = require('../lib/dashboard-reconcile.js');+const { publishDeclaredDashboard, projectDashboard, preservationMatches, committedProjectionInput, committedDeclaration, canonicalDeclaration, validateDeclaredDashboard } = require('../lib/dashboard-reconcile.js');const { createAttemptSendObserver, publishManagedScope } = require('../lib/managed-feature-contract.js');const { LAYER_READERS } = require('../lib/managed-layer-readers.js');+const { ENV, APP, SOL, OPEN, ALL, catalogFor, declared, settle, makerRun, treeBytes, scopedSettle } = require('./helpers/dashboard-maker-run.js');// The $select of the publication read of a systemform's saved layer (systemform-published.js), with and without its// root fields; the SDK's own fetch selects more, so a probe that injects between the two reads can tell them apart.const PUBLICATION_SELECTS = new Set(['formid,name,description,formxml', 'formid,name,description,formxml,type,objecttypecode']);-const ENV = 'https://contoso.crm.dynamics.com';-const APP = 'contoso_app';-const SOL = 'contoso_solution';-const FP = environmentFingerprint(ENV);-const OPEN = '66666666-0000-4000-8000-000000000001';-const ALL = '66666666-0000-4000-8000-000000000002';-const MINE = '66666666-0000-4000-8000-000000000003';const DID = '55555555-0000-4000-8000-000000000001';const OTHER = '55555555-0000-4000-8000-000000000009';const C_OPEN = 'c1c1c1c1-0000-4000-8000-000000000001';const C_FOREIGN = 'c1c1c1c1-0000-4000-8000-000000000002';-const spec = { views: [{ entity: 'incident', name: 'Open cases' }, { entity: 'incident', name: 'All cases' }, { entity: 'incident', name: 'My cases' }] };-const built = { created: { views: { 'incident|Open cases': OPEN, 'incident|All cases': ALL, 'incident|My cases': MINE }, charts: {} } };-const resolveTile = (tile) => dashboardTileOpts(spec, tile, built);--const halt = (phase, label, code, { cause } = {}) => Object.assign(new Error(`${label}: ${code}`), { phase, code, cause, retry: 'never' });const codeOf = async (p) => { try { await p; } catch (e) { return e.code; } return null; };const contentWrites = (wire) => wire.writes().filter((e) => /^systemforms/i.test(e.path));// The binding store's next file write fails once, when `failing.armed` is set: a crash at that persistence boundary.@@ -52,9 +41,6 @@ function failNextStoreWrite() {};return { failing, deps };}-const catalogFor = (d) => createIntentCatalog([{ catalogKind: 'dashboard', key: dashboardKey(d), scope: { kind: 'solution', solution: SOL }, declaration: { scopeType: 'Standard', name: d.name } }]);-const declared = (tiles, extra = {}) => ({ name: 'Ops', reconcile: 'declared', tiles, ...extra });-// The build-wide send observer is installed on the client every send goes through (the build installs it once for the// run); `observer: false` is a run without it.async function world({ observer = true, platform } = {}) {@@ -76,14 +62,6 @@ async function rerun(w, { observer = true } = {}) {return { ...w, barrier, sdk, store, observer: obs };}-// The maker's typed adoption approval of `dashboard:ops` is given unless a test passes its own `approvals`.-const ADOPT = { adopt: new Set(['dashboard:ops']) };-const settle = (w, dashboard, extra = {}) => settleDeclaredDashboard({- dashboard, catalog: catalogFor(dashboard), sdk: w.sdk, store: w.store, barrier: w.barrier, halt, resolveTile, toComponent: dashboardComponent,- ensureMembership: async () => undefined, ctx: { appUniqueName: APP, environmentFingerprint: FP }, approvals: ADOPT,- provisionedLanguages: async () => w.wire.languages(),- ...(w.observer ? { sendObserver: w.observer } : {}), ...extra,-});const publish = (w, key, id) => publishDeclaredDashboard({ store: w.store, barrier: w.barrier, sdk: w.sdk, key, id });// A maker's dashboard: one bound-able list tile and one foreign custom control, published.@@ -496,6 +474,192 @@ test('a create whose answer was lost: the next run binds it only with the typedassert.deepEqual(approved.store.readGroup('dashboard', 'ops').committed.records.map((r) => r.origin), ['adopted', 'adopted']);});+// --- A create acknowledged by its durable receipt before the SDK recorded it (the retained workspace copy) ----------------++const errorOf = async (p) => { try { await p; } catch (e) { return e; } return null; };+const categoryOfErr = (e) => e && ((e.cause && e.cause.category) || e.category);+const causeChain = (e) => { const chain = []; for (let c = e; c && chain.length < 8; c = c.cause) chain.push(c); return chain; };+const sha256Hex = (text) => require('node:crypto').createHash('sha256').update(text, 'utf8').digest('hex');+// The receipt calls a store makes, recorded as they are made (the store handle's own methods, called through).+function recordReceipts(store) {+ const calls = { draft: [], dispatch: [], answer: [] };+ for (const [name, list] of [['noteDashboardCreateDraft', calls.draft], ['noteDashboardCreateDispatch', calls.dispatch], ['noteDashboardCreateAnswer', calls.answer]]) {+ const original = store[name].bind(store);+ store[name] = (token, args) => { list.push(args); return original(token, args); };+ }+ return calls;+}++for (const secondLanguage of [null, 1036]) {+ test(`a new declared dashboard's create receipt holds the exact body the POST sent and the draft its copy was assembled to${secondLanguage ? ', with its captions in a second language' : ''}`, async () => {+ const w = await world(secondLanguage ? { platform: { secondLanguage } } : undefined);+ const calls = recordReceipts(w.store);+ const d = declared([{ key: 'open', type: 'list', view: 'Open cases' }, { key: 'all', type: 'list', view: 'All cases' }]);+ const id = catalogFor(d).identityFor('dashboard', 'ops').derivedId;+ const out = await settle(w, d);+ assert.equal(out.result.committed, true);+ const posts = w.wire.log.filter(isCreate);+ assert.equal(posts.length, 1);+ assert.equal(calls.draft.length, 1, 'one receipt, recorded before the POST');+ assert.equal(calls.draft[0].bodySha256, sha256Hex(canonicalJson(posts[0].body)), 'the body hash is the hash of the body sent');+ assert.equal(calls.dispatch.length, 1);+ assert.equal(calls.answer.length, 1, 'the success acknowledged it');+ if (secondLanguage) assert.match(posts[0].body.formxml, new RegExp(`languagecode="${secondLanguage}"`), 'the tiles were sent with their second-language captions');+ const root = w.store.readGroup('dashboard', 'ops').committed.records.find((r) => r.kind === 'dashboard');+ assert.equal(root.origin, 'created');+ assert.deepEqual(root.localCreateDraft, { formatVersion: 1, rootId: id, attemptToken: root.localCreateDraft.attemptToken, draftSha256: calls.draft[0].draftSha256, bodySha256: calls.draft[0].bodySha256 });+ });+}++test('a create whose assembled copy is not the draft that was modelled is not sent, and keeps no receipt', async () => {+ const w = await world();+ const calls = recordReceipts(w.store);+ const updateElement = w.sdk.updateElement.bind(w.sdk);+ w.sdk.updateElement = async (kind, id, pointer, value) => updateElement(kind, id, pointer, pointer === '/bag' ? { ...value, a: [...(value.a || []), ['extra', '1']] } : value);+ const d = declared([{ key: 'open', type: 'list', view: 'Open cases' }]);+ assert.equal(await codeOf(settle(w, d)), 'create-local-draft-changed');+ assert.equal(w.wire.log.filter(isCreate).length, 0, 'nothing sent');+ assert.equal(calls.draft.length, 0, 'no receipt');+});++test('a create acknowledged by its receipt before the SDK recorded it recovers from the retained copy: one POST, created, published, no approval, the copy untouched; the next build does not stop', async () => {+ const workspaceDir = makeTempDir('dash-maker-ws-');+ const w = await makerRun({ workspaceDir, cutCreateAnswer: true });+ const d = declared([{ key: 'open', type: 'list', view: 'Open cases' }]);+ const id = catalogFor(d).identityFor('dashboard', 'ops').derivedId;+ assert.ok(await codeOf(settle(w, d)), 'the lost answer stops the run');+ assert.ok(w.wire.saved.has(id), 'the create landed');+ assert.equal(w.wire.log.filter(isCreate).length, 1);+ assert.equal(w.store.readGroup('dashboard', 'ops').pending.dashboardCreate.acknowledged, true, 'the receipt is acknowledged');++ const next = await makerRun({ wire: w.wire, dir: w.dir, workspaceDir });+ const copy = treeBytes(workspaceDir);+ const writes = w.wire.writes().length;+ const out = await scopedSettle(next, d, { approvals: {} }, { publishToo: true });+ assert.equal(out.isolated, true, 'the settle ran in an isolated workspace');+ assert.deepEqual(out.settled.result, { committed: true, recovered: true });+ assert.equal(out.settled.id, id);+ assert.equal(out.published.sent, true);+ assert.ok(w.wire.published.has(id), 'published');+ assert.deepEqual(w.wire.writes().slice(writes).map((e) => `${e.method} ${e.path}`), ['POST PublishXml'], 'no create and no content write: only the publish');+ assert.equal(w.wire.log.filter(isCreate).length, 1, 'one POST in the dashboard\'s life');+ const group = next.store.readGroup('dashboard', 'ops');+ assert.equal(group.pending, null);+ assert.deepEqual(group.committed.records.map((r) => r.origin), ['created', 'created'], 'its own acknowledged create');+ assert.equal(group.committed.records.find((r) => r.kind === 'dashboard').localCreateDraft.rootId, id);+ assert.deepEqual(treeBytes(workspaceDir), copy, 'the maker\'s copy is kept byte for byte');++ const third = await makerRun({ wire: w.wire, dir: w.dir, workspaceDir });+ const later = w.wire.writes().length;+ const again = await scopedSettle(third, d, { approvals: {} });+ assert.equal(again.isolated, true, 'the create evidence leads the next build past its own retained copy again');+ assert.equal(again.settled.result.noop, true);+ assert.equal(w.wire.writes().length, later, 'nothing sent');+ assert.deepEqual(treeBytes(workspaceDir), copy);+});++test('a retained copy edited after its acknowledged create is not recovered over: the build stops on the unsent edits and keeps the copy', async () => {+ const workspaceDir = makeTempDir('dash-maker-ws-');+ const w = await makerRun({ workspaceDir, cutCreateAnswer: true });+ const d = declared([{ key: 'open', type: 'list', view: 'Open cases' }]);+ const id = catalogFor(d).identityFor('dashboard', 'ops').derivedId;+ assert.ok(await codeOf(settle(w, d)));+ const next = await makerRun({ wire: w.wire, dir: w.dir, workspaceDir });+ await next.sdk.updateElement('dashboard', id, '/description', 'edited locally');+ const copy = treeBytes(workspaceDir);+ const writes = w.wire.writes().length;+ const err = await errorOf(scopedSettle(next, d, { approvals: {} }));+ assert.equal(err && err.code, 'create-completion-required');+ assert.equal(categoryOfErr(err), 'workspace-copy-unsent-edits');+ assert.equal(w.wire.writes().length, writes, 'nothing sent');+ assert.equal(next.store.readGroup('dashboard', 'ops').committed, null, 'nothing bound');+ assert.deepEqual(treeBytes(workspaceDir), copy, 'the copy is kept as the maker left it');+});++// A build killed at the create's durable acknowledgement, and the next build in a new OS process. The kill is+// `process.exit` inside the store's acknowledgement write, so nothing the first process held in memory (its SDK, its+// store handle, its send observer) can reach the second: that one sees only the binding store and the maker's SDK+// workspace on disk, and a service that still holds the created row (helpers/dashboard-create-crash-child.js).+function crashThenRecover(timing) {+ const root = makeTempDir('dash-crash-');+ const files = {+ timing,+ dir: path.join(root, 'store'),+ workspaceDir: path.join(root, 'workspace'),+ wireFile: path.join(root, 'wire.json'),+ crashFile: path.join(root, 'crash.json'),+ output: path.join(root, 'recover.json'),+ };+ fs.mkdirSync(files.dir);+ fs.mkdirSync(files.workspaceDir);+ const env = { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1' };+ delete env.NODE_TEST_CONTEXT;+ const child = (action) => {+ const input = path.join(root, `${action}-input.json`);+ fs.writeFileSync(input, JSON.stringify({ ...files, action }));+ return spawnSync(process.execPath, [path.join(__dirname, 'helpers', 'dashboard-create-crash-child.js'), input], { env, encoding: 'utf8', timeout: 120000 });+ };+ const crashed = child('crash');+ assert.equal(crashed.status, 77, `the first build is killed at the acknowledgement: ${crashed.stderr}`);+ const recovered = child('recover');+ assert.equal(recovered.status, 0, recovered.stderr);+ return { crash: JSON.parse(fs.readFileSync(files.crashFile, 'utf8')), next: JSON.parse(fs.readFileSync(files.output, 'utf8')) };+}++test('a build killed just BEFORE its create is durably acknowledged: the next build in a new process stops on the unsent copy, sends nothing, binds nothing and keeps the copy', () => {+ const { crash, next } = crashThenRecover('before');+ assert.notEqual(next.pid, crash.pid, 'two OS processes');+ assert.equal(crash.posts, 1, 'the create reached the service');+ assert.equal(crash.acknowledged, false, 'and the store never recorded it as acknowledged');+ assert.equal(next.error && next.error.code, 'create-completion-required', next.error && next.error.message);+ assert.equal(next.error.category, 'workspace-copy-unsent-edits', 'recovery stays the maker\'s');+ assert.equal(next.posts, 0, 'no second create');+ assert.deepEqual(next.writes, [], 'nothing sent');+ assert.equal(next.origins, null, 'nothing bound');+ assert.deepEqual(next.sourceAtStart, crash.source, 'the copy the killed build left');+ assert.deepEqual(next.sourceAtEnd, crash.source, 'is kept byte for byte');+});++test('a build killed just AFTER its create is durably acknowledged: the next build in a new process recovers it with no second create and no approval, binds it as created, publishes it and keeps the copy', () => {+ const { crash, next } = crashThenRecover('after');+ assert.notEqual(next.pid, crash.pid, 'two OS processes');+ assert.equal(crash.posts, 1, 'the create reached the service');+ assert.equal(crash.acknowledged, true, 'and the store recorded it as acknowledged before the kill');+ assert.equal(next.error, null, next.error && `${next.error.code}: ${next.error.message}`);+ assert.deepEqual(next.result, { committed: true, recovered: true });+ assert.equal(next.settledId, next.id);+ assert.equal(next.isolated, true, 'the settle ran in an isolated workspace');+ assert.equal(next.posts, 0, 'no second create');+ assert.deepEqual(next.writes, ['POST PublishXml'], 'no content write: only the publish');+ assert.equal(next.publishSent, true);+ assert.equal(next.published, true, 'published');+ assert.equal(next.pending, false);+ assert.deepEqual(next.origins, ['created', 'created'], 'its own acknowledged create, not an adoption');+ assert.deepEqual(next.sourceAtStart, crash.source, 'the copy the killed build left');+ assert.deepEqual(next.sourceAtEnd, crash.source, 'is kept byte for byte');+});++for (const step of ['dispatch', 'answer']) {+ test(`a create whose receipt ${step} cannot be written ${step === 'dispatch' ? 'is not sent' : 'is sent once and stays unacknowledged'}, and the build stops with the store's own error`, async () => {+ const { failing, deps } = failNextStoreWrite();+ const w = await makerRun({ workspaceDir: makeTempDir('dash-maker-ws-'), deps });+ const name = step === 'dispatch' ? 'noteDashboardCreateDispatch' : 'noteDashboardCreateAnswer';+ const original = w.store[name].bind(w.store);+ let thrown = null;+ w.store[name] = (token, args) => {+ failing.armed = true;+ try { return original(token, args); } catch (e) { thrown = e; throw e; }+ };+ const d = declared([{ key: 'open', type: 'list', view: 'Open cases' }]);+ const err = await errorOf(settle(w, d));+ assert.ok(thrown && thrown.code, 'the store refused the receipt write');+ assert.ok(causeChain(err).some((c) => c.code === thrown.code), `the store's own code is kept: ${causeChain(err).map((c) => c.code).join(', ')}`);+ assert.equal(w.wire.log.filter(isCreate).length, step === 'dispatch' ? 0 : 1);+ const pending = w.store.readGroup('dashboard', 'ops').pending;+ assert.equal(pending.dashboardCreate.acknowledged, false, 'nothing acknowledged it');+ });+}+test('a pinned dashboard is not the maker\'s consent to manage it: a write to it needs the typed adoption approval', async () => {const w = await world();putExisting(w.wire);diff --git a/plugins/model-apps/scripts/tests/download-label-language-real-bundle.test.js b/plugins/model-apps/scripts/tests/download-label-language-real-bundle.test.jsindex 42c3f11cc..674989496 100644--- a/plugins/model-apps/scripts/tests/download-label-language-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/download-label-language-real-bundle.test.js@@ -119,9 +119,9 @@ test('label language: rebuilt into a fresh environment without Spanish, the builassert.deepEqual(step.unexpected, []);const said = step.error ? step.error.message : JSON.stringify(step.value && step.value.result);assert.match(said, /not provisioned in this organization: 3082/, 'the language it lacks is named');- // The build's language guard stands at the start of the data-model phase, after the solution phase has made the solution and its- // publisher: no table, column or app is written — no Spanish text is stored as an English label.- assert.deepEqual(Object.keys(step.writes).sort(), ['POST publishers', 'POST solutions']);+ // The build's language guard stands before its first write, ahead of the solution phase: no publisher, solution, table, column or app is+ // written — no Spanish text is stored as an English label, and nothing is left behind to clean up.+ assert.deepEqual(Object.keys(step.writes).sort(), []);assert.equal(fresh.metadata.tables.get('contoso_pedido'), undefined);});diff --git a/plugins/model-apps/scripts/tests/download-lookup-label-language-real-bundle.test.js b/plugins/model-apps/scripts/tests/download-lookup-label-language-real-bundle.test.jsindex 37f8ff751..6a3aa9938 100644--- a/plugins/model-apps/scripts/tests/download-lookup-label-language-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/download-lookup-label-language-real-bundle.test.js@@ -139,6 +139,6 @@ test('lookup label language: a lookup labelled only in French, to a stock table,assert.deepEqual(step.unexpected, []);const said = step.error ? step.error.message : JSON.stringify(step.value && step.value.result);assert.match(said, /not provisioned in this organization: 1036/, 'the language it lacks is named');- assert.deepEqual(Object.keys(step.writes).sort(), ['POST publishers', 'POST solutions'], 'no table or lookup is written');+ assert.deepEqual(Object.keys(step.writes).sort(), [], 'nothing is written: no publisher, solution, table or lookup');assert.equal(fresh.metadata.tables.get('contoso_case'), undefined);});diff --git a/plugins/model-apps/scripts/tests/fresh-table-read-lag-real-bundle.test.js b/plugins/model-apps/scripts/tests/fresh-table-read-lag-real-bundle.test.jsnew file mode 100644index 000000000..a2ff49fac--- /dev/null+++ b/plugins/model-apps/scripts/tests/fresh-table-read-lag-real-bundle.test.js@@ -0,0 +1,229 @@+'use strict';+// A READ of a table the build has only just created can meet the table's metadata-cache lag (#796) — live, the lookup of a view by name on+// a new table answered+// HTTP 400 {"error":{"code":"0x80041102","message":"The entity with a name = 'contoso_ticket' with namemapping = 'Logical' was not found in the MetadataCache.LazyDynamicMetadataCache with version 9495075 and timestamp 9495075"}}+// These cases run the build over the REAL vendored SDK, the plugin's own HTTP client and the stateful fake Dataverse the lifecycle tests+// share (helpers/fake-lifecycle-org.js), with that answer injected on the named reads, and pin by what was sent and what the fake holds:+// * a lagged read is read again where it failed, so every write of the build — its saves, its publishes, their bodies — is exactly what+// the same build sends with no lag: only the reads differ;+// * the form looked up by name is never taken as missing because its read failed: on a table this invocation created the read is read+// again (the platform makes a stock "Information" Main form with every table, so a spec that names it would otherwise get a second);+// on a table that was there before, the build stops with the service's answer and creates nothing;+// * a lag that outlasts the build's retries stops it with the service's answer, and creates nothing.+const test = require('node:test');+const assert = require('node:assert/strict');+const crypto = require('node:crypto');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');+const { createLifecycleHarness } = require('./helpers/lifecycle-harness.js');++const TABLE = 'contoso_ticket';+const spec = {+ schemaVersion: 2,+ solution: { uniqueName: 'ContosoReadLag', displayName: 'Read Lag', publisherPrefix: 'contoso' },+ app: { name: 'Read Lag' },+ entities: [{+ schemaName: TABLE, displayName: 'Ticket', pluralName: 'Tickets',+ primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' },+ columns: [{ schemaName: 'contoso_priority', displayName: 'Priority', type: 'Choice', options: ['Low', 'High'] }],+ }],+ views: [{ name: 'Open Tickets', entity: TABLE, columns: ['contoso_name', 'contoso_priority'] }],+ charts: [{ name: 'Tickets by Priority', entity: TABLE, chartType: 'Pie', groupBy: 'contoso_priority', measure: 'count' }],+ forms: [{ name: 'Ticket Form', entity: TABLE, layout: 'auto' }],+ appShell: { areas: [{ label: 'Work', groups: [{ label: 'Records', subAreas: [{ entity: TABLE, title: 'Tickets' }] }] }] },+};+const LAG_MESSAGE = `The entity with a name = '${TABLE}' with namemapping = 'Logical' was not found in the MetadataCache.LazyDynamicMetadataCache with version 9495075 and timestamp 9495075`;+const lagAnswer = () => ({ statusCode: 400, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ error: { code: '0x80041102', message: LAG_MESSAGE } }) });++// The reads the cases lag, as the SDK and the build send them (the URL decoded), e.g.+// GET /api/data/v9.0/savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_ticket' and name eq 'Tickets by Priority'&$top=2+// GET /api/data/v9.0/savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_ticket' and name eq 'Open Tickets'&$top=2+// GET /api/data/v9.0/systemforms?$select=formid&$filter=objecttypecode eq 'contoso_ticket' and name eq 'Ticket Form' and type eq 2&$top=2+const chartRead = (r, url) => r.method === 'GET' && /\/savedqueryvisualizations\?/.test(url) && /name eq 'Tickets by Priority'/.test(url);+const viewRead = (r, url) => r.method === 'GET' && /\/savedqueries\?/.test(url) && /name eq 'Open Tickets'/.test(url);+const formRead = (name) => (r, url) => r.method === 'GET' && /\/systemforms\?/.test(url) && url.includes(`objecttypecode eq '${TABLE}' and name eq '${name}'`);++// One environment and the harness over it. `lag(r, url)` says which requests answer the lag instead of the fake (each is counted once+// per request, so a budget of answers is the caller's).+function world(label, lag = () => false) {+ const org = createLifecycleOrg();+ const original = org.request;+ const injected = [];+ org.request = async (r) => {+ const url = decodeURIComponent(r.url);+ if (lag(r, url, org)) {+ injected.push(`${r.method} ${url.replace(org.origin, '')}`);+ return lagAnswer();+ }+ return original(r);+ };+ return { org, injected, h: createLifecycleHarness(org, makeTempDir(`read-lag-${label}-`)) };+}+const once = (n, test) => { let left = n; return (r, url, org) => left > 0 && test(r, url, org) && left-- > 0; };+const build = (w, s = spec) => w.h.measure(() => w.h.build(s, { publish: false, sampleData: false, verify: false }));+const retriesOf = (step) => ((step.value && step.value.log) || []).filter((l) => /retry/i.test(l));+const formsNamed = (org, name) => org.find('systemforms', (r) => r.objecttypecode === TABLE && r.name === name).map((r) => r.formid);++// Every write a step sent, each as `METHOD path sha256(body)`, sorted, with every GUID (a new row's id differs from run to run) and the+// unique suffix a build gives a web resource read as placeholders: what the build asked for, and in what words.+const GUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;+function writesOf(org, step) {+ return org.requests.slice(step.mark, step.end).filter((r) => r.method !== 'GET').map((r) => {+ const body = r.body === undefined ? '' : JSON.stringify(r.body).replace(GUID, '<id>');+ return `${r.method} ${String(r.path).replace(GUID, '<id>')} ${crypto.createHash('sha256').update(body).digest('hex').slice(0, 16)}`;+ }).sort();+}++test('reads that meet the lag of a table the build just created are read again in place: every write and publish equals the run with no lag', async () => {+ const control = world('control');+ const clean = await build(control);+ assert.equal(clean.error, undefined, clean.error && clean.error.message);+ assert.equal(clean.value.result.ok, true);+ assert.deepEqual(retriesOf(clean), [], 'no lag, no retry');++ // Three lag answers, the whole allowance of the invocation: two on the chart's lookup and one on the view's.+ const lagged = world('lagged', ((chart, view) => (r, url, org) => chart(r, url, org) || view(r, url, org))(once(2, chartRead), once(1, viewRead)));+ const step = await build(lagged);+ assert.equal(step.error, undefined, step.error && step.error.message);+ assert.deepEqual(step.unexpected, []);+ assert.equal(step.value.result.ok, true);+ assert.equal(lagged.injected.length, 3, lagged.injected.join('\n'));+ assert.equal(retriesOf(step).length, 3, 'one wait for each lag answer');+ assert.deepEqual(writesOf(lagged.org, step), writesOf(control.org, clean), 'the same writes, with the same bodies, as the run with no lag');+ assert.deepEqual(step.writes, clean.writes);+ assert.equal(step.writes['POST PublishXml'], clean.writes['POST PublishXml']);+ assert.equal(step.writes['PATCH savedqueries'], clean.writes['PATCH savedqueries']);+ // The lag answers are given before the fake sees the request, so the reads it served are the run with no lag's, one for one.+ assert.equal(step.reads, clean.reads, 'the reads that met the lag were each made again once, and nothing else was read');+});++test('a form lookup that meets the lag on a table this build created is read again: a spec that names the stock "Information" form reconciles that one form', async () => {+ const stockSpec = { ...spec, forms: [{ ...spec.forms[0], name: 'Information' }] };+ const control = world('stock-control');+ const clean = await build(control, stockSpec);+ assert.equal(clean.error, undefined, clean.error && clean.error.message);+ assert.equal(formsNamed(control.org, 'Information').length, 1);+ assert.equal(clean.writes['POST systemforms'], undefined, 'the stock form is reconciled, never created');++ // The table is created by the build; the one lag answer comes on the lookup of its stock form by name.+ const lagged = world('stock-lag', once(1, (r, url, org) => org.metadata.tables.has(TABLE) && formRead('Information')(r, url)));+ const step = await build(lagged, stockSpec);+ assert.equal(step.error, undefined, step.error && step.error.message);+ assert.equal(step.value.result.ok, true);+ assert.equal(lagged.injected.length, 1);+ assert.equal(retriesOf(step).length, 1);+ assert.equal(formsNamed(lagged.org, 'Information').length, 1, 'one "Information" form: the lag was not read as "no such form"');+ assert.equal(step.writes['POST systemforms'], undefined, 'no form is created');+ assert.deepEqual(writesOf(lagged.org, step), writesOf(control.org, clean));+});++test('a form lookup that meets the lag on a table that was there before the build stops it with the service\'s answer and creates nothing', async () => {+ let on = false;+ const w = world('existing', (r, url) => on && formRead('Ticket Form')(r, url));+ const first = await build(w);+ assert.equal(first.error, undefined, first.error && first.error.message);+ assert.equal(formsNamed(w.org, 'Ticket Form').length, 1);+ on = true;+ const again = await build(w);+ assert.ok(again.error, 'the rebuild stops');+ assert.match(again.error.message, /0x80041102|not found in the MetadataCache/);+ assert.match(again.error.message, new RegExp(`name = '${TABLE}'`));+ assert.deepEqual(retriesOf(again), [], 'a table this invocation did not create is not waited for');+ assert.equal(again.writes['POST systemforms'], undefined, 'no second form is created');+ assert.equal(formsNamed(w.org, 'Ticket Form').length, 1, 'the environment still holds one "Ticket Form"');+ assert.equal(w.injected.length, 1, 'read once');+});++test('a form lookup on a table this build created that stays lagged past the build\'s retries stops it with the service\'s answer and creates nothing', async () => {+ const w = world('exhausted', (r, url, org) => org.metadata.tables.has(TABLE) && formRead('Ticket Form')(r, url));+ const step = await build(w);+ assert.ok(step.error, 'the build stops');+ assert.match(step.error.message, /not found in the MetadataCache/);+ assert.equal(w.injected.length, 4, 'the first read and its three re-reads: the three retries of the invocation, then the stop');+ assert.equal(step.writes['POST systemforms'], undefined, 'no form is created');+ assert.equal(formsNamed(w.org, 'Ticket Form').length, 0);+});++// The form preflight of the destructive-change gate (build-model-app.js discoverOpDiffState) reads the form by name BEFORE the data-model step+// creates the table, so on a new table the lookup answers the MetadataCache 400 and the gate asks whether the table is there. That question+// must be asked the way the data-model step asks it (entity-provision.js findExistingTable): for a table whose labels are localized, an+// inconclusive narrow read is read again, never answered by the broad `EntityDefinitions?$select=…DisplayName…` list — a read that, issued+// before a localized create, makes Dataverse keep only the base-language label. A plain table may still fall back to the list, as before.+const LOCALIZED = {+ ...spec,+ entities: [{ ...spec.entities[0], displayName: { 1033: 'Ticket', 3082: 'Entrada' }, pluralName: { 1033: 'Tickets', 3082: 'Entradas' }, columns: [] }],+ views: [], charts: [],+ forms: [{ entity: TABLE, name: 'Ticket Form', layout: 'explicit', tabs: [{ label: 'General', sections: [{ label: 'General', fields: ['contoso_name'] }] }] }],+};+const PLAIN = { ...LOCALIZED, entities: [{ ...LOCALIZED.entities[0], displayName: 'Ticket', pluralName: 'Tickets' }] };+// `narrow(n)` answers the first n narrow table reads after the preflight's form lookup with `status` (the production client tries a 5xx six+// times before it gives the answer back, so six 503s are one inconclusive read), e.g.+// GET /api/data/v9.0/EntityDefinitions(LogicalName='contoso_ticket')?$select=LogicalName,EntitySetName+// and records the order of the broad table list read and the table's create, e.g.+// GET /api/data/v9.0/EntityDefinitions?$select=LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity+async function preflightRun(label, s, status, narrowFaults) {+ const org = createLifecycleOrg();+ org.pageServer.languages.provisioned = [1033, 3082];+ const original = org.request;+ const sequence = [];+ let formMissed = false;+ let left = narrowFaults;+ org.request = async (r) => {+ const url = decodeURIComponent(r.url);+ if (!org.metadata.tables.has(TABLE) && formRead('Ticket Form')(r, url)) { formMissed = true; return lagAnswer(); }+ if (r.method === 'GET' && url.includes(`/EntityDefinitions(LogicalName='${TABLE}')`) && formMissed && left > 0) {+ left -= 1;+ sequence.push(`narrow ${status}`);+ return status === 400 ? lagAnswer() : { statusCode: status, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ error: { code: '0x80040216', message: 'Service unavailable' } }) };+ }+ if (r.method === 'GET' && /\/EntityDefinitions\?/.test(url)) sequence.push('broad');+ if (r.method === 'POST' && /\/EntityDefinitions$/.test(url)) sequence.push(`create ${Object.keys(labelsOf(r.body)).join('+')}`);+ return original(r);+ };+ const h = createLifecycleHarness(org, makeTempDir(`read-lag-preflight-${label}-`));+ const step = await h.measure(() => h.build(s, { publish: false, sampleData: false, verify: false }));+ const createAt = sequence.findIndex((e) => e.startsWith('create'));+ const broadAt = sequence.indexOf('broad');+ return { org, step, sequence, formMissed, createAt, broadAt, broadBeforeCreate: broadAt >= 0 && (createAt < 0 || broadAt < createAt) };+}+// The LCIDs of a create's DisplayName: `{ LocalizedLabels: [{ Label, LanguageCode }, …] }`.+function labelsOf(body) {+ const b = typeof body === 'string' ? JSON.parse(body) : body;+ return Object.fromEntries(((b.DisplayName && b.DisplayName.LocalizedLabels) || []).map((l) => [l.LanguageCode, l.Label]));+}++for (const [status, faults, what] of [[400, 1, 'answers the MetadataCache 400 once'], [503, 6, 'answers 503 past the client\'s own retries once']]) {+ test(`#796 the form preflight on a new LOCALIZED table whose narrow table read ${what} reads it again, and never sends the broad label-bearing table list before the create`, async () => {+ const run = await preflightRun(`loc-${status}`, LOCALIZED, status, faults);+ assert.equal(run.step.error, undefined, run.step.error && run.step.error.message);+ assert.ok(run.formMissed, 'the preflight looked the form up before the table existed');+ assert.equal(run.broadBeforeCreate, false, `no broad read before the localized create: ${run.sequence.join(' → ')}`);+ assert.equal(run.step.value.result.ok, true, JSON.stringify(run.step.value.result.errors));+ assert.deepEqual(run.step.unexpected, []);+ assert.equal(run.sequence[run.createAt], 'create 1033+3082', `the table is created with both labels: ${run.sequence.join(' → ')}`);+ });+}++test('#796 the form preflight on a new LOCALIZED table whose narrow table reads stay inconclusive stops before any write, with no broad read and no create', async () => {+ const run = await preflightRun('loc-stuck', LOCALIZED, 503, 1000);+ assert.equal(run.step.error, undefined, run.step.error && run.step.error.message);+ assert.equal(run.step.value.result.ok, false);+ assert.match(run.step.value.result.errors.join('\n'), /preflight safety check could not run/);+ assert.match(run.step.value.result.errors.join('\n'), /could not determine whether table 'contoso_ticket' already exists/);+ assert.equal(run.broadAt, -1, run.sequence.join(' → '));+ assert.equal(run.createAt, -1, 'no table is created');+ assert.deepEqual(Object.keys(run.step.writes), [], 'nothing is written');+});++test('#796 controls: a conclusive 404 proves a new localized table absent as before; a PLAIN table may still settle an inconclusive read by the table list', async () => {+ const conclusive = await preflightRun('loc-404', LOCALIZED, 400, 0);+ assert.equal(conclusive.step.error, undefined, conclusive.step.error && conclusive.step.error.message);+ assert.equal(conclusive.step.value.result.ok, true, JSON.stringify(conclusive.step.value.result.errors));+ assert.ok(conclusive.formMissed);+ assert.equal(conclusive.broadAt, -1, conclusive.sequence.join(' → '));+ const plain = await preflightRun('plain-400', PLAIN, 400, 1);+ assert.equal(plain.step.error, undefined, plain.step.error && plain.step.error.message);+ assert.equal(plain.step.value.result.ok, true, JSON.stringify(plain.step.value.result.errors));+ assert.deepEqual(plain.sequence.slice(0, 2), ['narrow 400', 'broad'], 'one narrow read, then the table list, unchanged');+ assert.ok(plain.createAt > plain.broadAt);+});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/halt-retry-policy.test.js b/plugins/model-apps/scripts/tests/halt-retry-policy.test.jsindex 332fc4b47..439c5f99d 100644--- a/plugins/model-apps/scripts/tests/halt-retry-policy.test.js+++ b/plugins/model-apps/scripts/tests/halt-retry-policy.test.js@@ -126,7 +126,7 @@ const POLICY = {};// The sites whose code is an expression, on purpose: the code is decided at run time, so the policy cannot be read off a literal.const DYNAMIC = [- { file: 'lib/sdk-build.js', expr: 'stopCode', kind: 'never', what: 'a declared artifact that did not settle (managedStop): the code of its own first finding; never retried' },+ { file: 'lib/sdk-build.js', expr: 'stopCode', kind: 'by-failure', what: 'a declared artifact that did not settle (managedStop): the code of its own first finding; never retried, save an identity read that met the metadata-cache lag of a table this invocation created (isFreshTableReadLag, #796), which the build\'s bounded retry rides out' },{ file: 'lib/entity-provision.js', expr: "(err && err.code) || 'sdk-error'", kind: 'by-failure', what: 'the runner wraps every failed step with the code of what failed' },{ file: 'lib/entity-provision.js', expr: 'sdkCode', kind: 'by-failure', what: 'a push the SDK refused by value, with the code the SDK gave' },{ file: 'lib/sdk-build.js', expr: 'verdict.code', kind: 'never', what: 'the navigation verdict (app-navigation-empty): a re-run reads the same spec' },diff --git a/plugins/model-apps/scripts/tests/helpers/dashboard-create-crash-child.js b/plugins/model-apps/scripts/tests/helpers/dashboard-create-crash-child.jsnew file mode 100644index 000000000..6cff53bf8--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/dashboard-create-crash-child.js@@ -0,0 +1,82 @@+'use strict';+// One OS process of the declared-dashboard crash-boundary tests (dashboard-settlement-real-bundle.test.js). The process+// is the boundary under test: the binding store and the maker's SDK workspace are files on disk, and only what reached+// them may decide the next build, never anything a process still holds in memory.+// node dashboard-create-crash-child.js <input.json>+// input: { action: 'crash' | 'recover', timing: 'before' | 'after', dir, workspaceDir, wireFile, crashFile, output }+// `crash`: a build creates a new declared dashboard, and its create POST succeeds; the process then exits at once (77),+// with no unwinding, immediately BEFORE the store writes the durable acknowledgement of that create (`timing: before`)+// or immediately AFTER it (`timing: after`). The service's rows are written to `wireFile` first, as the service would+// keep them, and what the process saw to `crashFile`.+// `recover`: a later build in a new process opens the same store `dir` and SDK workspace `workspaceDir` over a service+// rebuilt from `wireFile` and settles the same declaration with no adoption approval, then publishes; the outcome is+// written as JSON to `output`.+const fs = require('node:fs');+const { createManagedWire } = require('./managed-wire.js');+const { declared, catalogFor, settle, makerRun, treeBytes, scopedSettle } = require('./dashboard-maker-run.js');++const CRASH_EXIT = 77;+const createPosts = (wire) => wire.log.filter((e) => e.method === 'POST' && /^systemforms$/i.test(e.path)).length;+const dashboard = declared([{ key: 'open', type: 'list', view: 'Open cases' }]);++async function crash({ timing, dir, workspaceDir, wireFile, crashFile }) {+ const wire = createManagedWire();+ const w = await makerRun({ wire, dir, workspaceDir });+ const answer = w.store.noteDashboardCreateAnswer.bind(w.store);+ // The send observer calls this once the create POST has succeeded on the service; it is the one store write that+ // turns the create receipt into an acknowledged one.+ w.store.noteDashboardCreateAnswer = (...args) => {+ if (timing === 'after') answer(...args);+ fs.writeFileSync(wireFile, JSON.stringify({ saved: [...wire.saved.values()], published: [...wire.published.values()] }));+ const pending = w.store.readGroup('dashboard', 'ops').pending;+ fs.writeFileSync(crashFile, JSON.stringify({+ pid: process.pid,+ posts: createPosts(wire),+ acknowledged: !!(pending && pending.dashboardCreate && pending.dashboardCreate.acknowledged),+ source: treeBytes(workspaceDir),+ }));+ process.exit(CRASH_EXIT);+ };+ await settle(w, dashboard, { approvals: {} });+ throw new Error('the create was acknowledged without reaching the store');+}++async function recover({ dir, workspaceDir, wireFile, output }) {+ const state = JSON.parse(fs.readFileSync(wireFile, 'utf8'));+ const wire = createManagedWire();+ for (const row of state.saved) wire.putForm(row);+ for (const row of state.published) wire.published.set(row.formid, row);+ const w = await makerRun({ wire, dir, workspaceDir });+ const sourceAtStart = treeBytes(workspaceDir);+ let out = null;+ let error = null;+ try {+ out = await scopedSettle(w, dashboard, { approvals: {} }, { publishToo: true });+ } catch (e) {+ error = e;+ }+ const id = catalogFor(dashboard).identityFor('dashboard', 'ops').derivedId;+ const group = w.store.readGroup('dashboard', 'ops');+ fs.writeFileSync(output, JSON.stringify({+ pid: process.pid,+ id,+ error: error && { code: error.code, category: (error.cause && error.cause.category) || error.category, message: error.message },+ result: out && out.settled.result,+ settledId: out && out.settled.id,+ publishSent: !!(out && out.published && out.published.sent),+ isolated: out ? out.isolated : null,+ posts: createPosts(wire),+ writes: wire.writes().map((e) => `${e.method} ${e.path}`),+ published: wire.published.has(id),+ pending: !!group.pending,+ origins: group.committed ? group.committed.records.map((r) => r.origin) : null,+ sourceAtStart,+ sourceAtEnd: treeBytes(workspaceDir),+ }));+}++const input = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));+(input.action === 'crash' ? crash(input) : recover(input)).catch((e) => {+ process.stderr.write(`${e && e.stack ? e.stack : e}\n`);+ process.exit(1);+});diff --git a/plugins/model-apps/scripts/tests/helpers/dashboard-maker-run.js b/plugins/model-apps/scripts/tests/helpers/dashboard-maker-run.jsnew file mode 100644index 000000000..3c9a66ae6--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/dashboard-maker-run.js@@ -0,0 +1,89 @@+'use strict';+// The run a declared-dashboard test settles through: the real maker SDK bundle over a maker's SDK workspace kept between+// runs, the plugin's real HTTP client, the run's real publication barrier and the binding store, over the in-memory+// Dataverse of helpers/managed-wire.js. Shared by dashboard-settlement-real-bundle.test.js and by the second OS process of+// its crash-boundary tests (helpers/dashboard-create-crash-child.js), so both settle a dashboard exactly the same way.+const fs = require('node:fs');+const path = require('node:path');+const { makeTempDir } = require('./temp-dirs.js');+const { ORIGIN, createManagedWire } = require('./managed-wire.js');+const { createAzHttpClient } = require('../../lib/sdk-http-client.js');+const { withDashboardWorkspaceScope } = require('../../lib/dashboard-recovery-workspace.js');+const { createMakerSdk, createNodeWorkspaceStorage } = require('../../vendor/cds-maker-sdk.cjs');+const { openManagedContext } = require('../../lib/managed-bindings.js');+const { createPublicationBarrier } = require('../../lib/publication-barrier.js');+const { createIntentCatalog } = require('../../lib/creates-catalog.js');+const { environmentFingerprint } = require('../../lib/page-ownership-records.js');+const { dashboardTileOpts, dashboardComponent } = require('../../lib/sdk-build.js');+const { settleDeclaredDashboard, publishDeclaredDashboard, dashboardKey } = require('../../lib/dashboard-reconcile.js');+const { createAttemptSendObserver } = require('../../lib/managed-feature-contract.js');++const ENV = 'https://contoso.crm.dynamics.com';+const APP = 'contoso_app';+const SOL = 'contoso_solution';+const FP = environmentFingerprint(ENV);+const OPEN = '66666666-0000-4000-8000-000000000001';+const ALL = '66666666-0000-4000-8000-000000000002';+const MINE = '66666666-0000-4000-8000-000000000003';+const spec = { views: [{ entity: 'incident', name: 'Open cases' }, { entity: 'incident', name: 'All cases' }, { entity: 'incident', name: 'My cases' }] };+const built = { created: { views: { 'incident|Open cases': OPEN, 'incident|All cases': ALL, 'incident|My cases': MINE }, charts: {} } };+const resolveTile = (tile) => dashboardTileOpts(spec, tile, built);++const halt = (phase, label, code, { cause } = {}) => Object.assign(new Error(`${label}: ${code}`), { phase, code, cause, retry: 'never' });+const catalogFor = (d) => createIntentCatalog([{ catalogKind: 'dashboard', key: dashboardKey(d), scope: { kind: 'solution', solution: SOL }, declaration: { scopeType: 'Standard', name: d.name } }]);+const declared = (tiles, extra = {}) => ({ name: 'Ops', reconcile: 'declared', tiles, ...extra });++// The maker's typed adoption approval of `dashboard:ops` is given unless a test passes its own `approvals`.+const ADOPT = { adopt: new Set(['dashboard:ops']) };+const settle = (w, dashboard, extra = {}) => settleDeclaredDashboard({+ dashboard, catalog: catalogFor(dashboard), sdk: w.sdk, store: w.store, barrier: w.barrier, halt, resolveTile, toComponent: dashboardComponent,+ ensureMembership: async () => undefined, ctx: { appUniqueName: APP, environmentFingerprint: FP }, approvals: ADOPT,+ provisionedLanguages: async () => w.wire.languages(),+ ...(w.observer ? { sendObserver: w.observer } : {}), ...extra,+});+// A run over the maker's SDK workspace `workspaceDir`, kept between runs as a maker's is, and the binding store in `dir`.+// `cutCreateAnswer`: the create POST reaches the service and its success passes the send observer (the receipt is+// acknowledged), then the answer is lost on its way to the SDK: the client gets a final 409, so the SDK never records the+// create and keeps its copy as an unsent draft. `deps`: the store's file seams (failNextStoreWrite).+async function makerRun({ wire = createManagedWire(), dir = makeTempDir('dash-settle-'), workspaceDir, cutCreateAnswer = false, deps } = {}) {+ const barrier = createPublicationBarrier();+ const observer = createAttemptSendObserver();+ const observed = observer.wrap(wire.request);+ const transport = cutCreateAnswer+ ? async (req) => {+ const res = await observed(req);+ if (String(req.method).toUpperCase() !== 'POST' || !/\/systemforms$/i.test(new URL(req.url).pathname)) return res;+ return { statusCode: 409, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ error: { code: '0x80040216', message: 'the answer was lost' } }) };+ }+ : observed;+ const httpClient = createAzHttpClient(ORIGIN, { getToken: () => 'x'.repeat(40), request: barrier.gateRequest(transport), sleep: async () => {} });+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(workspaceDir), instanceUrl: ORIGIN, httpClient });+ await sdk.initWorkspace();+ const { store } = openManagedContext({ workspaceDir: dir, environment: ENV, appUniqueName: APP, solutionUniqueName: SOL, barrier, ...(deps ? { deps } : {}) });+ return { wire, barrier, sdk, dir, store, observer, workspaceDir };+}++// Every file of a directory tree and its bytes: the maker's workspace copy must come out of a recovery as it went in.+function treeBytes(root) {+ const out = {};+ const walk = (d) => {+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {+ const p = path.join(d, e.name);+ if (e.isDirectory()) walk(p);+ else out[path.relative(root, p)] = fs.readFileSync(p).toString('base64');+ }+ };+ walk(root);+ return out;+}++// The settle (and, when `publishToo`, the publish) of a run inside its dashboard workspace scope, as sdk-build.js runs them.+async function scopedSettle(w, d, extra = {}, { publishToo = false } = {}) {+ return withDashboardWorkspaceScope({ sourceSdk: w.sdk }, async (scope) => {+ const settled = await settle(w, d, { ...extra, workspaceScope: scope });+ const published = publishToo ? await publishDeclaredDashboard({ store: w.store, barrier: w.barrier, sdk: scope.currentSdk, key: 'ops', id: settled.id }) : null;+ return { settled, published, isolated: scope.isolated };+ });+}++module.exports = { ENV, APP, SOL, FP, OPEN, ALL, MINE, spec, built, resolveTile, halt, catalogFor, declared, ADOPT, settle, makerRun, treeBytes, scopedSettle };diff --git a/plugins/model-apps/scripts/tests/helpers/role-wire.js b/plugins/model-apps/scripts/tests/helpers/role-wire.jsnew file mode 100644index 000000000..4e2278eeb--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/role-wire.js@@ -0,0 +1,161 @@+'use strict';+// Security roles over a workflow wire (helpers/workflow-wire.js): `withRoles(wire)` replaces `wire.request` with one that+// serves the role, privilege and metadata requests the REAL vendored SDK (createPersonaRole, addEntityPrivilegesToRole,+// getEntityPrivileges) and the download's persona proof (lib/persona-restore.js) send, and hands every other request to the+// wire as before. Install it BEFORE any SDK is made over the wire: the client captures `wire.request` when it is made.+// Every request it serves is recorded in `wire.log` too, so a test that pins the writes of a run sees the role writes.+//+// What it serves, as the platform does:+// GET EntityDefinitions(LogicalName='<t>')?$select=LogicalName,Privileges one table's privileges (404 for a table it lacks)+// GET EntityDefinitions?$select=LogicalName,Privileges every table's privileges+// GET EntityDefinitions(LogicalName='roleprivileges')?$select=EntitySetName roleprivilegescollection (the set is irregular)+// GET businessunits?$filter=_parentbusinessunitid_value eq null the root business unit+// GET roles?$filter=name eq '<n>' and _businessunitid_value eq <bu> the role rows+// POST roles {name, description, [email protected]} a new unmanaged role (201 + OData-EntityId)+// POST roles(<id>)/Microsoft.Dynamics.CRM.ReplacePrivilegesRole {Privileges} the role's privileges become exactly these+// POST roles(<id>)/Microsoft.Dynamics.CRM.AddPrivilegesRole {Privileges} added; a privilege held deeper keeps its depth+// GET roleprivilegescollection?$filter=roleid eq <id> {privilegeid, privilegedepthmask} rows+// GET privileges?$filter=privilegeid eq <id> or … privilege names, table or not+// GET solutions?$filter=uniquename eq '<n>' / solutioncomponents?… the solution and its role members+// GET appmodules(<id>)/appmoduleroles_association the roles the app is associated with+// A request depth is the Dataverse PrivilegeDepth, by name (Basic, Local, Deep, Global) or number (0-3); a held depth is the+// roleprivileges bitmask (1 Basic, 2 Local, 4 Deep, 8 Global).+// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/replaceprivilegesrole+const crypto = require('node:crypto');++const ROOT_BU = 'b0000000-0000-4000-8000-000000000001';+const CHILD_BU = 'b0000000-0000-4000-8000-000000000002';+const SOLUTION_ID = 'c0000000-0000-4000-8000-000000000001';+const MASK = { basic: 1, local: 2, deep: 4, global: 8, 0: 1, 1: 2, 2: 4, 3: 8 };+const USER_OWNED = { types: ['Create', 'Read', 'Write', 'Delete', 'Append', 'AppendTo', 'Assign', 'Share'], scopes: ['Basic', 'Local', 'Deep', 'Global'] };+// An organization-owned table (a process flow's backing table, appmodule): Global only, nothing to assign or share.+const ORG_OWNED = { types: ['Create', 'Read', 'Write', 'Delete', 'Append', 'AppendTo'], scopes: ['Global'] };+const GUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;++// A stable id per name, so a test can name a privilege without reading it back.+function idOf(name) {+ const h = crypto.createHash('sha256').update(String(name)).digest('hex');+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-8${h.slice(17, 20)}-${h.slice(20, 32)}`;+}++function withRoles(wire, { solution = 'BP', appId } = {}) {+ const tables = new Map();+ const privileges = new Map(); // id -> { id, name, table|null }+ const roles = new Map(); // id -> { roleid, name, description, ismanaged, _businessunitid_value, held: Map<privilegeId, mask> }+ const members = new Set();+ const appRoles = new Set();+ const json = (statusCode, body, headers = {}) => ({ statusCode, headers, body: body === undefined ? '' : JSON.stringify(body) });+ const lcName = (s) => String(s || '').toLowerCase();++ function table(logical, { types, scopes } = USER_OWNED) {+ const name = lcName(logical);+ const label = name.charAt(0).toUpperCase() + name.slice(1);+ const rows = types.map((type) => {+ const id = idOf(`prv${type}${label}`);+ privileges.set(id, { id, name: `prv${type}${label}`, table: name });+ return { PrivilegeId: id, Name: `prv${type}${label}`, PrivilegeType: type, CanBeBasic: scopes.includes('Basic'), CanBeLocal: scopes.includes('Local'), CanBeDeep: scopes.includes('Deep'), CanBeGlobal: scopes.includes('Global'), CanBeEntityReference: false, CanBeParentEntityReference: false };+ });+ tables.set(name, rows);+ return Object.fromEntries(rows.map((r) => [r.PrivilegeType.toLowerCase(), r.PrivilegeId]));+ }+ // A privilege no table carries (prvExportToExcel is one): a persona cannot declare it.+ function plainPrivilege(name) {+ const id = idOf(name);+ privileges.set(id, { id, name, table: null });+ return id;+ }+ function addRole({ name, bu = ROOT_BU, marked = true, managed = false, held = {} }) {+ const roleid = idOf(`role:${name}:${roles.size}`);+ const description = marked ? 'Authored by @maker-studio/cds-maker-sdk (persona/security role).' : 'Made by hand';+ roles.set(roleid, { roleid, name, description, ismanaged: managed, _businessunitid_value: bu, held: new Map(Object.entries(held)) });+ return roleid;+ }+ const heldOf = (roleId) => Object.fromEntries([...roles.get(lcName(roleId)).held].sort(([a], [b]) => (a < b ? -1 : 1)));++ // `$filter` terms the role reads send: `<field> eq <value>` joined by `and`, a value quoted ('' escapes a quote), bare (a+ // GUID, a number) or `null`, e.g. name eq 'Dispatcher' and _businessunitid_value eq b0000000-…+ function terms(filter) {+ const out = [];+ for (const part of String(filter || '').split(/\s+and\s+/i)) {+ const m = /^\s*\(?\s*(\w+)\s+eq\s+(?:'((?:[^']|'')*)'|(\S+?))\s*\)?\s*$/i.exec(part);+ if (m) out.push([m[1].toLowerCase(), m[2] !== undefined ? m[2].replace(/''/g, "'").toLowerCase() : m[3].toLowerCase()]);+ }+ return out;+ }+ const matches = (row, filter) => terms(filter).every(([field, value]) => (value === 'null' ? row[field] == null : lcName(row[field]) === value));+ const roleRow = (r) => ({ roleid: r.roleid, name: r.name, description: r.description, ismanaged: r.ismanaged, _businessunitid_value: r._businessunitid_value });+ const tablesRow = (name) => ({ LogicalName: name, Privileges: tables.get(name) });++ function apply(method, p, q, body) {+ let m = /^EntityDefinitions\(LogicalName='([^']+)'\)$/i.exec(p);+ if (m && method === 'GET') {+ const name = lcName(m[1]);+ if (/Privileges/.test(q.get('$select') || '')) return tables.has(name) ? json(200, tablesRow(name)) : json(404, { error: { code: '0x80060888', message: `Could not find entity ${name}` } });+ if (name === 'roleprivileges') return json(200, { LogicalName: name, EntitySetName: 'roleprivilegescollection' });+ return null;+ }+ if (/^EntityDefinitions$/i.test(p) && method === 'GET' && /Privileges/.test(q.get('$select') || '')) return json(200, { value: [...tables.keys()].sort().map(tablesRow) });+ if (/^businessunits$/i.test(p) && method === 'GET') {+ const units = [{ businessunitid: ROOT_BU, _parentbusinessunitid_value: null }, { businessunitid: CHILD_BU, _parentbusinessunitid_value: ROOT_BU }];+ return json(200, { value: units.filter((u) => matches(u, q.get('$filter'))) });+ }+ if (/^roles$/i.test(p) && method === 'GET') return json(200, { value: [...roles.values()].filter((r) => matches(r, q.get('$filter'))).map(roleRow) });+ if (/^roles$/i.test(p) && method === 'POST') {+ const bu = (GUID.exec(String(body['[email protected]'] || '')) || [ROOT_BU])[0].toLowerCase();+ const roleid = addRole({ name: body.name, bu, marked: false });+ roles.get(roleid).description = body.description;+ return json(201, { roleid }, { 'odata-entityid': `${wire.origin || 'https://contoso.crm.dynamics.com'}/api/data/v9.2/roles(${roleid})` });+ }+ m = /^roles\(([^)]+)\)\/Microsoft\.Dynamics\.CRM\.(Replace|Add)PrivilegesRole$/i.exec(p);+ if (m && method === 'POST') {+ const r = roles.get(lcName(m[1]));+ if (!r) return json(404, { error: { code: '0x80040217', message: 'role With Id Does Not Exist' } });+ if (m[2] === 'Replace') r.held = new Map();+ for (const x of body.Privileges || []) {+ const id = lcName(x.PrivilegeId);+ const mask = MASK[lcName(x.Depth)];+ if (!mask) return json(400, { error: { code: '0x80040203', message: `bad depth ${x.Depth}` } });+ if (!r.held.has(id) || r.held.get(id) < mask) r.held.set(id, mask);+ }+ return json(204);+ }+ if (/^roleprivilegescollection$/i.test(p) && method === 'GET') {+ const t = terms(q.get('$filter')).find(([field]) => field === 'roleid');+ const r = t && roles.get(t[1]);+ return json(200, { value: r ? [...r.held].map(([privilegeid, privilegedepthmask]) => ({ privilegeid, privilegedepthmask })) : [] });+ }+ if (/^privileges$/i.test(p) && method === 'GET') {+ const ids = new Set((String(q.get('$filter') || '').match(new RegExp(GUID.source, 'gi')) || []).map(lcName));+ return json(200, { value: [...privileges.values()].filter((x) => ids.has(x.id)).map((x) => ({ privilegeid: x.id, name: x.name })) });+ }+ if (/^solutions$/i.test(p) && method === 'GET') return json(200, { value: matches({ uniquename: solution }, q.get('$filter')) ? [{ solutionid: SOLUTION_ID }] : [] });+ if (/^solutioncomponents$/i.test(p) && method === 'GET') {+ const asked = /componenttype eq 20\b/.test(q.get('$filter') || '');+ return json(200, { value: asked ? [...members].map((objectid) => ({ objectid, componenttype: 20, rootcomponentbehavior: 0 })) : [] });+ }+ m = /^appmodules\(([^)]+)\)\/appmoduleroles_association$/i.exec(p);+ if (m && method === 'GET') {+ if (appId && lcName(m[1]) !== lcName(appId)) return json(404, { error: { code: '0x80040217', message: 'appmodule With Id Does Not Exist' } });+ return json(200, { value: [...appRoles].map((roleid) => ({ roleid })) });+ }+ return null;+ }++ const inner = wire.request;+ wire.request = async (req) => {+ const url = new URL(req.url);+ const p = decodeURIComponent(url.pathname.replace(/^\/api\/data\/v[\d.]+\//, ''));+ const raw = req.body == null ? null : Buffer.isBuffer(req.body) ? req.body.toString('utf8') : String(req.body);+ let body = null;+ try { body = raw ? JSON.parse(raw) : null; } catch { body = raw; }+ const method = String(req.method).toUpperCase();+ const answer = apply(method, p, url.searchParams, body);+ if (!answer) return inner(req);+ wire.log.push({ method, url: req.url, path: p, query: url.search, body, headers: { ...(req.headers || {}) } });+ return answer;+ };++ return { table, plainPrivilege, addRole, heldOf, roles, members, appRoles, idOf, ROOT_BU, CHILD_BU };+}++module.exports = { withRoles, idOf, ROOT_BU, CHILD_BU, ORG_OWNED, USER_OWNED };diff --git a/plugins/model-apps/scripts/tests/lint-app-spec.test.js b/plugins/model-apps/scripts/tests/lint-app-spec.test.jsindex 847070b7f..08d8d406c 100644--- a/plugins/model-apps/scripts/tests/lint-app-spec.test.js+++ b/plugins/model-apps/scripts/tests/lint-app-spec.test.js@@ -209,6 +209,38 @@ test('CLI --strict turns warnings into a failure', () => {assert.match(strict.stdout, /failed by --strict/);});+// #799: `type` on a view entry was shown by older docs and shipped samples and never had an effect, so a spec carrying it must keep passing+// --strict; a genuine typo (`filter` for `filters`) drops the filter silently, so --strict failing on it is the point of the warning.+// The base spec carries other advice (no navigation, personas or pages), so these two start from one that lints clean.+const strictClean = (viewExtra) => {+ const s = good();+ s.views = [{ entity: 'c_order', name: 'Open Orders', columns: ['c_name'], ...viewExtra }];+ s.appShell = { areas: [{ label: 'Sales', groups: [{ label: 'Orders', subAreas: [{ entity: 'c_order', title: 'Orders' }, { title: 'Overview', page: 'ov' }] }] }] };+ s.personas = [{ persona: 'Clerk', jobs: [{ name: 'Enter orders', surfaces: ['Orders'], privileges: [{ entity: 'c_order', access: ['read', 'write', 'create'] }] }] }];+ s.pages = [{ key: 'ov', name: 'Overview', purpose: 'overview', source: { kind: 'intent' } }];+ return s;+};++test('CLI --strict still passes a view that carries the old `type` key, with no warning', () => {+ const control = runCli(strictClean(), ['--strict', '--json']);+ assert.strictEqual(control.code, 0, `the control spec must itself lint clean: ${control.stdout}`);+ const strict = runCli(strictClean({ type: 'main' }), ['--strict', '--json']);+ assert.strictEqual(strict.code, 0, strict.stderr);+ const payload = JSON.parse(strict.stdout);+ assert.deepStrictEqual(payload.warnings, []);+ assert.strictEqual(payload.ok, true);+});++test('CLI --strict fails on a misspelled view key that the build would drop; without --strict the spec still passes', () => {+ const s = strictClean({ filter: [{ attr: 'c_name', op: 'eq', value: 'x' }] });+ assert.strictEqual(runCli(s).code, 0, 'a warning alone passes without --strict');+ const strict = runCli(s, ['--strict', '--json']);+ assert.strictEqual(strict.code, 1);+ const payload = JSON.parse(strict.stdout);+ assert.strictEqual(payload.ok, false);+ assert.ok(payload.warnings.some((w) => /unknown key 'filter'.*did you mean 'filters'\?/.test(w)), JSON.stringify(payload.warnings));+});+test('CLI reports an unreadable spec by name rather than a generic gate error', () => {let out;try {diff --git a/plugins/model-apps/scripts/tests/live-plan.test.js b/plugins/model-apps/scripts/tests/live-plan.test.jsindex 10653206e..29700f259 100644--- a/plugins/model-apps/scripts/tests/live-plan.test.js+++ b/plugins/model-apps/scripts/tests/live-plan.test.js@@ -199,6 +199,18 @@ test('#559 a failed artifact query is unknown, not a silent create', async () =>assert.match(plan[0].stateWhy, /query refused/);});+test('#796 a form on a table that reads present, whose lookup meets the metadata-cache lag, is unknown, not create', async () => {+ // The answer that also means "no such table":+ // HTTP 400 {"error":{"code":"0x80041102","message":"The entity with a name = 'new_t' with namemapping = 'Logical' was not found in the MetadataCache..."}}+ // The table was just read present, so here it is the table's lag, and the form may well be there.+ const plan = [{ phase: 'forms', label: 'form for new_t', key: { kind: 'form', entity: 'new_t', name: 'Information', formType: 'Main' } }];+ const { provision } = reader({ tables: { new_t: { columns: [] } } });+ provision.queryRecords = async () => { throw Object.assign(new Error("The entity with a name = 'new_t' with namemapping = 'Logical' was not found in the MetadataCache"), { statusCode: 400 }); };+ await annotateLivePlan(plan, { spec: {}, provision });+ assert.strictEqual(plan[0].state, 'unknown');+ assert.match(plan[0].stateWhy, /not found in the MetadataCache/);+});+test('#559 an item with no key is left unprobed rather than guessed', async () => {const plan = [{ phase: 'publish', label: 'publish customizations' }];const { provision, reads } = reader({});@@ -372,7 +384,7 @@ test('#559 a spec with no localized labels resolves inconclusive probes through// every view and form on it — and the apply never reaches them: findExistingTable raises BuildHalt// for exactly this state, outside any runner.run, so the build aborts in `data-model`.//-// The form arm is the one that hides best: resolveExistingFormId deliberately swallows the+// The form arm is the one that hides best: resolveExistingFormId by default swallows the// MetadataCache 400 and returns null, and `!!null` is a confident "absent".test('#559 a view/chart/form on a table whose probe was INCONCLUSIVE is unknown, not create', async () => {const spec = { entities: [{ schemaName: 'new_loc', displayName: { 1033: 'Localized', 3082: 'Localizada' }, columns: [] }] };diff --git a/plugins/model-apps/scripts/tests/localized-labels.test.js b/plugins/model-apps/scripts/tests/localized-labels.test.jsindex 3853681b6..8b179c14d 100644--- a/plugins/model-apps/scripts/tests/localized-labels.test.js+++ b/plugins/model-apps/scripts/tests/localized-labels.test.js@@ -728,6 +728,119 @@ test('the guard costs nothing for a spec with only plain labels', async () => {assert.strictEqual(called, 0);});+// The check runs before the build's FIRST write, which is the publisher and the solution, not the first table. Run inside the+// data-model phase only, it stopped a build whose label names a language the organization lacks after the solution phase had+// already created the publisher and the solution. The halt is the one the data-model phase gives: same code, phase and message.+const SOLUTION_WRITE = /^(createPublisher|createSolution)$/;+const ANY_WRITE = /^(create|update|delete|add|push|set|insert|associate|publish|save|remove)/;+function spanishSpec() {+ const s = base();+ s.entities[0].displayName = ES;+ s.entities[0].pluralName = { 1033: 'Project Baselines', 3082: 'Líneas base' };+ return s;+}+// The simple mock SDK with no publisher and no solution yet, so the solution phase creates both; `writes` lists every write call by name.+function languageWorld() {+ const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');+ const { sdk } = makeSimpleMockSdk();+ const query = sdk.queryRecords;+ sdk.queryRecords = async (entity, o) => (entity === 'solution' || entity === 'publisher' ? [] : query(entity, o));+ const writes = [];+ for (const name of Object.keys(sdk)) {+ const fn = sdk[name];+ if (typeof fn !== 'function' || !ANY_WRITE.test(name)) continue;+ sdk[name] = (...args) => { writes.push(name); return fn(...args); };+ }+ return { sdk, writes };+}+async function buildWithLanguages(spec, { provisionedLanguages, apply = true, phases = ['solution', 'data-model'] }) {+ const fs = require('node:fs');+ const os = require('node:os');+ const path = require('node:path');+ const { runSdkBuild } = require('../lib/sdk-build.js');+ const { sdk, writes } = languageWorld();+ const appDir = fs.mkdtempSync(path.join(os.tmpdir(), 'label-languages-'));+ let probes = 0;+ const probe = async () => { probes += 1; return provisionedLanguages(); };+ try {+ const result = await runSdkBuild(spec, {+ sdk, apply, env: 'https://contoso.crm.dynamics.com', appDir, phases, livePlan: false, preResolvedLanguageCode: 1033, provisionedLanguages: probe, warn: () => {},+ }).then((r) => ({ r }), (err) => ({ err }));+ return { ...result, writes, probes };+ } finally {+ fs.rmSync(appDir, { recursive: true, force: true });+ }+}++test('a full build with a label in an unprovisioned language halts before the publisher and the solution are created', async () => {+ const { checkLocalizedLabelLanguages } = require('../lib/entity-provision.js');+ const today = await checkLocalizedLabelLanguages(spanishSpec(), async () => [1033]).then(() => null, (e) => e);+ assert.ok(today, 'the check itself halts this spec');+ for (const phases of [['solution', 'data-model'], undefined]) {+ const { err, writes, probes } = await buildWithLanguages(spanishSpec(), { provisionedLanguages: async () => [1033], ...(phases ? { phases } : {}) });+ assert.ok(err, `the build must halt (phases ${JSON.stringify(phases)})`);+ assert.strictEqual(err.code, 'localized-label-language-not-provisioned', String(err && err.stack));+ assert.strictEqual(err.phase, 'data-model');+ assert.strictEqual(err.message, today.message);+ assert.deepStrictEqual(writes.filter((w) => SOLUTION_WRITE.test(w)), [], 'the publisher or the solution was created before the label languages were checked');+ assert.deepStrictEqual(writes, [], 'nothing may be written before the label languages are checked');+ assert.strictEqual(probes, 1, 'the languages are read once');+ }+});++test('a provisioned language, or a language list that cannot be read, builds as before with one read of the list', async () => {+ for (const provisionedLanguages of [async () => [1033, 3082], async () => { throw new Error('HTTP 403'); }, async () => []]) {+ const { err, writes, probes } = await buildWithLanguages(spanishSpec(), { provisionedLanguages });+ assert.ifError(err);+ assert.deepStrictEqual(writes.filter((w) => SOLUTION_WRITE.test(w)), ['createPublisher', 'createSolution']);+ assert.ok(writes.includes('createTable'), `the table is created: ${writes.join(', ')}`);+ assert.strictEqual(probes, 1, 'the languages are read once, not again in the data-model phase');+ }+});++test('a dry run does not read the language list and writes nothing', async () => {+ const { r, err, writes, probes } = await buildWithLanguages(spanishSpec(), { provisionedLanguages: async () => [1033], apply: false });+ assert.ifError(err);+ assert.strictEqual(r.dryRun, true);+ assert.deepStrictEqual(writes, []);+ assert.strictEqual(probes, 0);+});++test('a run without the data-model phase does not check the label languages', async () => {+ const { err, writes, probes } = await buildWithLanguages(spanishSpec(), { provisionedLanguages: async () => [1033], phases: ['solution'] });+ assert.ifError(err);+ assert.deepStrictEqual(writes.filter((w) => SOLUTION_WRITE.test(w)), ['createPublisher', 'createSolution']);+ assert.strictEqual(probes, 0);+});++test('provisionEntities halts on an unprovisioned label language before the publisher and the solution are created', async () => {+ const path = require('node:path');+ const { provisionEntities } = require(path.join(__dirname, '..', 'provision-entities.js'));+ const input = {+ solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' },+ entities: [{ schemaName: 'contoso_projectbaseline', displayName: ES, pluralName: { 1033: 'Project Baselines', 3082: 'Líneas base' }, primaryAttribute: { schemaName: 'contoso_title' }, columns: [] }],+ relationships: [],+ };+ const run = async (provisionedLanguages) => {+ const { sdk, writes } = languageWorld();+ let probes = 0;+ const out = await provisionEntities(input, { apply: true }, {+ sdk, provision: sdk, warn: () => undefined, provisionedLanguages: async () => { probes += 1; return provisionedLanguages(); },+ }).then((r) => ({ r }), (err) => ({ err }));+ return { ...out, writes, probes };+ };+ const halted = await run(async () => [1033]);+ assert.strictEqual(halted.err && halted.err.code, 'localized-label-language-not-provisioned', String(halted.err && halted.err.stack));+ assert.deepStrictEqual(halted.writes, [], 'nothing may be written before the label languages are checked');+ assert.strictEqual(halted.probes, 1);+ const built = await run(async () => [1033, 3082]);+ assert.ifError(built.err);+ assert.deepStrictEqual(built.writes.filter((w) => SOLUTION_WRITE.test(w)), ['createPublisher', 'createSolution']);+ assert.ok(built.writes.includes('createTable'));+ // Once, before the solution: the data-model phase does not read the list again (no language override here, so nothing else reads it).+ assert.strictEqual(built.probes, 1);+});+test('the localized label reaches the SDK UNFLATTENED', async () => {// The plugin must not pre-flatten: the SDK's serializer is what turns a map into a multi-entry// LocalizedLabels array. Flattening here would silently restore the English-only behaviour whilediff --git a/plugins/model-apps/scripts/tests/managed-bindings.test.js b/plugins/model-apps/scripts/tests/managed-bindings.test.jsindex 9931cf1c8..c68f5ff04 100644--- a/plugins/model-apps/scripts/tests/managed-bindings.test.js+++ b/plugins/model-apps/scripts/tests/managed-bindings.test.js@@ -2151,4 +2151,108 @@ test('incarnation identity: a lineage selected by its identity under another keyassert.equal(codeOf(() => prepareAt(open(dir), first.rootId, { incarnation: { identity: FORM, epoch: 1, rootId: first.rootId } })), CODES.conflict);assert.equal(fileText(s), text, 'nothing written');assert.equal(typeof prepareAt(open(dir), list[0].rootId, { incarnation: { identity: FORM, epoch: 2, rootId: list[0].rootId } }, ALIAS), 'string');-});\ No newline at end of file+});++// --- A new dashboard's durable create receipt (noteDashboardCreateDraft / Dispatch / Answer) and the created root's+// create evidence (`localCreateDraft`), which the next run's recovery of a retained workspace copy relies on.+const RECEIPT = { rootId: DASH, draftSha256: H('7'), bodySha256: H('8') };+function receiptedCreate(store, key = 'ops') {+ const token = store.prepareAttempt({ family: 'dashboard', key, baseGeneration: null, root: { kind: 'dashboard', key, id: DASH }, knownScopes: [DASH_SCOPE], declarationSha256: H('e'), publication: { scope: DASH_SCOPE, state: 'owed' } });+ const { epoch } = store.markSending(token, expected(DASH, [], 'dashboard-v1'), { observed: true });+ return { token, epoch };+}+function acknowledgedCreate(store, key = 'ops') {+ const { token, epoch } = receiptedCreate(store, key);+ store.noteDashboardCreateDraft(token, { sendEpoch: epoch, ...RECEIPT });+ const { dispatchToken } = store.noteDashboardCreateDispatch(token, { sendEpoch: epoch, bodySha256: RECEIPT.bodySha256 });+ store.noteAttemptDispatch(token, epoch);+ store.noteDashboardCreateAnswer(token, { sendEpoch: epoch, dispatchToken, bodySha256: RECEIPT.bodySha256 });+ return { token, epoch };+}+const commitDashboard = (store, token, key, baseGeneration = null, root = rec('dashboard', key, DASH)) => store.commitGroup({ token, baseGeneration, records: [root], proof: PROOF, consumerState: { declaration: {}, tiles: {}, seedIds: [] }, publication: { scope: DASH_SCOPE, state: 'owed', desiredSha256: H('5'), dispatchToken: null } });+const rootOf = (store, key = 'ops') => store.readGroup('dashboard', key).committed.records.find((r) => r.kind === 'dashboard');++test('dashboard create receipt: recorded once, immutable, its dispatch and answer correlated, every refusal writing nothing', () => {+ const store = open(makeTempDir('mb-dash-receipt-'));+ const { token, epoch } = receiptedCreate(store);+ store.noteDashboardCreateDraft(token, { sendEpoch: epoch, ...RECEIPT });+ store.noteDashboardCreateDraft(token, { sendEpoch: epoch, ...RECEIPT });+ const before = fileText(store);+ assert.equal(codeOf(() => store.noteDashboardCreateDraft(token, { sendEpoch: epoch, ...RECEIPT, bodySha256: H('9') })), CODES.completion, 'another body is not sent under it');+ assert.equal(codeOf(() => store.noteDashboardCreateDraft(token, { sendEpoch: epoch + 1, ...RECEIPT })), CODES.pending, 'another epoch');+ assert.equal(codeOf(() => store.noteDashboardCreateDraft(token, { sendEpoch: epoch, ...RECEIPT, rootId: FORM })), CODES.notSettled, 'another root');+ assert.equal(codeOf(() => store.noteDashboardCreateDispatch(token, { sendEpoch: epoch, bodySha256: H('9') })), CODES.completion, 'another body is not dispatched');+ assert.equal(fileText(store), before, 'the refusals wrote nothing');+ const { dispatchToken } = store.noteDashboardCreateDispatch(token, { sendEpoch: epoch, bodySha256: RECEIPT.bodySha256 });+ assert.equal(store.noteDashboardCreateDispatch(token, { sendEpoch: epoch, bodySha256: RECEIPT.bodySha256 }).dispatchToken, dispatchToken, 'a re-send keeps its dispatch');+ assert.equal(codeOf(() => store.noteDashboardCreateAnswer(token, { sendEpoch: epoch, dispatchToken: 'another', bodySha256: RECEIPT.bodySha256 })), CODES.notSettled, 'an answer to another dispatch');+ assert.equal(store.readGroup('dashboard', 'ops').pending.dashboardCreate.acknowledged, false);+ assert.equal(codeOf(() => store.noteSaved(token, { proof: null, acknowledgedRoot: true })), CODES.notSettled, 'an SDK result never acknowledges a receipted create');+ store.noteDashboardCreateAnswer(token, { sendEpoch: epoch, dispatchToken, bodySha256: RECEIPT.bodySha256 });+ assert.equal(store.readGroup('dashboard', 'ops').pending.dashboardCreate.acknowledged, true);+ store.noteSaved(token, { proof: null, acknowledgedRoot: true });++ // An edit of an existing root keeps no create receipt.+ const edit = open(makeTempDir('mb-dash-receipt-edit-'));+ const g = settleDashboard(edit, 'ops');+ const t2 = edit.prepareAttempt({ family: 'dashboard', key: 'ops', baseGeneration: g.generation, root: g.root, knownScopes: [DASH_SCOPE], declarationSha256: H('e') });+ const { epoch: e2 } = edit.markSending(t2, expected(DASH, [], 'dashboard-v1'), { observed: true });+ assert.equal(codeOf(() => edit.noteDashboardCreateDraft(t2, { sendEpoch: e2, ...RECEIPT })), CODES.notSettled);+});++test('dashboard create receipt: a proven-unsent continuation moves it to the new epoch with its hashes kept; an acknowledged one never continues', () => {+ const store = open(makeTempDir('mb-dash-receipt-epoch-'));+ const { token, epoch } = receiptedCreate(store);+ store.noteDashboardCreateDraft(token, { sendEpoch: epoch, ...RECEIPT });+ store.noteDashboardCreateDispatch(token, { sendEpoch: epoch, bodySha256: RECEIPT.bodySha256 });+ store.noteAttemptDispatch(token, epoch);+ store.noteAttemptNotStarted(token, epoch);+ const next = store.markSending(token, expected(DASH, [], 'dashboard-v1'), { claim: 'continue', observed: true });+ assert.equal(next.epoch, epoch + 1);+ const d = store.readGroup('dashboard', 'ops').pending.dashboardCreate;+ assert.deepEqual(d, { formatVersion: 1, rootId: DASH, sendEpoch: epoch + 1, draftSha256: RECEIPT.draftSha256, bodySha256: RECEIPT.bodySha256, dispatchToken: null, acknowledged: false });++ const acked = open(makeTempDir('mb-dash-receipt-acked-'));+ const { token: t2 } = acknowledgedCreate(acked);+ const before = fileText(acked);+ assert.equal(codeOf(() => acked.markSending(t2, expected(DASH, [], 'dashboard-v1'), { claim: 'continue', observed: true })), CODES.pending);+ assert.equal(fileText(acked), before);+});++test('created dashboard root: the store mints its create evidence from the acknowledged receipt, keeps it for later generations of that root, refuses one a caller makes up, and drops it with a retirement', () => {+ const store = open(makeTempDir('mb-dash-marker-'));+ const { token } = acknowledgedCreate(store);+ store.noteSaved(token, { proof: null, acknowledgedRoot: true });+ const g1 = commitDashboard(store, token, 'ops');+ const marker = { formatVersion: 1, rootId: DASH, attemptToken: token, draftSha256: RECEIPT.draftSha256, bodySha256: RECEIPT.bodySha256 };+ assert.deepEqual(rootOf(store).localCreateDraft, marker);++ const edit = () => {+ const { committed } = store.readGroup('dashboard', 'ops');+ const t = store.prepareAttempt({ family: 'dashboard', key: 'ops', baseGeneration: committed.generation, root: committed.root, knownScopes: [DASH_SCOPE], declarationSha256: H('e') });+ store.markSending(t, expected(DASH, [], 'dashboard-v1'));+ store.noteSaved(t, { proof: null, acknowledgedRoot: false });+ return { t, base: committed.generation };+ };+ let { t, base } = edit();+ const before = fileText(store);+ assert.equal(codeOf(() => commitDashboard(store, t, 'ops', base, rec('dashboard', 'ops', DASH, { localCreateDraft: { ...marker, draftSha256: H('9') } }))), CODES.groupInvalid, 'made-up evidence');+ assert.equal(fileText(store), before, 'nothing written');+ const g2 = commitDashboard(store, t, 'ops', base, rec('dashboard', 'ops', DASH, { localCreateDraft: marker }));+ assert.notEqual(g2.generation, g1.generation);+ assert.deepEqual(rootOf(store).localCreateDraft, marker, 'the record read back and handed in again keeps it');+ ({ t, base } = edit());+ commitDashboard(store, t, 'ops', base);+ assert.deepEqual(rootOf(store).localCreateDraft, marker, 'a later generation of the same root keeps it');++ // A created root with no receipt (no observed send) has none.+ const plain = open(makeTempDir('mb-dash-marker-plain-'));+ settleDashboard(plain, 'ops');+ assert.equal(rootOf(plain).localCreateDraft, undefined);++ // Retired with its root: nothing in the store keeps it, so no later incarnation of the key can inherit it.+ const g = store.readGroup('dashboard', 'ops').committed;+ retireNow(store, { family: 'dashboard', key: 'ops', generation: g.generation, rootId: DASH, evidence: absent(DASH) });+ assert.equal(store.readGroup('dashboard', 'ops').committed, null);+ assert.equal(fileText(store).includes('localCreateDraft'), false);+});diff --git a/plugins/model-apps/scripts/tests/managed-publication.test.js b/plugins/model-apps/scripts/tests/managed-publication.test.jsindex c45033d79..fa8af00ad 100644--- a/plugins/model-apps/scripts/tests/managed-publication.test.js+++ b/plugins/model-apps/scripts/tests/managed-publication.test.js@@ -310,16 +310,16 @@ test('a drifted saved layer someone else already published is not called unpubliconst formRow = (id, formxml, table = 'account') => ({ formid: id, name: 'Main', objecttypecode: table, type: 2, formxml });// A form an earlier run committed on `account`: `publishedXml` is live, `savedXml` is saved, and the group's publication// is `state` — 'owed' (desired = the saved layer it committed) or 'not-needed' (saved equalled published at the commit).-function committedForm(s, { id, key, publishedXml, savedXml, state = 'owed' }) {+function committedForm(s, { id, key, publishedXml, savedXml, state = 'owed', origin = 'created' }) {s.wire.putForm(formRow(id, publishedXml), { publishedToo: true });s.wire.saved.get(id).formxml = savedXml;const t = s.store.prepareAttempt({ family: 'form', key, baseGeneration: null, root: { kind: 'form', key, id }, knownScopes: [ACCOUNT], declarationSha256: H('e'), publication: { scope: ACCOUNT, state: 'owed' } });s.store.markSending(t, expected(id));- s.store.noteSaved(t, { proof: null, acknowledgedRoot: true });+ s.store.noteSaved(t, { proof: null, acknowledgedRoot: origin === 'created' });const publication = state === 'owed'? { scope: ACCOUNT, state: 'owed', desiredSha256: layerHash(s.wire.saved.get(id)), dispatchToken: null }: { scope: ACCOUNT, state: 'not-needed', desiredSha256: null, dispatchToken: null };- s.store.commitGroup({ token: t, baseGeneration: null, records: [rec('form', key, id)], proof: PROOF, consumerState: consumer('form'), publication });+ s.store.commitGroup({ token: t, baseGeneration: null, records: [{ ...rec('form', key, id), origin }], proof: PROOF, consumerState: consumer('form'), publication, adoptionApproved: origin === 'adopted' });}const MAIN_G = { family: 'form', key: 'account/main' };const QUICK_G = { family: 'form', key: 'account/quick' };@@ -2435,6 +2435,168 @@ test('publication refusals: a send answered but not read back names its own dispassert.deepEqual(shapeOf(bare), [PUBLICATION_UNCONFIRMED, undefined, undefined, undefined]);});+// --- Caption diagnostics of an adopted form (lib/form-caption-diagnostics.js) --------------------------------------+// A form the build adopted can read one way saved and another way published in one cell's base-language caption, with+// the publish's saved layer unchanged. No read tells a platform read projection from a maker's unpublished edit, so the+// stop stays exactly as strict as before; it only names the cell and the language. Every helper failure must leave the+// generic stop, its data, its requests and the store exactly as a run with no diagnostic leaves them.+const CAP_TAB = '0a0a0a0a-0000-4000-8000-0000000000a1';+const CAP_SECTION = '0b0b0b0b-0000-4000-8000-0000000000b1';+const CAP_CELL = '0c0c0c0c-0000-4000-8000-0000000000c1';+const CAP_CELL2 = '0d0d0d0d-0000-4000-8000-0000000000d1';+const cellXml = (id, caption, { control = 'subgrid_issues', lcid = '1033', more = '' } = {}) => `<cell id="{${id.toUpperCase()}}"><labels><label description="${caption}" languagecode="${lcid}" />${more}</labels><control id="${control}" classid="{E7A81278-8635-4D9E-8D4D-59480B391C5B}" /></cell>`;+const captionForm = (cells, { section = CAP_SECTION } = {}) => `<form><tabs><tab id="{${CAP_TAB}}" name="general"><labels><label description="General" languagecode="1033" /></labels><columns><column width="100%"><sections><section id="{${section}}" name="main"><labels><label description="Main" languagecode="1033" /></labels><rows><row>${cells}</row></rows></section></sections></column></columns></tab></tabs></form>`;+const SAVED_SPLIT = captionForm(cellXml(CAP_CELL, 'Inspections'));+const PUBLISHED_SPLIT = captionForm(cellXml(CAP_CELL, 'Issues'));+const CAPTION_HELPER = require('node:path').join(__dirname, '..', 'lib', 'form-caption-diagnostics.js');++// Run `fn` with the caption helper module replaced, in the module cache, by `impl` over the real one (a loader stub for+// this test only: production code has no switch for it), and put the cache back after.+async function withCaptionHelper(impl, fn) {+ const Module = require('node:module');+ const before = require.cache[CAPTION_HELPER];+ const real = fs.existsSync(CAPTION_HELPER) ? require(CAPTION_HELPER) : {};+ const stub = new Module(CAPTION_HELPER);+ stub.filename = CAPTION_HELPER;+ stub.loaded = true;+ stub.exports = { ...real, ...impl };+ require.cache[CAPTION_HELPER] = stub;+ try { return await fn(); } finally { if (before) require.cache[CAPTION_HELPER] = before; else delete require.cache[CAPTION_HELPER]; }+}+// The store bytes with the tokens a run mints at random named by their order, so two runs compare by what they wrote.+const tokenless = (text) => {+ const seen = new Map();+ return String(text).replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, (t) => { if (!seen.has(t)) seen.set(t, `token-${seen.size}`); return seen.get(t); });+};+// An adopted form whose publish answers success and is not applied: the published read keeps the old caption, the saved+// read the caption the publish shipped.+async function splitPublish({ origin = 'adopted', savedXml = SAVED_SPLIT, publishedXml = PUBLISHED_SPLIT } = {}) {+ const s = await setup();+ committedForm(s, { id: MAIN, key: 'account/main', publishedXml, savedXml, origin });+ s.wire.script((e) => /PublishXml/.test(e.path), { statusCode: 204, unapplied: true });+ const at = s.wire.log.length;+ const e = await caught(publishManagedScope({+ store: s.store, barrier: s.barrier, scope: ACCOUNT, groups: [MAIN_G], client: s.sdk.dataverse, path: 'managed forms of account',+ publish: () => publishTablesXml(s.sdk.dataverse, ['account']), settle: { sleep: async () => {} },+ }));+ const token = pubOf(s.store).dispatchToken;+ return {+ s, e, token,+ requests: s.wire.log.slice(at).map((x) => `${x.method} ${x.path}`),+ store: tokenless(fs.readFileSync(s.store.file, 'utf8')),+ shape: [e.code, e.dispatchToken === token, e.approval === publicationRiskApproval(ACCOUNT, token), e.remedy === publicationRemedy(ACCOUNT, token)],+ };+}+// The next run's read-only confirmation of that dispatch: the scope's block labels, its answer, and whether it wrote.+async function splitConfirm(s) {+ const n = await nextRun(s);+ const labels = [];+ const before = fs.readFileSync(n.store.file, 'utf8');+ const at = s.wire.log.length;+ const r = await confirmUncertainPublication({ store: n.store, barrier: { blockScope: (scope, label) => labels.push(label) }, scope: ACCOUNT, client: n.sdk.dataverse });+ return { r, labels, unchanged: fs.readFileSync(n.store.file, 'utf8') === before, requests: s.wire.log.slice(at).map((x) => `${x.method} ${x.path}`) };+}++test('caption diagnostics: an adopted form whose saved and published captions differ in one cell stays unconfirmed, and its stop names that cell and language — never its text, never in the store', async () => {+ const run = await splitPublish();+ assert.equal(run.e.code, PUBLICATION_UNCONFIRMED);+ assert.deepEqual(run.shape, [PUBLICATION_UNCONFIRMED, true, true, true], 'the dispatch, approval and remedy are the ones it always named');+ assert.equal(pubOf(run.s.store).state, 'unconfirmed', 'a diagnostic confirms nothing');+ assert.match(run.e.message, /does not show what it shipped: managed form "account\/main" its saved layer is still the one the publish shipped/);+ assert.ok(run.e.message.endsWith(`. managed form "account/main": Caption difference at cell ${CAP_CELL} (language 1033). This observation does not show whether the difference is an unpublished edit or a platform read projection.`), run.e.message);+ assert.doesNotMatch(run.e.message, /Inspections|Issues/, 'no caption text is repeated');+ assert.doesNotMatch(fs.readFileSync(run.s.store.file, 'utf8'), /captionDifferences|languageCode|0c0c0c0c/i, 'the diagnostic is never written to the store');+ // The reader answers it beside the two hashes, which are what they would be without it.+ const group = run.s.store.readGroup('form', 'account/main').committed;+ const read = await readSystemFormLayers(run.s.sdk.dataverse, group);+ assert.deepEqual(read.captionDifferences, { entries: [{ cellId: CAP_CELL, languageCode: 1033 }], omittedCount: 0 });+ const created = await readSystemFormLayers(run.s.sdk.dataverse, { ...group, records: group.records.map((r) => ({ ...r, origin: 'created' })) });+ assert.deepEqual(created, { savedSha256: read.savedSha256, publishedSha256: read.publishedSha256 }, 'a created form gets no diagnostic, and the same two hashes');+ // The next run's read-only confirmation names it too, writes nothing, and leaves the dispatch unconfirmed.+ const next = await splitConfirm(run.s);+ assert.deepEqual(next.r.confirmed, []);+ assert.equal(next.unchanged, true);+ assert.match(next.labels.join('\n'), new RegExp(`a fresh read did not prove it ended: its saved layer is still the one the publish shipped.*; .*publication-risk:table:account/.*\\. managed form "account/main": Caption difference at cell ${CAP_CELL} \\(language 1033\\)`));+});++test('caption diagnostics are fail-safe: a helper that throws, answers anything unusable, or a formatter that throws leaves the generic stop, its data, its requests and the store exactly as a run with no diagnostic', async () => {+ let calls = 0;+ const control = await withCaptionHelper({ cellCaptionDifferences: () => { calls += 1; return null; } }, () => splitPublish());+ assert.ok(calls > 0, 'the adopted form\'s layers are offered to the diagnostic helper');+ const controlNext = await withCaptionHelper({ cellCaptionDifferences: () => null }, () => splitConfirm(control.s));+ assert.equal(control.e.message.includes('Caption difference'), false);+ const cases = [+ ['a helper that throws', { cellCaptionDifferences: () => { calls += 1; throw new Error('diagnostic exploded'); } }],+ ['a malformed answer', { cellCaptionDifferences: () => { calls += 1; return { entries: [{ cellId: 'not-a-guid', languageCode: 1033 }], omittedCount: 0 }; } }],+ ['an empty answer', { cellCaptionDifferences: () => { calls += 1; return { entries: [], omittedCount: 0 }; } }],+ ['too many entries', { cellCaptionDifferences: () => { calls += 1; return { entries: Array.from({ length: 9 }, (_, i) => ({ cellId: `0c0c0c0c-0000-4000-8000-00000000000${i}`, languageCode: 1033 })), omittedCount: 0 }; } }],+ ['a getter that throws', { cellCaptionDifferences: () => { calls += 1; return { get entries() { throw new Error('getter'); }, omittedCount: 0 }; } }],+ ['a formatter that throws', { formatCaptionDifferences: () => { calls += 1; throw new Error('formatter exploded'); } }],+ ['a formatter that answers no text', { formatCaptionDifferences: () => { calls += 1; return { text: 'x' }; } }],+ ];+ for (const [label, impl] of cases) {+ calls = 0;+ const run = await withCaptionHelper(impl, () => splitPublish());+ assert.ok(calls > 0, `${label}: the stub was reached`);+ assert.equal(run.e.code, control.e.code, label);+ assert.equal(run.e.message, control.e.message, `${label}: the generic message`);+ assert.deepEqual(run.shape, control.shape, `${label}: the dispatch, approval and remedy`);+ assert.deepEqual(run.requests, control.requests, `${label}: the requests`);+ assert.equal(run.store, control.store, `${label}: the store bytes`);+ assert.equal(pubOf(run.s.store).state, 'unconfirmed', label);+ const next = await withCaptionHelper(impl, () => splitConfirm(run.s));+ assert.deepEqual(next.r, controlNext.r, `${label}: the recovered confirmation`);+ assert.equal(next.unchanged, true, `${label}: the read-only confirmation writes nothing`);+ assert.deepEqual(next.requests, controlNext.requests, `${label}: the confirmation's requests`);+ assert.deepEqual(next.labels.map((l) => l.split(run.token).join('<token>')), controlNext.labels.map((l) => l.split(control.token).join('<token>')), `${label}: the confirmation's block`);+ }+});++test('caption diagnostics compare one cell by its id, its tab, section and control, one language at a time — anything ambiguous or unread names nothing', () => {+ const { cellCaptionDifferences, formatCaptionDifferences } = require('../lib/form-caption-diagnostics.js');+ const pair = (s, p) => cellCaptionDifferences(captionForm(s), captionForm(p));+ assert.deepEqual(pair(cellXml(CAP_CELL, 'A'), cellXml(CAP_CELL, 'B')), { entries: [{ cellId: CAP_CELL, languageCode: 1033 }], omittedCount: 0 });+ assert.equal(pair(cellXml(CAP_CELL, 'A'), cellXml(CAP_CELL, 'A')), null, 'the same caption');+ // A second language on both sides is compared on its own; one on a single side is not reported (no base language is inferred).+ assert.deepEqual(pair(cellXml(CAP_CELL, 'A', { more: '<label description="X" languagecode="3082" />' }), cellXml(CAP_CELL, 'A', { more: '<label description="Y" languagecode="3082" />' })),+ { entries: [{ cellId: CAP_CELL, languageCode: 3082 }], omittedCount: 0 });+ assert.equal(pair(cellXml(CAP_CELL, 'A', { more: '<label description="X" languagecode="3082" />' }), cellXml(CAP_CELL, 'A')), null);+ // An extra cell, a cell that moved section, or holds another control is not a caption difference.+ assert.equal(pair(cellXml(CAP_CELL, 'A') + cellXml(CAP_CELL2, 'Z'), cellXml(CAP_CELL, 'A')), null);+ assert.equal(cellCaptionDifferences(captionForm(cellXml(CAP_CELL, 'A')), captionForm(cellXml(CAP_CELL, 'B'), { section: CAP_CELL2 })), null);+ assert.equal(pair(cellXml(CAP_CELL, 'A'), cellXml(CAP_CELL, 'B', { control: 'subgrid_other' })), null);+ // Ambiguity names nothing: a cell id twice, a language twice in a cell, a language that is not a whole number, unread XML.+ assert.equal(pair(cellXml(CAP_CELL, 'A') + cellXml(CAP_CELL, 'A'), cellXml(CAP_CELL, 'B')), null);+ assert.equal(pair(cellXml(CAP_CELL, 'A', { more: '<label description="C" languagecode="1033" />' }), cellXml(CAP_CELL, 'B')), null);+ assert.equal(pair(cellXml(CAP_CELL, 'A', { lcid: 'en' }), cellXml(CAP_CELL, 'B', { lcid: 'en' })), null);+ assert.equal(cellCaptionDifferences('<form><tabs>', captionForm(cellXml(CAP_CELL, 'B'))), null);+ assert.equal(cellCaptionDifferences(captionForm(cellXml(CAP_CELL, 'A')), null), null);+ // Bounded: eight named, sorted by cell then language, the rest counted.+ const ids = Array.from({ length: 10 }, (_, i) => `0e0e0e0e-0000-4000-8000-0000000000${String(10 + (9 - i))}`);+ const many = cellCaptionDifferences(captionForm(ids.map((id) => cellXml(id, 'A', { control: id })).join('')), captionForm(ids.map((id) => cellXml(id, 'B', { control: id })).join('')));+ assert.equal(many.entries.length, 8);+ assert.equal(many.omittedCount, 2);+ assert.deepEqual(many.entries.map((e) => e.cellId), [...ids].sort().slice(0, 8));+ assert.match(formatCaptionDifferences(many), /^Caption differences at cell 0e0e0e0e-0000-4000-8000-000000000010 \(language 1033\), .*, and 2 more\. This observation does not show/);+ assert.equal(formatCaptionDifferences({ entries: [{ cellId: 'x', languageCode: 1033 }], omittedCount: 0 }), null);+});++test('caption diagnostics never reach a dashboard or a created form, and never change a layer hash', async () => {+ const run = await splitPublish({ origin: 'created' });+ assert.equal(run.e.code, PUBLICATION_UNCONFIRMED);+ assert.doesNotMatch(run.e.message, /Caption difference/, 'a form the build created is not diagnosed');+ const adopted = await splitPublish();+ assert.equal(adopted.e.message.split('. managed form "account/main": Caption difference')[0], run.e.message, 'the same generic stop before the diagnostic');+ assert.deepEqual(adopted.requests, run.requests, 'the same requests');+ // The dashboard reader is not the form reader: an adopted dashboard root gets no diagnostic.+ const { readSystemFormRootLayers } = require('../lib/systemform-published.js');+ const d = await setup();+ d.wire.putForm({ formid: DASH, name: 'Ops', objecttypecode: 'none', type: 0, formxml: PUBLISHED_SPLIT }, { publishedToo: true });+ d.wire.saved.get(DASH).formxml = SAVED_SPLIT;+ const dash = await readSystemFormRootLayers(d.sdk.dataverse, { root: { kind: 'dashboard', key: 'ops', id: DASH }, records: [{ ...rec('dashboard', 'ops', DASH), origin: 'adopted' }] });+ assert.deepEqual(Object.keys(dash).sort(), ['publishedSha256', 'savedSha256']);+});+// Straight after a publish the platform may answer a cell caption still being rewritten (the wire's `rewritingReads`), while a// read some seconds later is the saved layer exactly: the read-back is made again on the bounded settle schedule, and only a// read that shows the send confirms it.diff --git a/plugins/model-apps/scripts/tests/output-token-writers.test.js b/plugins/model-apps/scripts/tests/output-token-writers.test.jsindex 2bda4fbca..20fe96eb9 100644--- a/plugins/model-apps/scripts/tests/output-token-writers.test.js+++ b/plugins/model-apps/scripts/tests/output-token-writers.test.js@@ -345,6 +345,7 @@ const WRITES = /\.(?:writeFileSync|writeFile|appendFileSync|appendFile|createWriconst GUARDED_WRITERS = {'lib/safe-fs.js': /redactFileData\(data, opts\)/,'lib/apply-snapshot-store.js': /fs\.writeFileSync\(fd, redactFileData\(text\)\)/,+ 'lib/managed-fragments.js': /fs\.writeFileSync\(fd, redactFileData\(text\)\)/,};// The writers that are not guarded, and why none of them can write a token: each writes what the plugin made itself, or what a person gave it, never a word of a service's, or runs in a process that obtains no token.diff --git a/plugins/model-apps/scripts/tests/role-privileges.test.js b/plugins/model-apps/scripts/tests/role-privileges.test.jsindex 93b39bfa7..af4a3a751 100644--- a/plugins/model-apps/scripts/tests/role-privileges.test.js+++ b/plugins/model-apps/scripts/tests/role-privileges.test.js@@ -4,7 +4,7 @@// row landed — verified clean. This is a metadata read, not a runtime check.const { test } = require('node:test');const assert = require('node:assert');-const { declaredPrivileges, compareRolePrivileges, depthFromMask } = require('../lib/role-privileges.js');+const { declaredPrivileges, compareRolePrivileges, compileRolePrivileges, depthFromMask } = require('../lib/role-privileges.js');const { verifySpec } = require('../lib/verify-spec.js');// A realistic privilege set as EntityDefinitions returns it.@@ -229,3 +229,36 @@ test('depthFromMask: tolerates a numeric string', () => {assert.strictEqual(depthFromMask('8'), 'Global');assert.strictEqual(depthFromMask('7'), 'Deep');});++// compileRolePrivileges compiles a persona's requests as the vendored SDK does before ReplacePrivilegesRole: what the managed+// download's persona proof (lib/persona-restore.js) compares a role's held privileges to. The privileges are getEntityPrivileges rows.+const sdkPrivs = (entity, id, scopes = ['user', 'businessUnit', 'parentChild', 'organization']) => [+ { name: `prvRead${entity}`, privilegeId: `{${id}-read}`, privilegeType: 'Read', scopes },+ { name: `prvWrite${entity}`, privilegeId: `${id}-write`, privilegeType: 'Write', scopes },+];+const compiled = (m) => Object.fromEntries([...m].map(([id, v]) => [id, v.depth]));++test('compileRolePrivileges keys each privilege by its bare id at the depth its scope maps to, user scope by default', () => {+ const tables = new Map([['account', sdkPrivs('Account', 'A')], ['contact', sdkPrivs('Contact', 'C')]]);+ const m = compileRolePrivileges([{ entity: 'account', access: ['read', 'write'] }, { entity: 'contact', access: ['read'], scope: 'organization' }], tables);+ assert.deepStrictEqual(compiled(m), { 'a-read': 'Basic', 'a-write': 'Basic', 'c-read': 'Global' });+ assert.strictEqual(m.get('a-read').name, 'prvReadAccount');+});++test('compileRolePrivileges merges a privilege tables share at one scope, takes the deeper scope for one table, and refuses two tables at two', () => {+ const shared = (entity) => [{ name: 'prvReadActivity', privilegeId: 'S-read', privilegeType: 'Read', scopes: ['user', 'organization'] }];+ const tables = new Map([['email', shared('email')], ['task', shared('task')]]);+ assert.deepStrictEqual(compiled(compileRolePrivileges([{ entity: 'email', access: ['read'] }, { entity: 'task', access: ['read'] }], tables)), { 's-read': 'Basic' });+ assert.deepStrictEqual(compiled(compileRolePrivileges([{ entity: 'email', access: ['read'] }, { entity: 'email', access: ['read'], scope: 'organization' }], tables)), { 's-read': 'Global' });+ assert.throws(() => compileRolePrivileges([{ entity: 'email', access: ['read'] }, { entity: 'task', access: ['read'], scope: 'organization' }], tables), /share the privilege 'prvReadActivity' at different scopes/);+});++test('compileRolePrivileges refuses what a build would refuse: no access, an unknown scope or access, an access or scope the table lacks', () => {+ const tables = new Map([['account', sdkPrivs('Account', 'A')], ['flow', sdkPrivs('Flow', 'F', ['organization'])]]);+ assert.throws(() => compileRolePrivileges([{ entity: 'account', access: [] }], tables), /asks for no access/);+ assert.throws(() => compileRolePrivileges([{ entity: 'account', access: ['read'], scope: 'global' }], tables), /unknown scope 'global'/);+ assert.throws(() => compileRolePrivileges([{ entity: 'account', access: ['own'] }], tables), /unknown access 'own'/);+ assert.throws(() => compileRolePrivileges([{ entity: 'account', access: ['delete'] }], tables), /does not support 'delete' access/);+ assert.throws(() => compileRolePrivileges([{ entity: 'flow', access: ['read'] }], tables), /does not support the 'user' scope/);+ assert.throws(() => compileRolePrivileges([{ entity: 'lead', access: ['read'] }], tables), /privileges of 'lead' are not known/);+});diff --git a/plugins/model-apps/scripts/tests/rule-settlement.test.js b/plugins/model-apps/scripts/tests/rule-settlement.test.jsindex fcf1ce80d..36a8f0ec6 100644--- a/plugins/model-apps/scripts/tests/rule-settlement.test.js+++ b/plugins/model-apps/scripts/tests/rule-settlement.test.js@@ -170,6 +170,33 @@ test('a new declared rule is created Draft, proved by a read, then activated byassert.deepEqual(writesSince(wire, again.from), []);});+// #796: the rule's identity read on a table the build has only just created can meet the table's metadata-cache lag (HTTP 400 0x80041102 "…was not found in the MetadataCache…"). With the caller's `freshTable`+// the stop is one the build's bounded retry may ride out and the next settlement creates the rule once; without it, for another table's answer or any other answer, it stays final. Nothing is sent either way.+test('an identity read that meets the metadata-cache lag of a table the build just created stops as the retry may ride out; any other unread answer stays final (#796)', async () => {+ const { retryPolicyFor } = require('../lib/retry-policy.js');+ const notInCache = (t) => `The entity with a name = '${t}' with namemapping = 'Logical' was not found in the MetadataCache.LazyDynamicMetadataCache with version 1 and timestamp 1`;+ const nameRead = (e) => e.method === 'GET' && e.path === 'workflows';+ const answer400 = (code, message) => ({ statusCode: 400, body: { error: { code, message } } });+ for (const [label, answer, freshTable, policy] of [+ ['the lag of a table the build created', answer400('0x80041102', notInCache('account')), 'account', RETRY.SERVICE],+ ['no freshTable', answer400('0x80041102', notInCache('account')), undefined, RETRY.NEVER],+ ['the answer names another table', answer400('0x80041102', notInCache('contoso_other')), 'account', RETRY.NEVER],+ ['an unrelated 400', answer400('0x80040265', 'The value of the attribute is not valid'), 'account', RETRY.NEVER],+ ]) {+ const wire = createWorkflowWire();+ const dir = makeTempDir('rule-settle-');+ wire.script(nameRead, answer);+ const out = await settle(wire, dir, RULE, freshTable ? { freshTable } : {});+ assert.equal(out.error && out.error.cause && out.error.cause.code, 'create-identity-unverified', label);+ assert.equal(retryPolicyFor(out.error.cause), policy, label);+ assert.deepEqual(writesSince(wire, out.from), [], `${label}: nothing is sent`);+ if (policy !== RETRY.SERVICE) continue;+ const again = await settle(wire, dir, RULE, { freshTable });+ assert.ifError(again.error);+ assert.deepEqual(writeLines(wire, again.from).filter((l) => l.startsWith('POST workflows')), ['POST workflows(00000000-0000-0000-0000-000000000000)/Microsoft.Dynamics.CRM.CreateProcessWithWfomJson'], `${label}: one create`);+ }+});+test('a Draft rule is created Draft and never activated', async () => {const wire = createWorkflowWire();const out = await settle(wire, makeTempDir('rule-settle-'), { ...RULE, status: 'Draft' });diff --git a/plugins/model-apps/scripts/tests/schema-features-provision.test.js b/plugins/model-apps/scripts/tests/schema-features-provision.test.jsindex 779a16002..11db5135f 100644--- a/plugins/model-apps/scripts/tests/schema-features-provision.test.js+++ b/plugins/model-apps/scripts/tests/schema-features-provision.test.js@@ -255,6 +255,77 @@ test('a one-way change is made when it is authorized for that column', async ()await run(m, specOf([{ schemaName: 'new_due', type: 'DateTime', dateTimeBehavior: 'DateOnly' }]), { authorizedDestructive: ['dateTimeBehavior:new_ticket.new_due'] });assert.deepEqual(m.calls.find((c) => c[0] === 'updateColumn').slice(1), ['new_ticket', 'new_due', { dateTimeBehavior: 'DateOnly' }]);});++// A table the first lookup misses, whose create is then answered "already exists" (the create of an earlier, lost answer, or another writer's),+// is found by a second lookup. Its columns are read then, as a table the first lookup found has them read, so its Date and Time columns are+// guarded, and an authorized declared repair made, BEFORE the build adds a column to it — in the same build, not the next one.+// POST EntityDefinitions -> HTTP 400 {"error":{"code":"0x8009050d","message":"Entities already exist: new_ticket."}}+function foundAfterCreate({ dates = NULL_TABLE.dates, readBack, columns = NULL_TABLE.tables.new_ticket, columnsRead } = {}) {+ let probes = 0;+ const server = metadataServer({ tables: { new_ticket: columns }, dates, readBack });+ const m = mockSdk({+ dataverseGet: (p) => {+ if (/\?\$select=LogicalName,EntitySetName/.test(p) && (probes += 1) === 1) return { status: 404, body: {} };+ if (columnsRead && /\/Attributes\?\$select=LogicalName,RequiredLevel$/.test(p)) return columnsRead(p);+ return server(p);+ },+ });+ m.sdk.createTable = async (o) => {+ m.calls.push(['createTable', o]);+ throw Object.assign(new Error('HTTP 400: Entities already exist: new_ticket.'), { statusCode: 400, cause: { error: { code: '0x8009050d', message: 'Entities already exist: new_ticket.' } } });+ };+ // The platform's answer to the create of a column the table has (ALREADY_EXISTS_CODES.column).+ m.sdk.createColumn = async (l, o) => {+ m.calls.push(['createColumn', l, o]);+ if (columns.includes(o.schemaName.toLowerCase())) {+ throw Object.assign(new Error(`HTTP 400: An attribute with the specified name ${o.schemaName} already exists for entity ${l}.`), { statusCode: 400, cause: { error: { code: '0x80047013' } } });+ }+ return { logicalName: o.schemaName.toLowerCase(), metadataId: `col-${o.schemaName}` };+ };+ m.provision.dataverse.post = async (p, body) => { m.calls.push(['post', p, body]); return { status: 204, body: {} }; };+ return m;+}+const DUE_AND_NOTE = [{ schemaName: 'new_due', type: 'DateTime', dateTimeBehavior: 'UserLocal' }, { schemaName: 'new_note', type: 'Text' }];+const writesOf = (m) => m.calls.filter((c) => ['updateColumn', 'createColumn'].includes(c[0])).map((c) => `${c[0]} ${c[0] === 'updateColumn' ? c[2] : c[2].schemaName}`);++test('a table found after its create was answered "already exists" has its declared Date and Time repair made and read back before a column is added, in the same build', async () => {+ for (const preflight of [true, false]) {+ const m = foundAfterCreate({ readBack: dateRow('new_due', 'UserLocal') });+ await run(m, specOf(DUE_AND_NOTE), { dateBehaviorPreflight: preflight });+ assert.equal(m.calls.filter((c) => c[0] === 'createTable').length, 1, `preflight ${preflight}`);+ assert.deepEqual(writesOf(m), ['updateColumn new_due', 'createColumn new_note'], `preflight ${preflight}: the repair, then only the new column`);+ assert.deepEqual(m.calls.find((c) => c[0] === 'updateColumn').slice(1), ['new_ticket', 'new_due', { dateTimeBehavior: 'UserLocal' }]);+ assert.equal(dateGets(m).length, 2, `preflight ${preflight}: the collection read and the one column read-back`);+ }+});++test('a table found after its create keeps every rule of a table the first lookup found: no consent, no repair; unreadable columns, the old path', async () => {+ // A one-way change without its consent is refused before any column is sent, as for a table the first lookup found.+ const refused = foundAfterCreate({ dates: { value: [dateRow('new_due', 'UserLocal')] } });+ const err = await halted(run(refused, specOf([{ schemaName: 'new_due', type: 'DateTime', dateTimeBehavior: 'DateOnly' }, { schemaName: 'new_note', type: 'Text' }]), { dateBehaviorPreflight: true }));+ assert.equal(err.code, 'DESTRUCTIVE_NOT_AUTHORIZED');+ assert.deepEqual(writesOf(refused), []);+ // With it, the change is made before the new column.+ const consented = foundAfterCreate({ dates: { value: [dateRow('new_due', 'UserLocal')] }, readBack: dateRow('new_due', 'DateOnly') });+ await run(consented, specOf([{ schemaName: 'new_due', type: 'DateTime', dateTimeBehavior: 'DateOnly' }, { schemaName: 'new_note', type: 'Text' }]),+ { dateBehaviorPreflight: true, authorizedDestructive: ['dateTimeBehavior:new_ticket.new_due'] });+ assert.deepEqual(writesOf(consented), ['updateColumn new_due', 'createColumn new_note']);+ // Columns that cannot be read leave the build where it was: every declared column looks new, and the preflight stops on the column with+ // no behaviour before anything is sent.+ const unread = foundAfterCreate({ readBack: dateRow('new_due', 'UserLocal'), columnsRead: () => ({ status: 503, body: {} }) });+ const err2 = await halted(run(unread, specOf(DUE_AND_NOTE), { dateBehaviorPreflight: true }));+ assert.equal(err2.code, 'DATETIME_BEHAVIOR_MISSING');+ assert.deepEqual(writesOf(unread), []);+});++test('an existing column declared secured on a table found after its create is still secured', async () => {+ const m = foundAfterCreate({ columns: ['new_ticketid', 'new_name', 'new_salary'], dates: { value: [] } });+ m.provision.dataverse.get = ((get) => async (p) => (/\$select=LogicalName,IsSecured$/.test(p) ? { status: 200, body: securedRowsOf(false) } : get(p)))(m.provision.dataverse.get);+ await run(m, specOf([{ schemaName: 'new_salary', type: 'Money', isSecured: true }, { schemaName: 'new_note', type: 'Text' }]));+ assert.deepEqual(m.calls.filter((c) => c[0] === 'updateColumn').map((c) => c.slice(1)), [['new_ticket', 'new_salary', { isSecured: true }]]);+ assert.deepEqual(writesOf(m).filter((w) => w.startsWith('createColumn')), ['createColumn new_note'], 'the column the table has is not sent');+});+const securedRowsOf = (salary) => ({ value: [{ LogicalName: 'new_name', IsSecured: false }, { LogicalName: 'new_salary', IsSecured: salary }] });// ------------------------------------------------------------------------------------------------ column securityconst SECURE_TABLE = { tables: { new_ticket: ['new_ticketid', 'new_name', 'new_salary'] } };diff --git a/plugins/model-apps/scripts/tests/sdk-build-declared-bpf.test.js b/plugins/model-apps/scripts/tests/sdk-build-declared-bpf.test.jsindex c6d577f0c..0ef9da400 100644--- a/plugins/model-apps/scripts/tests/sdk-build-declared-bpf.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build-declared-bpf.test.js@@ -13,8 +13,10 @@const test = require('node:test');const assert = require('node:assert/strict');-const { runSdkBuild } = require('../lib/sdk-build.js');-const { validateAppSpec } = require('../lib/app-spec.js');+const { runSdkBuild, personaRoleSpecFor } = require('../lib/sdk-build.js');+const { validateAppSpec, BPF_ROLE_ACCESS } = require('../lib/app-spec.js');+const { JOB_NAME } = require('../lib/persona-restore.js');+const { withRoles, CHILD_BU, ORG_OWNED } = require('./helpers/role-wire.js');const { openManagedBindings, attemptProvenUnsent } = require('../lib/managed-bindings.js');const { createPublicationBarrier } = require('../lib/publication-barrier.js');const { createAttemptSendObserver } = require('../lib/managed-feature-contract.js');@@ -207,6 +209,78 @@ test('a declared flow is created Draft under its catalog ids, proved, then activ});});+// #796: the flow's identity read on a table this invocation created can meet the table's metadata-cache lag (HTTP 400 0x80041102 "…was not found in the MetadataCache…"). The build's stop is then one its bounded+// retry may ride out (build-model-app.js isTransientHalt); with the table not created by this invocation the same answer stays final. Nothing is sent either way, and the next build creates the flow once.+test('a declared flow whose identity read meets the lag of a table this invocation created stops as a retry may ride out, and the next attempt creates it once (#796)', async () => {+ const { isTransientHalt } = require('../build-model-app.js');+ const lag = { statusCode: 400, body: { error: { code: '0x80041102', message: "The entity with a name = 'new_ticket' with namemapping = 'Logical' was not found in the MetadataCache.LazyDynamicMetadataCache with version 1 and timestamp 1" } } };+ const nameRead = (e) => e.method === 'GET' && e.path === 'workflows';+ await withBpf(true, async () => {+ for (const fresh of [true, false]) {+ const wire = createWorkflowWire();+ const dir = makeTempDir('declared-bpf-');+ const createdTables = fresh ? new Set(['new_ticket']) : new Set();+ wire.script(nameRead, lag);+ const first = await build(wire, dir, specWith([FLOW]), { createdTables });+ assert.ok(first.err, `fresh=${fresh}: the run stops`);+ assert.deepEqual(first.writes.filter((c) => /^workflows/i.test(c.path)), [], `fresh=${fresh}: nothing is sent for the flow`);+ assert.equal(isTransientHalt(first.err, { spec: specWith([FLOW]) }), fresh, `fresh=${fresh}: ${chainText(first.err)}`);+ if (!fresh) continue;+ const again = await build(wire, dir, specWith([FLOW]), { createdTables });+ assert.equal(again.err, undefined, chainText(again.err));+ assert.deepEqual(again.writes.filter((c) => /^workflows/i.test(c.path)).map((c) => c.method), ['POST', 'PATCH'], 'created once, then activated');+ }+ });+});++// The whole CLI assembly (build-model-app.js buildModelApp) over the same wire, its attempt told the table was created by this invocation:+// a lag on the flow's identity read is read again in place within the build's one retry allowance, and once that is spent the build stops+// with the service's own answer in the words the CLI prints (dataverse-auth.js emitResult: redactOutput(err.message)), not only in its cause chain.+test('a declared flow\'s identity read on a table this invocation created is read again in place; past the build\'s retries the printed stop quotes the service\'s answer (#796)', async () => {+ const { redactOutput } = require('../lib/output-redaction.js');+ const MESSAGE = "The entity with a name = 'new_ticket' with namemapping = 'Logical' was not found in the MetadataCache.LazyDynamicMetadataCache with version 1 and timestamp 1";+ const nameRead = (e) => e.method === 'GET' && e.path === 'workflows';+ await withBpf(true, async () => {+ const cli = async (lags) => {+ const wire = createWorkflowWire();+ for (let i = 0; i < lags; i += 1) wire.script(nameRead, { statusCode: 400, body: { error: { code: '0x80041102', message: MESSAGE } } });+ const appDir = makeTempDir('declared-bpf-');+ const dir = path.join(appDir, '.maker-workspace');+ fs.mkdirSync(dir);+ const barrier = createPublicationBarrier();+ const sendObserver = createAttemptSendObserver();+ const workflowEffectGate = createDeferredWorkflowGate();+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: ORIGIN, httpClient: clientOver(wire, { barrier, observer: sendObserver, workflowEffectGate }) });+ await sdk.initWorkspace();+ const events = [];+ let attempts = 0;+ let err;+ try {+ await buildModelApp(specWith([FLOW]), { apply: true, env: ORIGIN, workspaceDir: dir, appDir, retryDelayMs: 0 }, {+ sdk, provisionSdk: sdk, publicationBarrier: barrier, sendObserver, workflowEffectGate, warn: () => {}, log: () => {},+ journal: { path: 'x', record: (e) => events.push(e), close: () => {} },+ runBuild: (s, o) => { attempts += 1; o.createdTables.add('new_ticket'); return runSdkBuild(s, { ...o, phases: ['business-process-flows'] }); },+ });+ } catch (e) { err = e; }+ return { err, attempts, retries: events.filter((e) => e.status === 'retry').length, workflowWrites: wire.log.filter((c) => c.method !== 'GET' && /^workflows/i.test(c.path)) };+ };+ const recovered = await cli(2);+ assert.equal(recovered.err, undefined, chainText(recovered.err));+ assert.equal(recovered.attempts, 1, 'one attempt: the read was made again where it failed');+ assert.equal(recovered.retries, 2);+ assert.deepEqual(recovered.workflowWrites.map((c) => c.method), ['POST', 'PATCH'], 'created once, then activated');+ const spent = await cli(4);+ assert.ok(spent.err, 'the lag outlasts the three retries');+ assert.equal(spent.attempts, 1);+ assert.equal(spent.retries, 3);+ assert.deepEqual(spent.workflowWrites, [], 'nothing is sent for the flow');+ const printed = redactOutput(spent.err.message);+ assert.match(printed, /HTTP 400/, printed);+ assert.ok(printed.includes('0x80041102'), printed);+ assert.ok(printed.includes(MESSAGE), printed);+ });+});+test('a declared flow found unbound halts through the build halt with the typed adoption it needs; the adopted flow keeps its stored backing table', async () => {await withBpf(true, async () => {const wire = createWorkflowWire();@@ -526,14 +600,15 @@ test('verify lists a reader that cannot read a flow as unverified, and a flow th// download-model-app.js main with its side effects replaced: the download's SDK is a real one over the wire, and runDownload answers// the spec a download of this app hydrates, which holds no process flow (a plain download reconstructs none), or `plain` if given.-async function download(wire, out, argv, { plain, personas, ...extra } = {}) {+async function download(wire, out, argv, { plain, personas, appId, ...extra } = {}) {const { sdk } = await sdkOver(wire);const dl = Object.create(sdk);- dl.queryRecords = async (table, o) => (table === 'appmodule' ? [{ uniquename: APP }] : sdk.queryRecords(table, o));+ dl.queryRecords = async (table, o) => (table === 'appmodule' ? [{ uniquename: APP, ...(appId ? { appmoduleid: appId } : {}) }] : sdk.queryRecords(table, o));const downloaded = specWith([]);delete downloaded.businessProcessFlows;if (plain) downloaded.businessProcessFlows = plain;- // A download writes no personas[]; `personas` stands in for a spec that has them, the control of a flow that names one.+ // A plain download writes no personas[]; `personas` stands in for a spec that has them, the control of a flow that names one.+ // `appId` is the app's id in the app read, which the persona proof needs to read the roles the app is associated with.if (personas) downloaded.personas = personas;const emitted = [];const said = [];@@ -600,7 +675,7 @@ test('the explicit managed download names a flow whose last attempt is not settl});});-test('the explicit managed download leaves out a flow whose securityRoles name personas, which a download never writes, and says what to copy', async () => {+test('the explicit managed download leaves out a flow whose securityRoles name personas it cannot prove from their roles, and says what to copy', async () => {await withBpf(true, async () => {const DISPATCHER = { persona: 'Dispatcher', jobs: [{ name: 'Triage tickets', privileges: [{ entity: 'new_ticket', access: ['read', 'write'] }] }] };const AGENT = { persona: 'Agent', jobs: [{ name: 'Resolve tickets', privileges: [{ entity: 'new_ticket', access: ['read'] }] }] };@@ -610,21 +685,615 @@ test('the explicit managed download leaves out a flow whose securityRoles name passert.equal((await build(wire, dir, { ...specWith([roled]), personas: [DISPATCHER, AGENT] })).err, undefined);assert.deepEqual(storeOf(dir).readGroup('bpf', GROUP).committed.originalDeclaration.securityRoles, roled.securityRoles, 'the store keeps the roles');const flags = ['--include-managed', '--managed-manifest', storeFileOf(dir)];- const left = await download(wire, makeTempDir('declared-bpf-'), flags);+ const out = makeTempDir('declared-bpf-');+ const left = await download(wire, out, flags);assert.equal(left.emitted[0].ok, true, JSON.stringify(left.emitted) + left.said);- assert.deepEqual(left.emitted[0].payload.managedBpfs, { restored: [], stale: [{ key: GROUP, reason: 'its securityRoles name persona \'Dispatcher\', persona \'Agent\', and a download writes no personas[]; copy this flow and the personas it names from the spec it was built from' }] });+ // This wire holds no role and no business unit: the proof reads, finds nothing to prove from, and makes no persona up.+ const unproved = (p) => `persona '${p}', which the download could not prove from its role: the root business unit could not be read`;+ const reason = `its securityRoles name ${unproved('Dispatcher')}; ${unproved('Agent')}; copy this flow and the personas it names from the spec it was built from`;+ assert.deepEqual(left.emitted[0].payload.managedBpfs, { restored: [], stale: [{ key: GROUP, reason }] });assert.match(left.said, /WARNING: managed business process flow new_ticket\/Ticket process was not restored: its securityRoles name persona 'Dispatcher'/);assert.equal(left.written.businessProcessFlows, undefined, 'never restored without its roles');assert.equal(left.written.personas, undefined, 'and no persona is made up');+ // The proved flow is written ready to paste, with the personas it still needs, in the download's own fragments file.+ // A new file, named for this download: the result and the warning name it.+ const fragmentsFile = left.emitted[0].payload.managedFragments.file;+ assert.equal(path.dirname(fragmentsFile), path.join(out, '.maker-workspace'));+ assert.match(path.basename(fragmentsFile), /^managed-fragments-\d{8}T\d{6}Z-[0-9a-f]{6}\.json$/);+ assert.deepEqual(left.emitted[0].payload.managedFragments, { file: fragmentsFile, keys: [{ family: 'bpf', key: GROUP }] });+ assert.ok(left.said.includes(`WARNING: 1 managed item(s) left out only for what the download could not bring are written ready to paste in ${fragmentsFile}:`), left.said);+ const fragments = JSON.parse(fs.readFileSync(fragmentsFile, 'utf8'));+ assert.equal(fragments.kind, 'model-apps.managed-download-fragments');+ assert.equal(fragments.formatVersion, 1);+ assert.equal(fragments.app, APP);+ assert.deepEqual(fragments.items, [{ family: 'bpf', key: GROUP, reason, needs: [{ persona: 'Dispatcher' }, { persona: 'Agent' }], paste: { businessProcessFlows: [roled] } }]);// Only the persona it lacks is named; with every one there, the same flow is restored whole, roles included.const one = await download(wire, makeTempDir('declared-bpf-'), flags, { personas: [{ ...DISPATCHER, persona: ' dispatcher ' }] });- assert.match(one.emitted[0].payload.managedBpfs.stale[0].reason, /^its securityRoles name persona 'Agent', and a download/);- const both = await download(wire, makeTempDir('declared-bpf-'), flags, { personas: [DISPATCHER, AGENT] });+ assert.match(one.emitted[0].payload.managedBpfs.stale[0].reason, /^its securityRoles name persona 'Agent', which the download could not prove from its role: /);+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(one.emitted[0].payload.managedFragments.file), 'utf8')).items[0].needs, [{ persona: 'Agent' }]);+ // Into the same folder: nothing is left out, so the payload says nothing of fragments, nothing is written, and the file the+ // earlier download wrote is kept as it was (the download never removes a file there).+ const earlier = fs.readFileSync(fragmentsFile);+ const both = await download(wire, out, flags, { personas: [DISPATCHER, AGENT] });assert.deepEqual(both.emitted[0].payload.managedBpfs, { restored: [GROUP], stale: [] });assert.deepEqual(both.written.businessProcessFlows, [roled]);+ assert.equal('managedFragments' in both.emitted[0].payload, false);+ assert.deepEqual(fs.readFileSync(fragmentsFile), earlier, 'the earlier download\'s file is kept, byte for byte');+ assert.deepEqual(fs.readdirSync(path.join(out, '.maker-workspace')).filter((n) => n.startsWith('managed-fragments')), [path.basename(fragmentsFile)]);});});+// --- personas proved from their roles ---------------------------------------------------------------------------------------++const APP_ID = '00000000-0000-0000-0000-00000000a333';+const DISPATCHER = { persona: 'Dispatcher', jobs: [{ name: 'Triage tickets', privileges: [{ entity: 'new_ticket', access: ['read', 'write'] }] }] };+const ROLED = { ...FLOW, securityRoles: { personas: ['Dispatcher'] } };++// A flow built with a persona, and the persona's role as a build leaves it: made by the real SDK from the persona+// (createPersonaRole), with the flow's grants on its backing table (addEntityPrivilegesToRole), in the solution, and associated+// with the app unless the persona opts out. `grants`, `member` and `associated` leave one of those undone. `also` are more flows+// built with it whose backing tables the role is NOT granted on.+async function rolesBuilt({ persona = DISPATCHER, grants = true, member = true, associated = persona.appAccess !== false, also = [] } = {}) {+ const wire = createWorkflowWire();+ const roles = withRoles(wire, { solution: SOLUTION, appId: APP_ID });+ roles.table('new_ticket');+ const appRead = roles.table('appmodule', ORG_OWNED).read;+ const dir = makeTempDir('declared-bpf-');+ assert.equal((await build(wire, dir, { ...specWith([ROLED, ...also]), personas: [persona] })).err, undefined);+ const backingOf = (flow) => wire.row(storeOf(dir).readGroup('bpf', `new_ticket/${flow.name}`).committed.root.id).uniquename;+ const backing = backingOf(ROLED);+ assert.ok(backing, 'the built flow names its backing table');+ for (const flow of [ROLED, ...also]) roles.table(backingOf(flow), ORG_OWNED);+ const { sdk } = await sdkOver(wire);+ const { roleId } = await sdk.createPersonaRole(personaRoleSpecFor(persona));+ if (grants) await sdk.addEntityPrivilegesToRole(roleId, [{ entity: backing, access: BPF_ROLE_ACCESS, scope: 'organization' }]);+ if (member) roles.members.add(roleId);+ if (associated) roles.appRoles.add(roleId);+ return { wire, roles, backing, roleId, appRead, role: roles.roles.get(roleId), flags: ['--include-managed', '--managed-manifest', storeFileOf(dir)] };+}++// Answers the GETs `match` picks with `answer(req, prior)` in place of the wire's own (`prior` is the wire's own, to edit).+function answerGets(r, match, answer) {+ const prior = r.wire.request;+ r.wire.request = async (req) => (req.method === 'GET' && match(req) ? answer(req, prior) : prior(req));+}+const json = (body) => ({ statusCode: 200, headers: {}, body: JSON.stringify(body) });+const isAssociation = (req) => /appmoduleroles_association/.test(req.url);+const isTables = (req) => /\/EntityDefinitions\?/.test(req.url);+const associationPage2 = `${ORIGIN}/api/data/v9.2/appmodules(${APP_ID})/appmoduleroles_association?$select=roleid&page=2`;++test('the explicit managed download writes a persona a restored flow names from its role, when a rebuild provably leaves that role as it is', async () => {+ await withBpf(true, async () => {+ for (const persona of [DISPATCHER, { ...DISPATCHER, appAccess: false }]) {+ const r = await rolesBuilt({ persona });+ const before = r.roles.heldOf(r.roleId);+ const got = await download(r.wire, makeTempDir('declared-bpf-'), r.flags, { appId: APP_ID });+ assert.equal(got.emitted[0].ok, true, JSON.stringify(got.emitted) + got.said);+ assert.deepEqual(got.emitted[0].payload.managedBpfs, { restored: [GROUP], stale: [], personas: [{ name: 'Dispatcher', flows: [GROUP] }] });+ const privileges = [+ { entity: r.backing, access: ['create', 'read', 'write', 'delete'], scope: 'organization' },+ { entity: 'new_ticket', access: ['read', 'write'], scope: 'user' },+ ].sort((a, b) => (a.entity < b.entity ? -1 : 1));+ const written = { persona: 'Dispatcher', ...(persona.appAccess === false ? { appAccess: false } : {}), jobs: [{ name: JOB_NAME, privileges }] };+ assert.deepEqual(got.written.personas, [written]);+ assert.deepEqual(got.written.businessProcessFlows, [ROLED], 'the flow is restored with its roles');+ assert.equal('managedFragments' in got.emitted[0].payload, false);+ assert.match(got.said, /NOTE: persona 'Dispatcher' was written from its role as it is now; a build owns a persona's role, so a privilege added to that role outside the spec is removed by the next build\./);+ assert.deepEqual(got.calls.filter((c) => c.method !== 'GET'), [], 'the download writes nothing to the environment');+ // A rebuild from what was written, as its security phase makes it with the real SDK: the same role, converged onto exactly+ // what it held (before the flow grants are added again, too), and the flow grants then change nothing.+ const { sdk } = await sdkOver(r.wire);+ const again = await sdk.createPersonaRole(personaRoleSpecFor(got.written.personas[0]));+ assert.equal(again.roleId, r.roleId);+ assert.deepEqual(r.roles.heldOf(r.roleId), before, 'ReplacePrivilegesRole leaves the role as it was');+ await sdk.addEntityPrivilegesToRole(r.roleId, [{ entity: r.backing, access: BPF_ROLE_ACCESS, scope: 'organization' }]);+ assert.deepEqual(r.roles.heldOf(r.roleId), before);+ }+ });+});++test('a persona the managed download wrote for one flow is proved again for the next flow that names it', async () => {+ await withBpf(true, async () => {+ // Groups are restored in key order, so 'Zeta process' comes after 'Ticket process' and finds the persona already written.+ const ZETA = { ...ROLED, name: 'Zeta process' };+ const r = await rolesBuilt({ also: [ZETA] });+ const before = r.roles.heldOf(r.roleId);+ const got = await download(r.wire, makeTempDir('declared-bpf-'), r.flags, { appId: APP_ID });+ assert.equal(got.emitted[0].ok, true, JSON.stringify(got.emitted) + got.said);+ const { managedBpfs } = got.emitted[0].payload;+ assert.deepEqual(managedBpfs.restored, [GROUP]);+ assert.deepEqual(managedBpfs.personas, [{ name: 'Dispatcher', flows: [GROUP] }], 'written for the first flow only');+ assert.equal(managedBpfs.stale.length, 1);+ assert.equal(managedBpfs.stale[0].key, 'new_ticket/Zeta process');+ assert.match(managedBpfs.stale[0].reason, /^its securityRoles name persona 'Dispatcher', which the download could not prove from its role: its role does not hold prvCreate\w+, prvRead\w+, prvWrite\w+ and 1 more at organization scope on the flow's backing table '\w+', which a build would grant; copy this flow/);+ assert.deepEqual(got.written.businessProcessFlows, [ROLED]);+ assert.equal(got.written.personas.length, 1);+ assert.deepEqual(got.calls.filter((c) => c.method !== 'GET'), []);+ assert.deepEqual(r.roles.heldOf(r.roleId), before);+ });+});++test('the persona proof reads every page of the app association: a role the server answers on a later page is associated, never appAccess false', async () => {+ await withBpf(true, async () => {+ const r = await rolesBuilt();+ const before = r.roles.heldOf(r.roleId);+ const pages = [];+ answerGets(r, isAssociation, (req) => {+ pages.push(req.url);+ return /page=2/.test(req.url)+ ? json({ value: [{ roleid: r.roleId }] })+ : json({ value: [{ roleid: '00000000-0000-4000-8000-00000000eeee' }], '@odata.nextLink': associationPage2 });+ });+ const got = await download(r.wire, makeTempDir('declared-bpf-'), r.flags, { appId: APP_ID });+ assert.equal(got.emitted[0].ok, true, JSON.stringify(got.emitted) + got.said);+ assert.equal(pages.length, 2, 'the next link is followed');+ assert.deepEqual(got.emitted[0].payload.managedBpfs, { restored: [GROUP], stale: [], personas: [{ name: 'Dispatcher', flows: [GROUP] }] });+ assert.equal('appAccess' in got.written.personas[0], false, 'associated: the default, which keeps the association');+ assert.equal(got.written.personas[0].jobs[0].privileges.some((p) => p.entity === 'appmodule'), false, 'the appmodule read is the build\'s own, not a job privilege');+ const { sdk } = await sdkOver(r.wire);+ assert.equal((await sdk.createPersonaRole(personaRoleSpecFor(got.written.personas[0]))).roleId, r.roleId);+ assert.deepEqual(r.roles.heldOf(r.roleId), before, 'a rebuild leaves the role as it was');+ });+});++test('a flow whose securityRoles name two personas is restored only when both are proved', async () => {+ await withBpf(true, async () => {+ const r = await rolesBuilt();+ const two = { ...ROLED, securityRoles: { personas: ['Dispatcher', 'Agent'] } };+ const dir = path.dirname(r.flags[2]);+ assert.equal((await build(r.wire, dir, { ...specWith([two]), personas: [DISPATCHER, { ...DISPATCHER, persona: 'Agent' }] })).err, undefined);+ const got = await download(r.wire, makeTempDir('declared-bpf-'), r.flags, { appId: APP_ID });+ assert.equal(got.emitted[0].ok, true, JSON.stringify(got.emitted) + got.said);+ assert.deepEqual(got.emitted[0].payload.managedBpfs.restored, []);+ assert.equal(got.written.personas, undefined, 'none of them, not the one that was proved');+ assert.equal(got.written.businessProcessFlows, undefined);+ assert.deepEqual(got.emitted[0].payload.managedFragments.keys, [{ family: 'bpf', key: GROUP }]);+ });+});++test('the explicit managed download writes no persona it cannot prove from its role, and leaves the flow out with what to copy', async () => {+ await withBpf(true, async () => {+ const cases = [+ ['a privilege no table carries', {}, (r) => r.role.held.set(r.roles.plainPrivilege('prvExportToExcel'), 8), /its role holds 1 privilege\(s\) no table carries \(prvExportToExcel\); a persona declares table privileges only, so a build would remove them$/],+ ['its role in a child business unit only', {}, (r) => { r.role._businessunitid_value = CHILD_BU; }, /no role named 'Dispatcher' is in the root business unit$/],+ ['a role a build did not make', {}, (r) => { r.role.description = 'Made by hand'; }, /a role named 'Dispatcher' in the root business unit is managed or was not made by a build, and a build refuses to change it$/],+ ['a managed role', {}, (r) => { r.role.ismanaged = true; }, /is managed or was not made by a build/],+ ['a second role made by a build', {}, (r) => r.roles.addRole({ name: 'Dispatcher' }), /more than one role made by a build is named 'Dispatcher' in the root business unit$/],+ ['no flow grants', { grants: false }, () => {}, /its role does not hold prvCreate\w+, prvRead\w+, prvWrite\w+ and 1 more at organization scope on the flow's backing table '\w+', which a build would grant$/],+ ['the app associated without its read', {}, (r) => r.role.held.delete(r.appRead), /a persona read from its role would not rebuild it exactly \(a build would add prvReadAppmodule at Global\)$/],+ ['outside the solution', { member: false }, () => {}, /its role is not in solution 'BP', so a build would add it$/],+ // Whether the app is associated is written as `appAccess`, so only a complete, well-formed association read decides it.+ ['an app association answered without its list', {}, (r) => answerGets(r, isAssociation, () => json({ unexpected: 'no list' })), /whether the app is associated with its role could not be read \(the association rows: no readable result set\)$/],+ ['an app association row that names no role', {}, (r) => answerGets(r, isAssociation, () => json({ value: [{ roleid: r.roleId }, { name: 'no id' }] })), /whether the app is associated with its role could not be read \(an association row names no role\)$/],+ ['an app association page after the first refused', {}, (r) => answerGets(r, isAssociation, (req) => (/page=2/.test(req.url)+ ? { statusCode: 403, headers: {}, body: JSON.stringify({ error: { code: '0x80040220', message: 'no read privilege' } }) }+ : json({ value: [{ roleid: r.roleId }], '@odata.nextLink': associationPage2 }))), /whether the app is associated with its role could not be read \(the association rows: HTTP 403 /],+ // A second marked role of the name, and a lookup the server cuts to one row with a next link: one row read is not one role.+ ['a role lookup cut short', {}, (r) => {+ r.roles.addRole({ name: 'Dispatcher' });+ answerGets(r, (req) => /\/roles$/.test(new URL(req.url).pathname), async (req, prior) => {+ const answer = await prior(req);+ const body = JSON.parse(answer.body);+ body.value = body.value.slice(0, 1);+ body['@odata.nextLink'] = `${ORIGIN}/api/data/v9.2/roles?page=2`;+ return { ...answer, body: JSON.stringify(body) };+ });+ }, /its role lookup was cut short, so it is not known to be the only role named 'Dispatcher' in the root business unit$/],+ ['table metadata the server says continues', {}, (r) => answerGets(r, isTables, async (req, prior) => {+ const answer = await prior(req);+ const body = JSON.parse(answer.body);+ body['@odata.nextLink'] = `${ORIGIN}/api/data/v9.2/EntityDefinitions?page=2`;+ return { ...answer, body: JSON.stringify(body) };+ }), /which table each privilege of its role belongs to could not be read \(the answer says more tables exist\)$/],+ ['table metadata refused', {}, (r) => answerGets(r, isTables, () => ({ statusCode: 403, headers: {}, body: JSON.stringify({ error: { code: '0x80040220', message: 'no metadata access' } }) })), /which table each privilege of its role belongs to could not be read \(HTTP 403\)$/],+ ];+ for (const [label, opts, change, why] of cases) {+ const r = await rolesBuilt(opts);+ await change(r);+ const before = r.roles.heldOf(r.roleId);+ const got = await download(r.wire, makeTempDir('declared-bpf-'), r.flags, { appId: APP_ID });+ assert.equal(got.emitted[0].ok, true, label + JSON.stringify(got.emitted) + got.said);+ const { managedBpfs } = got.emitted[0].payload;+ assert.deepEqual(managedBpfs.restored, [], label);+ assert.equal('personas' in managedBpfs, false, label);+ const { reason } = managedBpfs.stale[0];+ assert.match(reason, /^its securityRoles name persona 'Dispatcher', which the download could not prove from its role: /, label);+ assert.match(reason.replace(/; copy this flow and the personas it names from the spec it was built from$/, ''), why, label);+ assert.equal(got.written.personas, undefined, label);+ assert.equal(got.written.businessProcessFlows, undefined, label);+ assert.deepEqual(got.emitted[0].payload.managedFragments.keys, [{ family: 'bpf', key: GROUP }], label);+ assert.doesNotMatch(got.said, /NOTE: persona/, label);+ assert.deepEqual(got.calls.filter((c) => c.method !== 'GET'), [], label);+ assert.deepEqual(r.roles.heldOf(r.roleId), before, label);+ }+ });+});++test('the managed download writes its fragments to a new file it creates, and never writes over, through or instead of a file that is there', async () => {+ await withBpf(true, async () => {+ const roled = { ...FLOW, securityRoles: { personas: ['Dispatcher'] } };+ const DISPATCHER = { persona: 'Dispatcher', jobs: [{ name: 'Triage tickets', privileges: [{ entity: 'new_ticket', access: ['read'] }] }] };+ const wire = createWorkflowWire();+ const dir = makeTempDir('declared-bpf-');+ assert.equal((await build(wire, dir, { ...specWith([roled]), personas: [DISPATCHER] })).err, undefined);+ const flags = ['--include-managed', '--managed-manifest', storeFileOf(dir)];+ const OWN = `${JSON.stringify({ kind: 'model-apps.managed-download-fragments', formatVersion: 1, app: APP, items: [{ family: 'bpf', key: 'old/Old' }] })}\n`;+ // Whatever is in .maker-workspace before the download is there after it, byte for byte; the one new fragments file is added.+ const writtenBeside = async (label, prepare) => {+ const out = makeTempDir('declared-bpf-');+ const ws = path.join(out, '.maker-workspace');+ fs.mkdirSync(ws);+ prepare(ws);+ const before = snapshotTree(ws);+ const got = await download(wire, out, flags);+ assert.equal(got.emitted[0].ok, true, label + JSON.stringify(got.emitted) + got.said);+ const { file, keys } = got.emitted[0].payload.managedFragments;+ assert.deepEqual(keys, [{ family: 'bpf', key: GROUP }], label);+ assert.equal(path.dirname(file), ws, label);+ assert.match(path.basename(file), /^managed-fragments-\d{8}T\d{6}Z-[0-9a-f]{6}\.json$/, label);+ assert.equal(path.basename(file) in before, false, `${label}: a name that was free`);+ assert.deepEqual(JSON.parse(fs.readFileSync(file, 'utf8')).items.map((i) => i.key), [GROUP], label);+ assert.ok(got.said.includes(`are written ready to paste in ${file}:`), label);+ const after = snapshotTree(ws);+ for (const name of Object.keys(before)) assert.equal(after[name], before[name], `${label}: ${name} is as it was`);+ assert.deepEqual(Object.keys(after).filter((n) => n.startsWith('managed-fragments') && !(n in before)), [path.basename(file)], label);+ return { out, ws, file };+ };+ // A maker's file at the name earlier versions used, one that is not JSON, a folder there, and a file a download wrote: all kept.+ await writtenBeside('a maker\'s JSON file', (ws) => fs.writeFileSync(path.join(ws, 'managed-fragments.json'), '{"mine":true}\n'));+ await writtenBeside('a maker\'s notes', (ws) => fs.writeFileSync(path.join(ws, 'managed-fragments.json'), 'notes'));+ await writtenBeside('a folder', (ws) => { fs.mkdirSync(path.join(ws, 'managed-fragments.json')); fs.writeFileSync(path.join(ws, 'managed-fragments.json', 'inside.txt'), 'kept'); });+ await writtenBeside('an earlier download\'s file', (ws) => fs.writeFileSync(path.join(ws, 'managed-fragments.json'), OWN));+ // Files named the way this download names its own, a maker's and an earlier download's: kept, and the new one is another name.+ await writtenBeside('files of the new kind', (ws) => {+ fs.writeFileSync(path.join(ws, 'managed-fragments-20260101T000000Z-000000.json'), 'maker notes');+ fs.writeFileSync(path.join(ws, 'managed-fragments-20260102T000000Z-abcdef.json'), OWN);+ });+ // A hard link to a file elsewhere: nothing is written through it.+ const outside = path.join(makeTempDir('declared-bpf-'), 'other.json');+ fs.writeFileSync(outside, OWN);+ await writtenBeside('a hard link', (ws) => fs.linkSync(outside, path.join(ws, 'managed-fragments.json')));+ assert.equal(fs.readFileSync(outside, 'utf8'), OWN);+ // Two downloads into one folder write two files; the first is kept as it was.+ const first = await writtenBeside('a first download', () => {});+ const firstBytes = fs.readFileSync(first.file);+ const second = await download(wire, first.out, flags);+ assert.equal(second.emitted[0].ok, true, JSON.stringify(second.emitted));+ assert.notEqual(second.emitted[0].payload.managedFragments.file, first.file);+ assert.deepEqual(fs.readFileSync(first.file), firstBytes);+ assert.deepEqual(fs.readFileSync(second.emitted[0].payload.managedFragments.file), firstBytes, 'the same app writes the same bytes');+ // <out> given through a junction (a directory symlink off Windows) in a parent folder: the result and the warning name the+ // file under <out> as it was given, and the file lands in the real folder.+ {+ const real = makeTempDir('declared-bpf-');+ const via = path.join(makeTempDir('declared-bpf-'), 'via');+ fs.symlinkSync(real, via, process.platform === 'win32' ? 'junction' : 'dir');+ const given = path.join(via, 'app');+ fs.mkdirSync(path.join(real, 'app'));+ const got = await download(wire, given, flags);+ assert.equal(got.emitted[0].ok, true, JSON.stringify(got.emitted) + got.said);+ const { file } = got.emitted[0].payload.managedFragments;+ assert.equal(path.dirname(file), path.join(given, '.maker-workspace'));+ assert.ok(got.said.includes(`are written ready to paste in ${file}:`), got.said);+ assert.equal(fs.lstatSync(path.join(real, 'app', '.maker-workspace', path.basename(file))).isFile(), true);+ }+ // A junction or a file at .maker-workspace would put the file outside the app folder or where a folder is not: refused, and+ // the app folder is exactly as it was.+ const elsewhere = makeTempDir('declared-bpf-');+ for (const [label, prepare] of [+ ['a junction', (ws) => fs.symlinkSync(elsewhere, ws, 'junction')],+ ['a file', (ws) => fs.writeFileSync(ws, 'maker notes')],+ ]) {+ const out = makeTempDir('declared-bpf-');+ prepare(path.join(out, '.maker-workspace'));+ const before = snapshotTree(out);+ const r = await download(wire, out, flags);+ assert.equal(r.emitted[0].ok, false, label + JSON.stringify(r.emitted));+ assert.equal(r.emitted[0].payload.code, 'managed-fragments-unwritable', label);+ assert.match(r.emitted[0].payload.error, /No other output was written\.$/, label);+ assert.deepEqual(snapshotTree(out), before, `${label}: the app folder is exactly as it was`);+ }+ assert.deepEqual(fs.readdirSync(elsewhere), [], 'nothing is written where the junction points');+ // Without --include-managed nothing is looked at: a plain download writes and refuses exactly as before.+ const plainOut = makeTempDir('declared-bpf-');+ fs.mkdirSync(path.join(plainOut, '.maker-workspace'));+ fs.writeFileSync(path.join(plainOut, '.maker-workspace', 'managed-fragments.json'), 'notes');+ const plain = await download(wire, plainOut, []);+ assert.equal(plain.emitted[0].ok, true, JSON.stringify(plain.emitted));+ assert.equal('managedFragments' in plain.emitted[0].payload, false);+ assert.equal(fs.readFileSync(path.join(plainOut, '.maker-workspace', 'managed-fragments.json'), 'utf8'), 'notes');+ });+});++test('a managed download with nothing to write as fragments writes nothing there and removes nothing', async () => {+ await withBpf(true, async () => {+ const wire = createWorkflowWire();+ const dir = makeTempDir('declared-bpf-');+ assert.equal((await build(wire, dir, specWith([FLOW]))).err, undefined);+ const flags = ['--include-managed', '--managed-manifest', storeFileOf(dir)];+ const OWN = `${JSON.stringify({ kind: 'model-apps.managed-download-fragments', formatVersion: 1, app: APP, items: [] })}\n`;+ for (const [label, prepare] of [+ ['a maker\'s file', (ws) => fs.writeFileSync(path.join(ws, 'managed-fragments.json'), 'maker notes')],+ ['a folder', (ws) => { fs.mkdirSync(path.join(ws, 'managed-fragments.json')); fs.writeFileSync(path.join(ws, 'managed-fragments.json', 'inside.txt'), 'kept'); }],+ ['an earlier download\'s files', (ws) => {+ fs.writeFileSync(path.join(ws, 'managed-fragments.json'), OWN);+ fs.writeFileSync(path.join(ws, 'managed-fragments-20260101T000000Z-abcdef.json'), OWN);+ }],+ ]) {+ const out = makeTempDir('declared-bpf-');+ const ws = path.join(out, '.maker-workspace');+ fs.mkdirSync(ws);+ prepare(ws);+ const before = snapshotTree(ws);+ const got = await download(wire, out, flags);+ assert.equal(got.emitted[0].ok, true, label + JSON.stringify(got.emitted));+ assert.deepEqual(got.emitted[0].payload.managedBpfs, { restored: [GROUP], stale: [] }, label);+ assert.equal('managedFragments' in got.emitted[0].payload, false, label);+ const after = snapshotTree(ws);+ for (const name of Object.keys(before)) assert.equal(after[name], before[name], `${label}: ${name} is as it was`);+ assert.deepEqual(Object.keys(after).filter((n) => n.startsWith('managed-fragments') && !(n in before)), [], `${label}: nothing new`);+ }+ });+});++test('a fragments file that cannot be written leaves every output that was there as it was: the page tree, the spec and the baseline are published only after it', async () => {+ await withBpf(true, async () => {+ const { runDownload } = require('../download-model-app.js');+ const { currentReadSdk } = require('./helpers/app-membership-sdk.js');+ const { fakeGenpage } = require('./helpers/fake-genpage.js');+ // Its own flow, persona and app id, so this test stands without the persona-proof tests (and their constants) above.+ const roled = { ...FLOW, securityRoles: { personas: ['Dispatcher'] } };+ const dispatcher = { persona: 'Dispatcher', jobs: [{ name: 'Triage tickets', privileges: [{ entity: 'new_ticket', access: ['read', 'write'] }] }] };+ const appId = '00000000-0000-0000-0000-00000000a333';+ const wire = createWorkflowWire();+ const dir = makeTempDir('declared-bpf-');+ assert.equal((await build(wire, dir, { ...specWith([roled]), personas: [dispatcher] })).err, undefined);+ const out = makeTempDir('declared-bpf-');+ const pid = '00000000-0000-4000-8000-00000000bbbb';+ const pageFile = path.join(out, 'pages', pid, 'page.tsx');+ fs.mkdirSync(path.dirname(pageFile), { recursive: true });+ fs.writeFileSync(pageFile, 'MAKER EDIT THAT MUST SURVIVE FAILURE');+ const oldSpec = JSON.stringify({ ...specWith([]), pages: [{ key: 'old', name: 'Page', pageId: pid }] });+ fs.writeFileSync(path.join(out, 'app-spec.json'), oldSpec);+ // A file where the fragments folder goes: no new file can be made in it.+ const ws = path.join(out, '.maker-workspace');+ fs.writeFileSync(ws, 'maker notes');+ const xml = `<SiteMap><Area><Group><SubArea GenPageId="${pid}" Title="Page"/><SubArea Entity="new_ticket"/></Group></Area></SiteMap>`;+ const layer = '00000000-0000-4000-8000-00000000cccc';+ const pageSdk = currentReadSdk({+ fetchArtifact: async () => ({ name: 'BP App', uniqueName: APP, siteMap: { areas: [{ title: 'Main', groups: [{ title: 'Records', subAreas: [{ type: 'GenPage', genPageId: pid, title: 'Page' }, { type: 'Entity', entity: 'new_ticket' }] }] }] } }),+ queryRecords: async (logical) => {+ if (logical === 'appmodule') return [{ appmoduleid: appId, appmoduleidunique: layer, uniquename: APP }];+ if (logical === 'appmodulecomponent') return [{ objectid: '00000000-0000-4000-8000-00000000dddd', componenttype: 62 }];+ if (logical === 'sitemap') return [{ sitemapxml: xml }];+ return [];+ },+ fetchEntityMetadata: async (logical) => ({ schemaName: logical, displayName: 'Ticket', primaryNameAttribute: 'new_subject' }),+ }, { appId, layerId: layer, sitemapXml: xml });+ const source = 'export default function Page(){return null;}';+ const genpage = fakeGenpage({ pages: [{ pageId: pid, name: 'Page', source }] });+ let staged;+ const run = () => download(wire, out, ['--include-managed', '--managed-manifest', storeFileOf(dir)], {+ // The real page download, over a page backend; the restore input is the flow this wire built.+ runDownload: async (args) => {+ const real = await runDownload({ ...args, sdk: pageSdk, genpage });+ assert.equal(real.ok, true, JSON.stringify(real));+ staged = args.stagePages;+ return { ...real, spec: specWith([]) };+ },+ });+ const stagingLeft = () => fs.readdirSync(out).filter((n) => n.startsWith('.download-pages.'));+ {+ const before = snapshotTree(out);+ const failed = await run();+ assert.equal(failed.emitted[0].ok, false);+ assert.equal(failed.emitted[0].payload.code, 'managed-fragments-unwritable');+ assert.equal(fs.readFileSync(pageFile, 'utf8'), 'MAKER EDIT THAT MUST SURVIVE FAILURE');+ assert.equal(fs.readFileSync(path.join(out, 'app-spec.json'), 'utf8'), oldSpec);+ assert.match(failed.emitted[0].payload.error, /No other output was written\.$/);+ assert.deepEqual(stagingLeft(), [], 'the staging folder is removed');+ assert.equal(staged, true, 'the managed download stages its pages');+ assert.deepEqual(snapshotTree(out), before, 'no baseline, no fragments, no leftover name: the app folder is exactly as it was');+ }+ fs.unlinkSync(ws);+ // Once the file can be written, the same download publishes everything, the page tree included.+ const done = await run();+ assert.equal(done.emitted[0].ok, true, JSON.stringify(done.emitted) + done.said);+ assert.deepEqual(done.emitted[0].payload.managedFragments.keys, [{ family: 'bpf', key: GROUP }]);+ assert.equal(fs.readFileSync(pageFile, 'utf8'), source);+ assert.notEqual(fs.readFileSync(path.join(out, 'app-spec.json'), 'utf8'), oldSpec);+ assert.deepEqual(stagingLeft(), []);+ });+});+++test('the fragments file is made by an exclusive create under a new name: a name that is taken, even at the last moment, is left as it is and another is used', () => {+ const { settleFragments } = require('../lib/managed-fragments.js');+ const ITEMS = [{ family: 'bpf', key: GROUP }];+ const at = new Date('2026-11-03T17:14:12.667Z');+ const nameOf = (suffix) => `managed-fragments-20261103T171412Z-${suffix}.json`;+ const sequence = (...values) => () => values.shift() || 'ffffff';+ const workspace = () => {+ const out = makeTempDir('declared-bpf-');+ const ws = path.join(out, '.maker-workspace');+ fs.mkdirSync(ws);+ return { out, ws };+ };+ const hooked = (name, hook, fn) => {+ const saved = fs[name];+ fs[name] = function (...args) { return hook(saved, this, args); };+ try { return fn(); } finally { fs[name] = saved; }+ };+ // Nothing due: nothing is made, not even the folder.+ {+ const out = makeTempDir('declared-bpf-');+ assert.equal(settleFragments(out, { app: APP, items: [] }), null);+ assert.deepEqual(fs.readdirSync(out), []);+ }+ // A name that is taken (a maker's file, a folder) is passed over and kept.+ {+ const { out, ws } = workspace();+ fs.writeFileSync(path.join(ws, nameOf('aaaaaa')), 'MAKER NOTES');+ fs.mkdirSync(path.join(ws, nameOf('bbbbbb')));+ const got = settleFragments(out, { app: APP, items: ITEMS, now: () => at, suffix: sequence('aaaaaa', 'bbbbbb', 'cccccc') });+ assert.equal(got.file, path.join(ws, nameOf('cccccc')));+ assert.equal(fs.readFileSync(path.join(ws, nameOf('aaaaaa')), 'utf8'), 'MAKER NOTES');+ assert.deepEqual(fs.readdirSync(path.join(ws, nameOf('bbbbbb'))), []);+ assert.deepEqual(fs.readdirSync(ws).sort(), [nameOf('aaaaaa'), nameOf('bbbbbb'), nameOf('cccccc')]);+ }+ // A file that takes the chosen name after it was chosen, just before the create: kept, and the next name is used.+ {+ const { out, ws } = workspace();+ let raced = 0;+ const got = hooked('openSync', (open, self, args) => {+ if (args[1] === 'wx' && !raced) { raced += 1; fs.writeFileSync(args[0], 'ARRIVED AT THE LAST MOMENT'); }+ return open.apply(self, args);+ }, () => settleFragments(out, { app: APP, items: ITEMS, now: () => at, suffix: sequence('aaaaaa', 'bbbbbb') }));+ assert.equal(raced, 1);+ assert.equal(got.file, path.join(ws, nameOf('bbbbbb')));+ assert.equal(fs.readFileSync(path.join(ws, nameOf('aaaaaa')), 'utf8'), 'ARRIVED AT THE LAST MOMENT');+ }+ // A link at the name, even one pointing nowhere, is not followed: nothing is made where it points.+ {+ const { out, ws } = workspace();+ const target = path.join(makeTempDir('declared-bpf-'), 'not-there.json');+ let linked = true;+ try { fs.symlinkSync(target, path.join(ws, nameOf('aaaaaa')), 'file'); } catch (e) { if (e.code !== 'EPERM') throw e; linked = false; }+ if (linked) {+ const got = settleFragments(out, { app: APP, items: ITEMS, now: () => at, suffix: sequence('aaaaaa', 'bbbbbb') });+ assert.equal(got.file, path.join(ws, nameOf('bbbbbb')));+ assert.equal(fs.existsSync(target), false, 'nothing is made through the link');+ assert.equal(fs.readlinkSync(path.join(ws, nameOf('aaaaaa'))), target);+ }+ }+ // A link put at the chosen name just before the create (it would have to guess the name): on POSIX the create refuses it and+ // the next name is used; on Windows the create follows it, and the download sees that and writes nothing, through it or at all.+ {+ const { out, ws } = workspace();+ const target = path.join(makeTempDir('declared-bpf-'), 'not-there.json');+ const at0 = path.join(ws, nameOf('aaaaaa'));+ let linked = true;+ try { fs.symlinkSync(target, path.join(ws, 'probe'), 'file'); fs.unlinkSync(path.join(ws, 'probe')); } catch (e) { if (e.code !== 'EPERM') throw e; linked = false; }+ if (linked) {+ let got;+ let error;+ try {+ got = hooked('openSync', (open, self, args) => {+ // By name: the create is given the folder's real path, which differs from `ws` when the temp folder holds an 8.3+ // short name (C:\Users\RUNNER~1 on a CI runner).+ if (args[1] === 'wx' && path.basename(args[0]) === nameOf('aaaaaa')) fs.symlinkSync(target, at0, 'file');+ return open.apply(self, args);+ }, () => settleFragments(out, { app: APP, items: ITEMS, now: () => at, suffix: sequence('aaaaaa', 'bbbbbb') }));+ } catch (e) { error = e; }+ assert.equal(fs.readlinkSync(at0), target, 'the link is left as it is');+ if (error) {+ assert.equal(error.code, 'managed-fragments-unwritable');+ assert.match(error.message, /took the name while it was made, so nothing was written to it/);+ assert.equal(fs.readFileSync(target, 'utf8'), '', 'nothing is written through the link');+ assert.deepEqual(fs.readdirSync(ws), [nameOf('aaaaaa')]);+ } else {+ assert.equal(got.file, path.join(ws, nameOf('bbbbbb')));+ assert.equal(fs.existsSync(target), false);+ }+ }+ }+ // Every name tried taken: refused, and nothing is written.+ {+ const { out, ws } = workspace();+ fs.writeFileSync(path.join(ws, nameOf('aaaaaa')), 'MAKER NOTES');+ assert.throws(() => settleFragments(out, { app: APP, items: ITEMS, now: () => at, suffix: () => 'aaaaaa' }),+ (e) => e.code === 'managed-fragments-unwritable' && /every name tried \(8\) was taken/.test(e.message));+ assert.deepEqual(fs.readdirSync(ws), [nameOf('aaaaaa')]);+ assert.equal(fs.readFileSync(path.join(ws, nameOf('aaaaaa')), 'utf8'), 'MAKER NOTES');+ }+ // A write that fails after the create: refused, and the half-written file, its own, is named and left for the maker.+ {+ const { out, ws } = workspace();+ assert.throws(() => hooked('writeFileSync', (write, self, args) => {+ if (typeof args[0] === 'number') throw Object.assign(new Error('no space left on device'), { code: 'ENOSPC' });+ return write.apply(self, args);+ }, () => settleFragments(out, { app: APP, items: ITEMS, now: () => at, suffix: () => 'aaaaaa' })),+ (e) => e.code === 'managed-fragments-unwritable' && e.message.includes(`A partial file was left at ${path.join(ws, nameOf('aaaaaa'))}; delete it.`));+ assert.deepEqual(fs.readdirSync(ws), [nameOf('aaaaaa')]);+ }+ // The path is reported as the caller gave <out>, not as the folder it really is: here <out> reaches its folder through a+ // directory junction (a directory symlink off Windows) in a parent, like an 8.3 short name or a mapped folder would. The file+ // really lands in the target.+ {+ const real = makeTempDir('declared-bpf-');+ const via = path.join(makeTempDir('declared-bpf-'), 'via');+ fs.symlinkSync(real, via, process.platform === 'win32' ? 'junction' : 'dir');+ const given = path.join(via, 'app');+ fs.mkdirSync(path.join(real, 'app'));+ const got = settleFragments(given, { app: APP, items: ITEMS, now: () => at, suffix: () => 'aaaaaa' });+ assert.equal(got.file, path.join(given, '.maker-workspace', nameOf('aaaaaa')));+ assert.equal(fs.lstatSync(path.join(real, 'app', '.maker-workspace', nameOf('aaaaaa'))).isFile(), true, 'it lands in the real folder');+ assert.deepEqual(fs.readdirSync(path.join(real, 'app', '.maker-workspace')), [nameOf('aaaaaa')]);+ }+ // The real clock and random suffix: a UTC time to the second and six hex digits.+ {+ const { out, ws } = workspace();+ const got = settleFragments(out, { app: APP, items: ITEMS });+ assert.equal(path.dirname(got.file), ws);+ assert.match(path.basename(got.file), /^managed-fragments-\d{8}T\d{6}Z-[0-9a-f]{6}\.json$/);+ }+});++test('the fragments file is written in the folder that was checked: a parent junction retargeted after the check, to a folder whose .maker-workspace is a junction elsewhere, does not move the write there', () => {+ const { settleFragments } = require('../lib/managed-fragments.js');+ const linkType = process.platform === 'win32' ? 'junction' : 'dir';+ const name = 'managed-fragments-20261103T182124Z-aaaaaa.json';+ const checked = makeTempDir('declared-bpf-');+ const other = makeTempDir('declared-bpf-');+ const outside = makeTempDir('declared-bpf-');+ const via = path.join(makeTempDir('declared-bpf-'), 'via');+ const checkedWorkspace = path.join(checked, 'app', '.maker-workspace');+ fs.mkdirSync(checkedWorkspace, { recursive: true });+ fs.mkdirSync(path.join(other, 'app'));+ fs.symlinkSync(outside, path.join(other, 'app', '.maker-workspace'), linkType);+ fs.symlinkSync(checked, via, linkType);+ const given = path.join(via, 'app');+ const givenWorkspace = path.join(given, '.maker-workspace');+ // assertSafeOutputDir answers the real path last, after its link checks: retarget `via` right then, once.+ const realpath = fs.realpathSync.native;+ let raced = 0;+ let got;+ let error;+ fs.realpathSync.native = function (file, ...args) {+ const resolved = realpath.call(this, file, ...args);+ if (path.resolve(String(file)) === givenWorkspace && !raced) {+ raced += 1;+ fs.rmSync(via, { recursive: true, force: true });+ fs.symlinkSync(other, via, linkType);+ }+ return resolved;+ };+ try {+ got = settleFragments(given, { app: APP, items: [{ family: 'bpf', key: GROUP }], now: () => new Date('2026-11-03T18:21:24Z'), suffix: () => 'aaaaaa' });+ } catch (e) { error = e; } finally { fs.realpathSync.native = realpath; }+ assert.equal(raced, 1, 'the retarget ran after the check');+ assert.deepEqual(fs.readdirSync(outside), [], 'nothing is written through the junction nobody checked');+ assert.equal(error, undefined);+ assert.deepEqual(fs.readdirSync(checkedWorkspace), [name], 'it lands in the folder that was checked');+ assert.equal(got.file, path.join(givenWorkspace, name), 'and is reported as the caller gave <out>');+});++// Every name under `dir`, with each file's bytes, without following links: what a refusal must leave as it was.+function snapshotTree(dir) {+ const out = {};+ const walk = (d, rel) => {+ for (const name of fs.readdirSync(d).sort()) {+ const full = path.join(d, name);+ const st = fs.lstatSync(full);+ const key = rel ? `${rel}/${name}` : name;+ if (st.isSymbolicLink()) out[key] = `link:${fs.readlinkSync(full)}`;+ else if (st.isDirectory()) { out[key] = 'dir'; walk(full, key); } else out[key] = fs.readFileSync(full, 'base64');+ }+ };+ walk(dir, '');+ return out;+}+// --- the CLI -----------------------------------------------------------------------------------------------------------------test('the enabled feature through the CLI: the printed typed approval binds the flow, verify passes then fails a changed declaration, and the managed download restores it', async () => {diff --git a/plugins/model-apps/scripts/tests/sdk-build-declared-forms.test.js b/plugins/model-apps/scripts/tests/sdk-build-declared-forms.test.jsindex 674b1d7e0..41bb4bbcd 100644--- a/plugins/model-apps/scripts/tests/sdk-build-declared-forms.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build-declared-forms.test.js@@ -819,8 +819,9 @@ test('verify still holds a plain Main form beside a declared one to the default});// download-model-app.js main with its side effects replaced: the download's SDK is a real one over the fake org (it answers the app's-// unique name itself), and runDownload answers the spec a download of this app would hydrate (forms[] empty, as every download).-async function download(org, out, argv, extra = {}) {+// unique name itself), and runDownload answers the spec a download of this app would hydrate (forms[] empty, as every download) and the+// publisher it read (`publisher`: this app's own, verified, unless a test says otherwise).+async function download(org, out, argv, extra = {}, publisher = { prefix: 'contoso', resolved: true }) {const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(newDir()), instanceUrl: org.origin, httpClient: org.httpClient });await sdk.initWorkspace();const dl = Object.create(sdk);@@ -839,7 +840,7 @@ async function download(org, out, argv, extra = {}) {preflightAuth: async () => ({ ok: true }),makeDownloadSdk: async () => ({ sdk: dl, cleanup() {} }),makeGenpageSdk: () => ({}),- runDownload: async () => ({ ok: true, spec: downloaded, pages: [], entities: ['contoso_item'], webResources: [], droppedSubareas: 0, droppedSubareaDetails: [] }),+ runDownload: async () => ({ ok: true, spec: downloaded, pages: [], entities: ['contoso_item'], webResources: [], droppedSubareas: 0, droppedSubareaDetails: [], publisher }),...extra,});const specFile = path.join(out, 'app-spec.json');@@ -847,6 +848,119 @@ async function download(org, out, argv, extra = {}) {}const storeFileOf = (org, dir) => path.join(dir, storeFileName(environmentFingerprint(org.origin), APP, SOLUTION));+// A declared form with an onload handler, and the script library it calls, built together.+const LIBRARY = 'contoso_/scripts/item.js';+const LIBRARY_SOURCE = 'var Item = { onLoad: function () {} };\n';+function handledSpec() {+ const s = makeSpec({ form: { events: [{ event: 'onload', library: LIBRARY, function: 'Item.onLoad' }] } });+ s.webResources = [{ name: LIBRARY, displayName: 'Item script', type: 'js', content: LIBRARY_SOURCE }];+ return s;+}+// The library's row as the build left it, made the unmanaged row a maker's own build leaves (the fake's create keeps no management flag).+function libraryRow(org) {+ const row = [...org.resources.values()].find((r) => r.name === LIBRARY);+ assert.ok(row, 'the build created the library');+ row.ismanaged = false;+ return row;+}+const libraryWrites = (calls) => calls.filter((c) => c.method !== 'GET' && /^\/webresources(?:et)?(?:[?(]|$)/i.test(c.path));++test('the explicit managed download restores a proved form with its handler library, declared external, and a rebuild from it writes no library where it exists', async () => {+ await withForms(true, async () => {+ const org = createFakeBuildOrg({ entities: ENTITIES });+ const dir = newDir();+ const built = handledSpec();+ assert.equal((await build(org, dir, built, { phases: ['web-resources', 'forms'] })).err, undefined);+ const row = libraryRow(org);+ const out = newDir();+ const r = await download(org, out, ['--include-managed', '--managed-manifest', storeFileOf(org, dir)]);+ assert.equal(r.emitted[0].ok, true, JSON.stringify(r.emitted) + r.said);+ assert.deepEqual(r.emitted[0].payload.managedForms, { restored: [KEY], stale: [], libraries: [{ name: LIBRARY, forms: [KEY] }] });+ assert.equal('managedFragments' in r.emitted[0].payload, false);+ assert.deepEqual((fs.existsSync(path.join(out, '.maker-workspace')) ? fs.readdirSync(path.join(out, '.maker-workspace')) : []).filter((n) => n.startsWith('managed-fragments')), []);+ assert.deepEqual(r.written.forms, built.forms, 'the declaration it was built from');+ assert.deepEqual(r.written.webResources, [{ name: LIBRARY, displayName: 'Item script', type: 'js', contentBase64: row.publishedContent, external: true }]);+ assert.equal(Buffer.from(row.publishedContent, 'base64').toString('utf8'), LIBRARY_SOURCE);+ assert.match(r.said, new RegExp(`NOTE: handler library '${LIBRARY}' of managed form ${KEY} was downloaded into webResources\\[\\] as external`));+ assert.deepEqual(libraryWrites(r.calls), [], 'the download writes nothing');+ assert.equal(r.calls.filter((c) => /^\/webresources(?:et)?\?/i.test(c.path)).length, 1, 'the library is read once');+ // The spec as written rebuilds where it was downloaded from: the library is reused as it is (external: its content is neither written+ // nor compared) and the form binds it.+ const again = await build(org, dir, r.written, { phases: ['web-resources', 'forms'] });+ assert.equal(again.err, undefined, chainText(again.err));+ assert.deepEqual(libraryWrites(again.calls), []);+ // Where it is missing, a build creates it from the downloaded content.+ const fresh = createFakeBuildOrg({ entities: ENTITIES });+ assert.equal((await build(fresh, newDir(), { ...r.written, forms: [] }, { phases: ['web-resources'] })).err, undefined);+ const made = [...fresh.resources.values()].find((x) => x.name === LIBRARY);+ assert.equal(made && made.content, row.publishedContent);+ });+});++test('the explicit managed download refuses a handler library it cannot prove is this publisher\'s own unmanaged script, and writes that form ready to paste', async () => {+ await withForms(true, async () => {+ const org = createFakeBuildOrg({ entities: ENTITIES });+ const dir = newDir();+ const built = handledSpec();+ assert.equal((await build(org, dir, built, { phases: ['web-resources', 'forms'] })).err, undefined);+ const row = libraryRow(org);+ const kept = { ...row };+ const flags = ['--include-managed', '--managed-manifest', storeFileOf(org, dir)];+ const byName = (c) => c.method === 'GET' && /^\/webresources(?:et)?\?/i.test(c.path);+ const cases = [+ ['managed', () => { row.ismanaged = true; }, /it is managed$/],+ ['management unknown', () => { delete row.ismanaged; }, /whether it is managed is not known$/],+ ['not a script', () => { row.webresourcetype = 1; }, /it is not a script$/],+ ['no content', () => { row.publishedContent = ''; }, /it has no content$/],+ ['another prefix', () => ({ prefix: 'fabrikam', resolved: true }), /its name does not carry this publisher's prefix 'fabrikam_'$/],+ ['unverified prefix', () => ({ prefix: 'contoso', resolved: false }), /publisher prefix was not verified/],+ ['no publisher', () => null, /publisher prefix was not verified/],+ ['not found', () => org.intercept(byName, () => ({ status: 200, headers: {}, body: { value: [] } })), /it was not found$/],+ ['two rows', () => org.intercept(byName, () => ({ status: 200, headers: {}, body: { value: [{ ...kept, content: kept.publishedContent }, { ...kept, content: kept.publishedContent }] } })), /more than one web resource answers its name$/],+ // One matching row on a page the server says continues is not one row: the lookup reads `top: 2`, so a next link means+ // more rows answer the name than were read.+ ['cut short', () => org.intercept(byName, () => ({ status: 200, headers: {}, body: { value: [{ ...kept, content: kept.publishedContent }], '@odata.nextLink': `${org.origin}/api/data/v9.2/webresourceset?page=2` } })), /its lookup was cut short, so it is not known to be the only web resource of its name$/],+ ['read refused', () => org.intercept(byName, () => ({ status: 403, headers: {}, body: { error: { code: '0x80040220', message: 'no read privilege' } } })), /it could not be read \(.*\)$/],+ ];+ for (const [label, arrange, why] of cases) {+ Object.keys(row).forEach((k) => delete row[k]);+ Object.assign(row, kept);+ const arranged = arrange();+ const publisher = arranged === null ? null : arranged && arranged.prefix ? arranged : { prefix: 'contoso', resolved: true };+ const out = newDir();+ const r = await download(org, out, flags, {}, publisher);+ if (typeof arranged === 'function') arranged();+ assert.equal(r.emitted[0].ok, true, label);+ const { managedForms } = r.emitted[0].payload;+ assert.deepEqual(managedForms.restored, [], label);+ assert.equal('libraries' in managedForms, false, label);+ assert.match(managedForms.stale[0].reason, new RegExp(`^its onload handler library '${LIBRARY}' was not downloaded: `), label);+ assert.match(managedForms.stale[0].reason, why, label);+ assert.deepEqual(r.written.forms, [], label);+ assert.equal(r.written.webResources, undefined, label);+ const { file } = r.emitted[0].payload.managedFragments;+ assert.equal(path.dirname(file), path.join(out, '.maker-workspace'), label);+ assert.match(path.basename(file), /^managed-fragments-\d{8}T\d{6}Z-[0-9a-f]{6}\.json$/, label);+ assert.deepEqual(r.emitted[0].payload.managedFragments, { file, keys: [{ family: 'form', key: KEY }] }, label);+ const fragments = JSON.parse(fs.readFileSync(file, 'utf8'));+ assert.deepEqual(fragments.items, [{ family: 'form', key: KEY, reason: managedForms.stale[0].reason, needs: [{ webResource: LIBRARY }], paste: { forms: built.forms } }], label);+ // Pasted with the library it needs, the downloaded spec validates.+ const pasted = { ...r.written, webResources: [built.webResources[0]], forms: fragments.items[0].paste.forms };+ assert.equal(validateAppSpec(pasted, { profile: 'plan', reconstructed: true }).ok, true, label);+ }+ Object.keys(row).forEach((k) => delete row[k]);+ Object.assign(row, kept);+ // A form left out for anything else gets no fragment: nothing proved it.+ const refusing = await download(org, newDir(), flags, {+ validateAppSpec: (s, o) => ((s.forms || []).length ? { ok: false, errors: ['forms: not in this download'], warnings: [] } : validateAppSpec(s, o)),+ });+ assert.equal(refusing.emitted[0].ok, true);+ assert.match(refusing.emitted[0].payload.managedForms.stale[0].reason, /does not validate in the downloaded spec/);+ assert.equal('managedFragments' in refusing.emitted[0].payload, false);+ assert.equal(refusing.written.webResources, undefined, 'a library is committed only with its form');+ });+});+test('the explicit managed download restores a proved declared form from the named binding store, and names any it cannot restore', async () => {await withForms(true, async () => {const org = createFakeBuildOrg({ entities: ENTITIES });diff --git a/plugins/model-apps/scripts/tests/sdk-build-declared-rules.test.js b/plugins/model-apps/scripts/tests/sdk-build-declared-rules.test.jsindex e16820e65..12032c4c4 100644--- a/plugins/model-apps/scripts/tests/sdk-build-declared-rules.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build-declared-rules.test.js@@ -211,6 +211,54 @@ test('a declared rule is created Draft under its catalog id, proved, then activa});});+// #796, as for a declared process flow (sdk-build-declared-bpf.test.js): through the whole CLI assembly, its attempt told the table was created by+// this invocation, a lag on the rule's identity read is read again in place within the build's one retry allowance, and once that is spent the+// build stops with the service's own answer in the words the CLI prints (dataverse-auth.js emitResult: redactOutput(err.message)).+test('a declared rule\'s identity read on a table this invocation created is read again in place; past the build\'s retries the printed stop quotes the service\'s answer (#796)', async () => {+ const { redactOutput } = require('../lib/output-redaction.js');+ const MESSAGE = "The entity with a name = 'new_ticket' with namemapping = 'Logical' was not found in the MetadataCache.LazyDynamicMetadataCache with version 1 and timestamp 1";+ const nameRead = (e) => e.method === 'GET' && e.path === 'workflows';+ await withRules(true, async () => {+ const cli = async (lags) => {+ const wire = createWorkflowWire();+ for (let i = 0; i < lags; i += 1) wire.script(nameRead, { statusCode: 400, body: { error: { code: '0x80041102', message: MESSAGE } } });+ const appDir = makeTempDir('declared-rule-');+ const dir = path.join(appDir, '.maker-workspace');+ fs.mkdirSync(dir);+ const barrier = createPublicationBarrier();+ const sendObserver = createAttemptSendObserver();+ const workflowEffectGate = createDeferredWorkflowGate();+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: ORIGIN, httpClient: clientOver(wire, { barrier, observer: sendObserver, workflowEffectGate }) });+ await sdk.initWorkspace();+ const events = [];+ let attempts = 0;+ let err;+ try {+ await buildModelApp(specWith([RULE]), { apply: true, env: ORIGIN, workspaceDir: dir, appDir, retryDelayMs: 0 }, {+ sdk, provisionSdk: sdk, publicationBarrier: barrier, sendObserver, workflowEffectGate, warn: () => {}, log: () => {},+ journal: { path: 'x', record: (e) => events.push(e), close: () => {} },+ runBuild: (s, o) => { attempts += 1; o.createdTables.add('new_ticket'); return runSdkBuild(s, { ...o, phases: ['business-rules'] }); },+ });+ } catch (e) { err = e; }+ return { err, attempts, retries: events.filter((e) => e.status === 'retry').length, workflowWrites: wire.log.filter((c) => c.method !== 'GET' && /^workflows/i.test(c.path)) };+ };+ const recovered = await cli(2);+ assert.equal(recovered.err, undefined, chainText(recovered.err));+ assert.equal(recovered.attempts, 1, 'one attempt: the read was made again where it failed');+ assert.equal(recovered.retries, 2);+ assert.equal(recovered.workflowWrites.filter((c) => /CreateProcessWithWfomJson/.test(c.path)).length, 1, 'created once');+ const spent = await cli(4);+ assert.ok(spent.err, 'the lag outlasts the three retries');+ assert.equal(spent.attempts, 1);+ assert.equal(spent.retries, 3);+ assert.deepEqual(spent.workflowWrites, [], 'nothing is sent for the rule');+ const printed = redactOutput(spent.err.message);+ assert.match(printed, /HTTP 400/, printed);+ assert.ok(printed.includes('0x80041102'), printed);+ assert.ok(printed.includes(MESSAGE), printed);+ });+});+test('a declared rule found unbound halts through the build halt with the typed adoption it needs; nothing is written until it is given', async () => {await withRules(true, async () => {const wire = createWorkflowWire();diff --git a/plugins/model-apps/scripts/tests/sdk-build.test.js b/plugins/model-apps/scripts/tests/sdk-build.test.jsindex 8c08ed4df..bc611e503 100644--- a/plugins/model-apps/scripts/tests/sdk-build.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build.test.js@@ -3638,6 +3638,24 @@ test('resolveExistingFormId treats a "not found in the MetadataCache" 400 (brandassert.strictEqual(await resolveExistingFormId(provision, { entityLogicalName: 'ftx_widget', name: 'Information', formType: 'Main' }), null);});+test('resolveExistingFormId (#796): the same answer is also the lag of a table created moments ago, so a caller that would create on a miss gets the failure back', async () => {+ // Live, a table that exists answered the form lookup with+ // HTTP 400 {"error":{"code":"0x80041102","message":"The entity with a name = 'contoso_ticket' with namemapping = 'Logical' was not found in the MetadataCache.LazyDynamicMetadataCache with version 9495075 and timestamp 9495075"}}+ // and the build read that as "no form" and created a second form of the same name.+ const lag = () => Object.assign(new Error("The entity with a name = 'contoso_ticket' with namemapping = 'Logical' was not found in the MetadataCache.LazyDynamicMetadataCache"), { statusCode: 400, code: '0x80041102' });+ const def = { entityLogicalName: 'contoso_ticket', name: 'Information', formType: 'Main' };+ const lagging = { queryRecords: async () => { throw lag(); } };+ await assert.rejects(() => resolveExistingFormId(lagging, def, { tableNotInCache: 'fail' }), /not found in the MetadataCache/);+ const proofs = [];+ await assert.rejects(() => resolveExistingFormId(lagging, def, { tableNotInCache: async (err) => { proofs.push(err.code); return false; } }), /not found in the MetadataCache/, 'the table is not proved absent');+ assert.strictEqual(await resolveExistingFormId(lagging, def, { tableNotInCache: async (err) => { proofs.push(err.code); return true; } }), null, 'the table is proved absent');+ assert.deepStrictEqual(proofs, ['0x80041102', '0x80041102']);+ assert.strictEqual(await resolveExistingFormId(lagging, def), null, 'a read-only caller keeps "not found"');+ // A successful read with no row is "not found" for every caller, and any other failure stays a failure.+ assert.strictEqual(await resolveExistingFormId({ queryRecords: async () => [] }, def, { tableNotInCache: 'fail' }), null);+ await assert.rejects(() => resolveExistingFormId({ queryRecords: async () => { throw Object.assign(new Error('503 Service Unavailable'), { statusCode: 503 }); } }, def, { tableNotInCache: async () => true }), /503/);+});+test('resolveExistingFormId RE-THROWS a non-metadata error (a transient failure must still fail closed)', async () => {const provision = { queryRecords: async () => { const e = new Error('429 Too Many Requests'); e.statusCode = 429; throw e; } };await assert.rejects(diff --git a/plugins/model-apps/scripts/tests/sdk-teardown.test.js b/plugins/model-apps/scripts/tests/sdk-teardown.test.jsindex e27b7592e..c8495e4d3 100644--- a/plugins/model-apps/scripts/tests/sdk-teardown.test.js+++ b/plugins/model-apps/scripts/tests/sdk-teardown.test.js@@ -3314,3 +3314,196 @@ test('#587 a non-GUID role id still resolves — the GUID test is an injection gassert.deepStrictEqual(await KIND_HANDLERS.role.resolve(sdk, { name: 'Dispatcher' }),[{ id: 'r1', name: 'Dispatcher' }]);});++// The only active Main form of a table the build created: the platform refuses the explicit form delete (HTTP 400, "You must have at least one active+// Main form"), and the table's own delete, a few steps later, removes the form with it. The refusal alone used to fail the run and keep the solution, so a+// second run was needed. Now the refusal waits for the tables step, and stands as a failure unless this run deleted the form's table AND a fresh read of+// the form's exact id shows it gone.+const MAIN_FORM_ID = 'f33a200d-0a76-4c52-b1d2-4d0a7c230991';+const LAST_MAIN_FORM_MESSAGE = 'This operation can’t be completed. You must have at least one active Main form.';+// FallbackFormDeactivation, https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/web-service-error-codes — the code alone names the refusal.+const LAST_MAIN_FORM_CODE = '0x8004F661';+const lastMainFormAnswer = (over = {}) => serviceAnswer(400, { code: LAST_MAIN_FORM_CODE, message: LAST_MAIN_FORM_MESSAGE, ...over });+const mainFormSpec = (entityOver = {}) => ({+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ entities: [{ schemaName: 'new_ticket', primaryAttribute: { schemaName: 'new_name' }, ...entityOver }],+ forms: [{ entity: 'new_ticket', name: 'Information', formType: 'Main' }],+});+// `refuse` is what the form delete answers; `read` is how the form's exact id answers after the run's table delete: 'gone' (404 with the missing-row+// code, in both layers), 'present' (the row), 'unreadable' (HTTP 500), or 'throws'. `tableDelete: 'fails'` makes the table's delete answer HTTP 500.+function mainFormWorld({ refuse = lastMainFormAnswer(), read = 'gone', tableDelete = 'works', extraForms = {} } = {}) {+ const sdk = mockSdk({+ solutions: { S: { solutionid: 'sol-1', uniquename: 'S' } },+ tables: ['new_ticket'],+ forms: { 'new_ticket:Information': { formid: MAIN_FORM_ID, name: 'Information' }, ...extraForms },+ });+ const realDeleteTable = sdk.deleteTable;+ sdk.deleteTable = async (logical) => {+ if (tableDelete === 'fails') { sdk.calls.push({ method: 'deleteTable', logical }); throw serviceAnswer(500, { message: 'Service Unavailable' }); }+ try { return await realDeleteTable(logical); } finally {+ // The table takes its forms with it, except when the run is set up to read the row as still there.+ if (read !== 'present') for (const key of Object.keys(sdk.db.forms)) if (key.startsWith(`${logical}:`)) delete sdk.db.forms[key];+ }+ };+ const realDelete = sdk.deleteRemoteArtifact;+ sdk.deleteRemoteArtifact = async (type, id) => {+ if (type === 'form' && refuse) { sdk.calls.push({ method: 'deleteRemoteArtifact', type, id }); throw refuse; }+ return realDelete(type, id);+ };+ sdk.formReads = [];+ sdk.dataverse = {+ async get(url) {+ sdk.formReads.push(url);+ if (read === 'throws') throw new Error('socket hang up');+ if (read === 'unreadable') return { status: 500, headers: {}, body: { error: { code: '0x80044150', message: 'Service Unavailable' } } };+ if (read === 'present') return { status: 200, headers: {}, body: { formid: MAIN_FORM_ID, name: 'Information', description: null, formxml: '<form />' } };+ return { status: 404, headers: {}, body: { error: { code: '0x80040217', message: `systemform With Id = ${MAIN_FORM_ID} Does Not Exist` } } };+ },+ };+ return sdk;+}+async function runMainFormTeardown(sdk, spec = mainFormSpec()) {+ const events = [];+ const counts = { ok: 0, skip: 0, error: 0 };+ const lines = [];+ const logEmit = require(path.join(__dirname, '..', 'teardown-model-app.js')).cliEmit((line) => lines.push(line), { apply: true, counts });+ const res = await runTeardown(spec, { apply: true }, { sdk, emit: (e) => { events.push(e); logEmit(e); } });+ return { res, events, counts, lines };+}+const solutionLeft = (sdk) => Object.keys(sdk.db.solutions);++test('the refusal of a table\'s only Main form is settled by the table delete: one run deletes the solution, reports the form removed with its table, and succeeds', async () => {+ const sdk = mainFormWorld();+ const { res, events, counts, lines } = await runMainFormTeardown(sdk);+ assert.strictEqual(res.ok, true, JSON.stringify(res.errors));+ assert.deepStrictEqual(res.errors, []);+ assert.deepStrictEqual(res.deleted.form, [MAIN_FORM_ID]);+ assert.deepStrictEqual(res.deleted.table, ['new_ticket']);+ assert.deepStrictEqual(solutionLeft(sdk), [], 'the solution is deleted in the same run');+ assert.deepStrictEqual(sdk.calls.filter((c) => /^delete/.test(c.method)).map((c) => `${c.method} ${c.type || c.logical || ''}`.trim()),+ ['deleteRemoteArtifact form', 'deleteTable new_ticket', 'deleteSolution'], 'the form delete is still sent first, and sent once');+ assert.strictEqual(events.filter((e) => e.status === 'error').length, 0, 'no failure is reported, not even for a moment');+ assert.deepStrictEqual(events.filter((e) => e.label && e.label.startsWith('form ')).map((e) => [e.status, e.label]),+ [['start', 'form "Information" (new_ticket)'], ['ok', 'form "Information" (new_ticket) (1 deleted — removed with its table new_ticket)']]);+ assert.deepStrictEqual(counts, { ok: 3, skip: 0, error: 0 }, 'form, table and solution are all deleted: the closing summary reads 3 deleted, 0 failed');+ assert.ok(lines.some((l) => l.includes('✓') && l.includes('form "Information"')), lines.join('\n'));+ assert.deepStrictEqual(sdk.formReads.length, 2, 'the exact id is read once per layer');+ assert.ok(sdk.formReads.every((u) => u.includes(`/systemforms(${MAIN_FORM_ID})`)));+});++test('the same refusal does not settle when the form\'s table is retained: the failure stands, nothing is sent to the form\'s id again, and the solution is kept', async () => {+ const sdk = mainFormWorld();+ const { res, counts } = await runMainFormTeardown(sdk, mainFormSpec({ existing: true }));+ assert.strictEqual(res.ok, false);+ assert.strictEqual(res.errors.length, 1);+ assert.match(res.errors[0].message, /You must have at least one active Main form/);+ assert.strictEqual(res.deleted.form, undefined);+ assert.strictEqual(sdk.calls.filter((c) => c.method === 'deleteTable').length, 0);+ assert.deepStrictEqual(sdk.formReads, [], 'no table was deleted, so there is nothing to confirm');+ assert.deepStrictEqual(solutionLeft(sdk), ['S']);+ assert.strictEqual(counts.error, 1);+});++test('the refusal stands when the table delete failed: the form is not read, the table and the solution are kept', async () => {+ const sdk = mainFormWorld({ tableDelete: 'fails' });+ const { res } = await runMainFormTeardown(sdk);+ assert.strictEqual(res.ok, false);+ assert.deepStrictEqual(res.errors.map((e) => e.step), ['form "Information" (new_ticket)', 'table new_ticket']);+ assert.deepStrictEqual(sdk.formReads, []);+ assert.deepStrictEqual(solutionLeft(sdk), ['S']);+});++for (const [read, what] of [['present', 'still there (200)'], ['unreadable', 'unreadable (HTTP 500)'], ['throws', 'unreadable (the read throws)']]) {+ test(`the refusal stands when the table was deleted but the form's exact id is ${what}: exit 1 and the solution is kept`, async () => {+ const sdk = mainFormWorld({ read });+ const { res, events, counts } = await runMainFormTeardown(sdk);+ assert.strictEqual(res.ok, false);+ assert.strictEqual(res.errors.length, 1);+ assert.strictEqual(res.errors[0].step, 'form "Information" (new_ticket)');+ assert.match(res.errors[0].message, /HTTP 400 from .*You must have at least one active Main form/);+ assert.strictEqual(res.deleted.form, undefined, 'not counted as removed');+ assert.deepStrictEqual(res.deleted.table, ['new_ticket']);+ assert.deepStrictEqual(solutionLeft(sdk), ['S']);+ const formEvents = events.filter((e) => e.label === 'form "Information" (new_ticket)').map((e) => e.status);+ assert.deepStrictEqual(formEvents, ['start', 'error']);+ assert.strictEqual(counts.error, 1);+ });+}++test('a form is read as gone only when BOTH layers answer the missing-row 404: a published 404 beside a saved row stands as a failure', async () => {+ const sdk = mainFormWorld();+ sdk.dataverse.get = async (url) => (/RetrieveUnpublished/.test(url)+ ? { status: 200, headers: {}, body: { formid: MAIN_FORM_ID, name: 'Information', description: null, formxml: '<form />' } }+ : { status: 404, headers: {}, body: { error: { code: '0x80040217', message: 'Does Not Exist' } } });+ const { res } = await runMainFormTeardown(sdk);+ assert.strictEqual(res.ok, false);+ assert.deepStrictEqual(solutionLeft(sdk), ['S']);+});++test('the refusal is recognised by its code alone: a localized message, or the code in another case, settles with the table', async () => {+ for (const refuse of [+ lastMainFormAnswer({ message: 'Diese Operation kann nicht abgeschlossen werden. Es muss mindestens ein aktives Hauptformular vorhanden sein.' }),+ lastMainFormAnswer({ code: LAST_MAIN_FORM_CODE.toLowerCase(), message: 'Something else entirely' }),+ ]) {+ const sdk = mainFormWorld({ refuse });+ const { res, counts } = await runMainFormTeardown(sdk);+ assert.strictEqual(res.ok, true, JSON.stringify(res.errors));+ assert.deepStrictEqual(res.deleted.form, [MAIN_FORM_ID]);+ assert.deepStrictEqual(solutionLeft(sdk), []);+ assert.deepStrictEqual(counts, { ok: 3, skip: 0, error: 0 });+ }+});++for (const [name, answer] of [+ ['another HTTP 400 of a form delete', () => serviceAnswer(400, { message: 'The form is referenced by 1 other component.' })],+ ['the same code and words under another status', () => serviceAnswer(403, { code: LAST_MAIN_FORM_CODE, message: LAST_MAIN_FORM_MESSAGE })],+ ['an error that is no answer of the platform', () => new Error(`You must have at least one active Main form`)],+ ['an unrelated coded HTTP 400 that quotes the words', () => serviceAnswer(400, { code: '0x80040265', message: 'Delete blocked by validation rule "You must have at least one active Main form": approval is required.' })],+ ['the right message with no code', () => serviceAnswer(400, { message: LAST_MAIN_FORM_MESSAGE })],+ ['the right message with an empty code', () => serviceAnswer(400, { code: '', message: LAST_MAIN_FORM_MESSAGE })],+ ['the related FallbackFormDeletion code (0x8004F654)', () => serviceAnswer(400, { code: '0x8004F654', message: LAST_MAIN_FORM_MESSAGE })],+]) {+ test(`${name} stays a failure exactly as before: reported at once, never read back, solution kept`, async () => {+ const sdk = mainFormWorld({ refuse: answer() });+ const { res, events } = await runMainFormTeardown(sdk);+ assert.strictEqual(res.ok, false);+ assert.strictEqual(res.errors.length, 1);+ assert.strictEqual(res.errors[0].message, answer().message, 'the original error is kept');+ assert.deepStrictEqual(sdk.formReads, []);+ assert.deepStrictEqual(solutionLeft(sdk), ['S']);+ const formEvents = events.filter((e) => e.label === 'form "Information" (new_ticket)');+ assert.deepStrictEqual(formEvents.map((e) => e.status), ['start', 'error']);+ assert.deepStrictEqual(res.deleted.table, ['new_ticket'], 'the table step still runs, as before');+ });+}++test('a table with several Main forms is unchanged: every form is deleted explicitly, nothing is read back, and the request order is the old one', async () => {+ const second = '0a0b0c0d-0000-4000-8000-000000000002';+ const sdk = mainFormWorld({ refuse: null, extraForms: { 'new_ticket:Second': { formid: second, name: 'Second' } } });+ const spec = mainFormSpec();+ spec.forms.push({ entity: 'new_ticket', name: 'Second', formType: 'Main' });+ const { res, events } = await runMainFormTeardown(sdk, spec);+ assert.strictEqual(res.ok, true, JSON.stringify(res.errors));+ assert.deepStrictEqual(res.deleted.form, [MAIN_FORM_ID, second]);+ assert.deepStrictEqual(sdk.formReads, []);+ assert.deepStrictEqual(sdk.calls.filter((c) => /^delete/.test(c.method)).map((c) => `${c.method} ${c.id || c.logical || ''}`.trim()),+ [`deleteRemoteArtifact ${MAIN_FORM_ID}`, `deleteRemoteArtifact ${second}`, 'deleteTable new_ticket', 'deleteSolution sol-1']);+ assert.ok(events.filter((e) => e.status === 'ok').every((e) => !/removed with its table/.test(e.label)));+});++test('a refused last Main form of one table settles with its table while another form of the run fails for its own reason', async () => {+ const other = '0a0b0c0d-0000-4000-8000-000000000003';+ const sdk = mainFormWorld({ extraForms: { 'new_ticket:Quick': { formid: other, name: 'Quick' } } });+ const realDelete = sdk.deleteRemoteArtifact;+ sdk.deleteRemoteArtifact = async (type, id) => {+ if (type === 'form' && id === other) { sdk.calls.push({ method: 'deleteRemoteArtifact', type, id }); throw serviceAnswer(400, { message: 'The form is referenced by 1 other component.' }); }+ return realDelete(type, id);+ };+ const spec = mainFormSpec();+ spec.forms.push({ entity: 'new_ticket', name: 'Quick', formType: 'Main' });+ const { res } = await runMainFormTeardown(sdk, spec);+ assert.strictEqual(res.ok, false, 'the other form\'s failure is not cleared by the first form\'s settlement');+ assert.deepStrictEqual(res.errors.map((e) => e.step), ['form "Quick" (new_ticket)']);+ assert.deepStrictEqual(res.deleted.form, [MAIN_FORM_ID]);+ assert.deepStrictEqual(solutionLeft(sdk), ['S']);+});diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex 025a10ae9..f7fcb798a 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -94,7 +94,8 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfaces**Wave 2 header/navigation refresh** — a *separate, independent* setting whose platform default is**ON**, so set it to `false` only when the user explicitly wants the classic header.- **App theme and header logo (Preview, 2.21.0)** — `app.theme`. Add it **only when the maker explicitly asks- for branding** (brand colours, a header colour, a logo); an ordinary app gets **no** `app.theme`, and you never+ for branding** (brand colours, a header colour, a logo) or says yes to the branding question you ask of every new app+ at the personas step (authoring-flow Level (a0)); an ordinary app gets **no** `app.theme` without one of those, and you neverinvent a palette, a font or a logo. Offer the choices: a `basePaletteColor` (or explicit `palette` slots), the`appHeader` colours, a `font` only if they name one, and a `logo` that is an **existing image web resource**(or one you also declare in `webResources[]`), never a URL. Say before the build that the theme is published@@ -156,7 +157,7 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfacesin this version). Leave a downloaded or older spec without these fields as it is — see the advanced reference.- **Declared form layouts** (`minimumPluginVersion: "2.21.0"`) — write `reconcile: "declared"` on a formonly when the maker asked its layout to follow the spec (fields, spans, sections, field options, sub-grids,- handlers); not for "add a form" or "add a field" with no layout. Tell the maker: controls the spec does not+ handlers) or said yes when you offered it at Level (b); not for "add a form" or "add a field" with no layout. Tell the maker: controls the spec does notdeclare stay where they are and nothing is deleted (so no `--allow-destructive` is needed for them); a layout the build cannot place safely stops before anywrite; a table publish puts live every saved change on that table, not only this form, with or without`--publish` (a declared dashboard is published after its write either way); and Dataverse does@@ -167,8 +168,10 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfaces`overwrite:form:` for changes made elsewhere): explain it and let the maker choose. `--verify` checks adeclared form against the spec, sub-grid views included (a form whose publish is unconfirmed is unverified,not passed). A download brings declared forms back only with `--include-managed --managed-manifest <store- file>` (one with an event handler is left out and named in `managedForms.stale`, as its handler's web- resource is not downloaded: add both back by hand); it carries no binding, so the first build that binds each form from the downloaded folder needs+ file>` (one with an event handler comes back with its handler library as an `external` web resource when+ that library is this publisher's own unmanaged script; otherwise it is left out and named in+ `managedForms.stale`, and its declaration is written ready to paste in the new file `managedFragments.file` names (`.maker-workspace/managed-fragments-<time>-<random>.json`)+ with the library it needs, so tell the maker to add both from the spec it was built from); it carries no binding, so the first build that binds each form from the downloaded folder needs`adopt:form:<key>` (a rebuild that writes nothing may leave it unbound). A form removed from the spec andthen deleted in Maker is released by the next build, which names it (`managed-root-retired`); until then`--verify` fails it. One whose publish is unconfirmed is not released (see the unconfirmed publish below). A@@ -179,7 +182,7 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfacesunconfirmed publish) is refused (`managed-form-unsettled`):restore the declaration and let it settle, or run the build again later.- **Declared dashboards** (`minimumPluginVersion: "2.21.0"`) — write `reconcile: "declared"` on a global- dashboard only when the maker asked its tiles to follow the spec on rebuilds; give it and every tile a+ dashboard only when the maker asked its tiles to follow the spec on rebuilds, or said yes when you offered it at Level (b); give it and every tile a`key`. Tell the maker: tiles the spec omits stay (nothing is deleted), and settings a tile does not state arekept; a new tile is added after the last row; in an environment with more than one language a new tile getsits caption, with the same text, in every language the environment has (if the build cannot read those@@ -202,7 +205,7 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfacesdashboard and tile ids it was proved on; its first binding needs `adopt:dashboard:<key>`, because thedownloaded folder has no store.- **Declared business rules** (`minimumPluginVersion: "2.21.0"`) — write `reconcile: "declared"` on a rule only- when the maker accepts that the build manages the WHOLE rule; give every condition, action and apply-action a+ when the maker accepts that the build manages the WHOLE rule (the offer at the personas step, or their own ask); give every condition, action and apply-action a`key`. Tell the maker: conditions and actions are never matched by their text; a new rule is created Draft andactivated only if nobody changed it in between; a rule that already exists is never edited by the build(change it in Maker, then re-adopt it); a rule changed outside the spec stops the build until it is re-adopted@@ -213,7 +216,7 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfacesout, as every business rule is); the first build that binds a rule that already exists needs`adopt:rule:<table>/<name>`, because the downloaded folder has no store.- **Declared business process flows** (`minimumPluginVersion: "2.21.0"`) — write- `reconcile: "declared"` on a flow only when the maker accepts that the build manages the WHOLE flow; give every+ `reconcile: "declared"` on a flow only when the maker accepts that the build manages the WHOLE flow (the offer at the personas step, or their own ask); give everystage and step a `key`. Tell the maker: a key keeps a stage's or step's id, so a rename keeps the records on it;a new flow is created Draft and activated only if nobody changed it in between; a flow that already exists isnever edited by the build (to change its body or status, change it in Maker, then re-adopt it, keeping every@@ -224,10 +227,16 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfacesit is re-adopted). A download brings it back declared, keys included, only with `--include-managed--managed-manifest <store file>` (otherwise it is left out); the first build that binds it from the downloaded folderneeds `adopt:bpf:<table>/<name>`, because that folder has no store. Changing only who may run a managed flow- (`securityRoles`) writes nothing to the flow; the build records it. A managed download does NOT restore a flow- that has `securityRoles`: a download writes no `personas[]`, so it leaves that flow out with a warning naming the- personas (nothing is lost; the store and the maker's own spec keep it). Tell the maker to copy that flow and the- personas it names from the spec it was built from. A+ (`securityRoles`) writes nothing to the flow; the build records it. A managed download restores a flow that has+ `securityRoles` only when it can prove each persona the flow names from the role a build made for it, and then+ writes that persona into `personas[]` (a NOTE names it). Tell the maker that persona now owns its role: a+ privilege added to that role outside the spec is removed by the next build. When a persona cannot be proved,+ the download leaves the flow out with a warning naming the personas and why (nothing is lost; the store and the+ maker's own spec keep it) and writes the flow ready to paste in+ the new file `managedFragments.file` names. Tell the maker to paste that flow and copy the+ personas it names from the spec it was built from. Earlier fragments files are kept; never delete one+ yourself. If the download stops with `managed-fragments-unwritable`, `.maker-workspace` is not a plain folder+ or cannot be written: ask the maker to fix it, never move or delete it yourself. Adeclared rule or flow removed from the spec whose row was deleted is no longer managed once the build reads it goneby its id (a `managed-root-retired` warning, which never means it was activated); until then, a removed one whosechange is still waiting to be proved keeps the build incomplete. A retirement a build reports it could not@@ -255,7 +264,7 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfacesrunning again does not merge it: put the change into the spec, then refresh the local copy.- **Configuration items** (`minimumPluginVersion: "2.21.0"`) — `environmentVariables[]`,`connectionReferences[]`, `customApis[]`, `duplicateDetectionRules[]` and `solution.version`. Declare one- only when the maker asks for it or a page of this app needs it (a page calling a connector needs its+ only when the maker asks for it, accepts your offer at the personas step, or a page of this app needs it (a page calling a connector needs itsconnection reference; an action a page calls needs its Custom API). Never write a value that differs perenvironment into the spec — a current value, a connection id, a secret: those go in a `--deployment-settings`file (the solution deployment-settings shape), which the maker supplies, and a `secret` variable takes no@@ -786,7 +795,10 @@ dependency order (**app module → dashboards → command bars → forms → sec→ reset enriched default views to drop parent lookups → relationships → AI row summaries → tables[children-first] → web resources (generated app icon + page manifest + declared) → global choices →solution**). Forms/charts/views/relationships are deleted **explicitly before tables** (a table-delete does not reliably cascade cross-references; it does remove the table's own columns). Security+delete does not reliably cascade cross-references; it does remove the table's own columns). A built+table's only Main form is refused by Dataverse ("You must have at least one active Main form"); the table's+delete removes it, and the run counts it as removed only when a fresh read of its id shows it gone —+otherwise the refusal stays a failure. Securityroles come **after forms** because a form assigned to a role names it inside its own formxml, whichthe platform counts as a dependency, and **before** relationships/tables because a role holding atable's privileges can block that table's delete. Command