diff --git a/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-29-project-tree-output-cap.json b/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-29-project-tree-output-cap.json new file mode 100644 index 0000000000..14b12c6fa1 --- /dev/null +++ b/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-29-project-tree-output-cap.json @@ -0,0 +1 @@ +{"area": "cmd/mxcli", "date": "2026-11-29", "symptom": "the companion Project pane failed on a large project with 'Unterminated string in JSON at position 4194304'", "cause": "project-tree printed indented JSON (4.5 MB on the reporter's app) and the desktop app keeps only the first 4 MB of a plugin command's output, so the pane parsed half a document", "file": "cmd/mxcli/project_tree.go (writeProjectTree); mods/companion/hooks/tree.ts (parseTree)", "fix": "writeProjectTree encodes without SetIndent (56% of the indented size on TestApp); parseTree reports output at the 4 MB limit as cut off rather than as a JSON parse error", "insight": "the error position was exactly 4194304 = 4 MiB, which names a transport cap, not a JSON bug. Machine-read output should be compact; anything a plugin pipes through $.process.run has a size ceiling the producer never sees", "refs": ["ako/mxcli#2601"], "test": "cmd/mxcli/project_tree_output_test.go; mods/companion/tests/tree.test.ts"} diff --git a/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-29-resolver-path-before-exact-and-unchecked-writers.json b/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-29-resolver-path-before-exact-and-unchecked-writers.json new file mode 100644 index 0000000000..47dce97ccf --- /dev/null +++ b/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-29-resolver-path-before-exact-and-unchecked-writers.json @@ -0,0 +1 @@ +{"area": "cmd/mxcli", "date": "2026-11-29", "symptom": "with another Mendix version's mx on PATH, every command took it over the project's installed exact version; the marketplace post-install repairs and install --allow-format-change's module-import then wrote the project's model with it, and fix --mx ran the PATH mx", "cause": "docker.ResolveMxForVersion tried PATH before an exact-version install or cache, and its callers that write the model never checked the release of what it returned (git merge #2644 and marketplace package #2652 had each patched around it locally)", "file": "cmd/mxcli/docker/check.go (ResolveMxForVersion), cmd/mxcli/mx_model_writer.go (mxForModelWrite, mxReleaseProblem, fixOverrideMx), cmd/mxcli/marketplace_postinstall.go, cmd/mxcli/cmd_marketplace_install.go, cmd/mxcli/cmd_fix.go", "fix": "the resolver takes localMxForVersion (exact install or cache) before PATH; model writers without an override go through mxForModelWrite, which refuses another release (*mxReleaseError) — post-install repairs are skipped with their manual commands, module-import is refused; fix --mx refuses an mx outside the named path; git merge's release check now shares mxReleaseProblem", "insight": "two per-caller fixes in a row (#2644, #2652) were the signal that the defect lived in the shared resolver: enumerate a helper's callers when the second caller needs the same patch, and split them by whether they WRITE the model — only writers need a hard release check, readers are served by fixing the preference order", "refs": ["ako/mxcli#2681", "ako/mxcli#2644", "ako/mxcli#2652"], "test": "cmd/mxcli/docker/resolve_exact_before_path_2681_test.go, cmd/mxcli/mx_model_writer_2681_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-29-agent02-follows-agent-editor-version.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-29-agent02-follows-agent-editor-version.json new file mode 100644 index 0000000000..d613958968 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-29-agent02-follows-agent-editor-version.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-11-29", "symptom": "on an Agent Editor 1.x project, `check -p` and `exec` refused a `create agent` with a Model and no SelectedModel (MDL-AGENT02 error) that the project phase accepted, so --no-check was the only way through", "cause": "the syntax phase (ValidateAgentSelectedModel) had no project and errored for every version; the project phase gated on a single 2.2 threshold, so it was also silent on 1.3–2.1, where Studio Pro does report AE018", "file": "mdl/executor/validate_agent_selected_model.go (agentSelectedModelVerdict, agentEditorCommonsVersion), validate_agent_left_unset.go, validate_program.go", "fix": "one verdict keyed on AgentEditorCommons' version, asked by both phases (the syntax phase through ValidateProgram's lazy project): before 1.3 nothing, 1.3–2.1 an error for an agent with a Model (AE018), 2.2+ also a warning without one; no project judges as current releases", "insight": "mx check does not run the Agent Editor extension (no AE code on 2.6.0 either, the control), so AE018 cannot be measured headlessly; grep the extension JS in the .mpk instead: the guard `model && !selectedModel` with errorCode AE018 is absent in 1.1.0/1.2.0 and present from 1.3.0. The startup-import threshold (2.2) and the Studio Pro check threshold (1.3) are different measurements of different things", "refs": ["ako/mxcli#2294", "ako/mxcli#2289", "ako/mxcli#2031"], "test": "mdl/executor/validate_agent_selected_model_version_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-29-assoc-path-qualified-final-attribute.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-29-assoc-path-qualified-final-attribute.json new file mode 100644 index 0000000000..d49e704848 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-29-assoc-path-qualified-final-attribute.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-11-29", "symptom": "`sort by Mod.Card_Task/Mod.Task.LastActivityAt` on a Gallery/pluggable datasource was stored as `Mod.Task.Mod.Task.LastActivityAt`; check and exec passed, mxbuild crashed loading the project (ArgumentNullException setting 'Attribute', no CE), fix widgets crashed, and re-exec reported Unchanged over the broken value", "cause": "resolveAssociationPathFrom qualified the final path segment with the hop's destination entity even when the author had already qualified it (`Mod.Entity.Attr` or `Entity.Attr`)", "file": "mdl/executor/cmd_pages_builder_v3.go (resolveAssociationPathFrom)", "fix": "a qualified final attribute is accepted when its entity is the destination or one it inherits from (an `Entity.` qualifier is read in the destination's module) and stripped to the bare name; any other entity leaves the path unresolved, so a sort refuses it at exec", "insight": "the resolver is shared by datasource sorts, DataGrid 2 columns, dynamic-text parameters and input bindings, so the reported widget is one of four writers of the same doubled name. The bare spelling is what describe emits, which is why round-trips never hit it: only hand- or agent-written qualified paths do. The 'in sync' report was correct about the bytes; the fix makes the same script produce different bytes, so re-exec repairs a stored page", "refs": ["ako/mxcli#2671", "mendixlabs/mxcli#1983", "mendixlabs/mxcli#1152"], "test": "mdl/executor/cmd_pages_builder_qualified_final_attr_2671_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-29-odata-edm-date-imported-localized-ce4598.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-29-odata-edm-date-imported-localized-ce4598.json new file mode 100644 index 0000000000..5e0eba457c --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-29-odata-edm-date-imported-localized-ce4598.json @@ -0,0 +1 @@ +{"area":"mdl/executor","date":"2026-11-29","symptom":"`create external entities from …` imported an Edm.Date property as a localized DateTime; mx check: CE4598 \"Cannot localize this attribute. The remote type of this attribute is 'Edm.Date', which does not support Localize\"","cause":"edmToDomainModelAttrType mapped Edm.DateTime, Edm.DateTimeOffset and Edm.Date in one case with LocalizeDate true; the single-entity rewrite then carried a stored true (carryStoredAttributeState, #1373) so even a re-import could not repair it","file":"mdl/executor/cmd_contract.go (edmToDomainModelAttrType, unlocalizeEdmDates), mdl/executor/cmd_odata.go (execCreateExternalEntity rewrite)","insight":"The remote type, not the stored value or the statement, decides Localize for Edm.Date: Mendix accepts only false. A carry rule that preserves a stored flag also preserves an earlier build's wrong value, so a constraint the platform imposes must run after the carry. The bulk import rebuilds attributes from the contract and repairs itself; the single-entity path does not. None of the formula1 contracts held an Edm.Date, which is why it surfaced only on a CRM contract.","refs":["ako/mxcli#2676"],"ce":["CE4598"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-29-page-that-shows-itself-page-not-found.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-29-page-that-shows-itself-page-not-found.json new file mode 100644 index 0000000000..50775fa28e --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-29-page-that-shows-itself-page-not-found.json @@ -0,0 +1 @@ +{"area":"mdl/executor","date":"2026-11-29","symptom":"A page whose widget does `show page` to the page itself cannot be created after `drop page`: \"failed to build page: failed to build widget: failed to resolve page: page not found: M.Driver\"; `check --references` also refused a script that creates such a page, drops and creates it again: \"page M.Driver references page M.Driver before it is created\"","cause":"execCreatePageV3 builds the page (buildPageV3, which minted the page ID) before CreatePage and trackCreatedPage, so resolvePageRef found the page only while an old copy was still stored; validateForwardPageRefs and MDL-PAGE01 counted the statement's reference to itself as one to the later create of the same name","file":"mdl/executor/cmd_pages_create_v3.go (pageBuilder.selfPage/selfPageID set before the build), cmd_pages_builder_input.go (resolvePageRef), cmd_pages_builder_v3.go (buildPageV3 uses selfPageID), validate.go (selfPageName, validateForwardPageRefs), validate_page_order.go","insight":"The report blamed `drop page`, but a first `create page` fails the same way: only the in-place rewrite worked, which is why it looked like a drop problem. Any resolver that looks a document up among the stored ones while that document is being built misses the document itself; decide the ID before the build and let the resolver answer for it. Fixing exec alone was not enough: the reference check had the same blind spot one layer up, so test the reporter's whole script, not only the failing statement.","refs":["ako/mxcli#2677"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-29-widget-describe-version-note.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-29-widget-describe-version-note.json new file mode 100644 index 0000000000..e75834f35d --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-29-widget-describe-version-note.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-11-29", "symptom": "`mxcli widget describe maps -p` printed an MDL example with `advanced: false` from the installed Maps 3.2.2 with no note that it holds for that version only; Maps 5.0.0 has no `advanced` property", "cause": "DescribeWidget recorded the version and source but said nothing about what that means for the example; the reader took it as valid for the version about to be installed", "file": "mdl/executor/widget_describe.go (installedVersionNote, embeddedVersionNote, WidgetDescription.VersionNote, PrintWidgetDescription)", "fix": "a VersionNote (text 'Note:' line and JSON versionNote) names the package and version read, and says to describe again after installing another; without -p it says the embedded template may differ from the installed one", "insight": "the hint is 'describe again', not 'widget init': the project's widget definitions already refresh when a package is replaced (RefreshStaleWidgetDefinitions, #2155), so the issue's suggested remedy is a step nobody needs", "refs": ["ako/mxcli#2586", "mendixlabs/mxcli#1944"], "test": "mdl/executor/widget_describe_version_note_test.go"} diff --git a/.claude/skills/mendix/agents/SKILL.md b/.claude/skills/mendix/agents/SKILL.md index ab99340a47..e4e840e0df 100644 --- a/.claude/skills/mendix/agents/SKILL.md +++ b/.claude/skills/mendix/agents/SKILL.md @@ -13,10 +13,10 @@ description: "Author Mendix AI agent documents in MDL — Model, Knowledge Base, | 24-50 | Overview | | 51-195 | Syntax | | 196-222 | Altering existing documents | -| 223-294 | Gotchas | -| 295-317 | Common Patterns | -| 318-385 | Calling Agents from Microflows | -| 386-388 | AI agent documents | +| 223-296 | Gotchas | +| 297-319 | Common Patterns | +| 320-387 | Calling Agents from Microflows | +| 388-390 | AI agent documents | # Agents @@ -233,7 +233,9 @@ an **error** and `exec` refuses the statement: on a `create agent` without it (`mxcli check`), and on a `create or modify agent` that leaves a new or stored agent without one (`check --references` and `exec`). A `create or modify` that leaves the key out keeps a stored selected model and is not flagged. With no -`Model` at all it is a warning. `mxcli lint` reports a stored agent without +`Model` at all it is a warning. With `-p` the verdict follows the +project's AgentEditorCommons: nothing before 1.3, only the AE018 error from 1.3 +to 2.1. `mxcli lint` reports a stored agent without one (MPR014). Agent Editor 1.x does not read it, so the project check is silent there. diff --git a/CHANGELOG.md b/CHANGELOG.md index 26954b80f8..c937d9d3c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- **An installed mx of the project's Mendix version is used before an `mx` on PATH, and no other version's mx writes the project's model** (ako/mxcli#2681) — `ResolveMxForVersion` tried PATH first, so another version's `mx` there won everywhere: `docker check`, `docker build`, the managed Java dependency sync and the marketplace reference project. The marketplace post-install repairs (`update-widgets`, `rename-design-properties`) and `marketplace install --allow-format-change` (`mx module-import`) then wrote the project's model with that `mx`, whatever its version. The resolver now takes an exact-version install or cache before PATH. Those two writers check the `mx`'s release: on a mismatch the repairs are skipped with their manual commands, and `module-import` is refused with the setup hint. `fix … --mx ` no longer falls back to the `mx` on PATH when the path holds none. - **`check -p` rejects `modify attribute` on an external entity that leaves the service's type** (ako/mxcli#1258) — changing a mapped attribute to another type class (an Edm.Int32 to `decimal`, an Edm.String to `integer`) or a string to another length than the contract's passed `check` and `exec`, and the build reported CE6616 or CE6621. New MDL112, which reads the contract stored on the consumed service. Integer and Long count as one class, as Mendix compares them, so `long` for an Edm.Int32 is accepted. Measured on MxBuild 11.16.1. - **`check -p` rejects `call external action` naming an action the service does not have** (ako/mxcli#1258) — an action missing from the consumed service's contract, or the right name in another case, passed `check` and `exec`, and the build reported CE7251 "Service … does not contain action …". New MDL111, which reads the contract stored on the project's consumed service and lists the actions it has. Action names are case-sensitive. A service the script itself creates or changes is not judged. Measured on MxBuild 11.16.1. - **`check` rejects a published OData service that exposes a Binary attribute** (ako/mxcli#1258) — exposing the entity's own Binary attribute, or one it inherits, passed `check` and `exec`, and the build reported CE5013 "Binary attribute … cannot be exposed through an OData entity". New MDL110; the attribute's type is read from the script, then the project. Every other attribute type exposes clean. Measured on MxBuild 11.16.1. @@ -27,6 +28,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **`git merge` no longer runs another Mendix version's merge engine** (ako/mxcli#2644, upstream mendixlabs/mxcli#1976) — the engine was resolved by preference, so with only another version cached (a Linux container, a CI runner) or an `mx` on PATH, `mx merge` of that version wrote the project's merged model and nothing said so. A model merge now runs only on an mx of the project's own release: another version's, or one whose version cannot be told, is refused before it runs, the merge is aborted, and the message names `mxcli setup mxbuild --version `. The `mx diff` behind the conflict review is held to the same check. `--mxbuild-path` names an mx on purpose; with it a mismatch only warns, as in `marketplace package`. An installed mx of the project's release is taken before an `mx` on PATH, so a different version on PATH no longer blocks a merge the right engine is there for. `--mxbuild-path` must name a folder that holds an mx: it no longer falls back to the `mx` on PATH and runs that under the override. - **Call ML model activities survive describe → exec** (ako/mxcli#2623, upstream mendixlabs/mxcli#1964) — `describe` printed a Call ML model activity as `-- Unsupported action: Microflows$MLModelCallAction`, so executing the description removed the activity. It now has a statement, `[$Out =] call ml model Module.MLModelMapping($In) [on error …];`, which writes Studio Pro's stored shape and is what `describe` prints. The output variable is typed as the mapping's output entity. `check --references` refuses a mapping that does not exist (mxbuild CE1613), and a nanoflow refuses the statement. `mxcli syntax microflow.ml-model`. - **A layout-grid column with no `DesktopWidth` is no longer one twelfth wide** — it was written at weight 1. A project before Mendix 11.12 failed the row with CE0535 ("must add up to 12"), and 11.12 drew the column at one twelfth of the row. Bare columns now share what the row's stated widths leave of 12, as Studio Pro's row presets do: one bare column gets 12, and two get 6 each. A bare column is AutoFill when there is no whole share. `check` warns (MDL-GRID01) about a row whose widths do not add up to 12 in a project below 11.12, where mxbuild reports CE0535 (measured on 11.6.6; 11.12.6 accepts it). +- **The companion Project pane loads large projects** (ako/mxcli#2601) — `mxcli project-tree` printed indented JSON, and on a large app the indentation pushed it past the 4 MB the desktop app keeps of a plugin command's output, so the pane failed with "Unterminated string in JSON". The tree is now one line of JSON (about 56% of the size), and a tree that is still cut off says so instead of showing a JSON parse error. Pipe through `python3 -m json.tool` to read it. +- **`widget describe` says which widget version its example holds for** (ako/mxcli#2586, upstream mendixlabs/mxcli#1944) — the properties and the MDL example come from one version: the package installed in the project with `-p`, mxcli's embedded template without. A new `Note:` line (and `versionNote` in `--format json`) names that package and version, and says to describe again after installing another version. The project's widget definitions refresh on their own when a package changes, so no `widget init` is needed. +- **MDL-AGENT02 follows the project's Agent Editor version** (ako/mxcli#2294) — `check -p` and `exec` refused a `create agent` with a `Model` and no `SelectedModel` on an Agent Editor 1.x project, which does not need one. Measured from each package's extension code: Studio Pro's AE018 first appears in 1.3.0, and the startup import reads `selectedModel` from 2.2. With a project, check now reports nothing before 1.3, only the AE018 error from 1.3 to 2.1, and both from 2.2. The project phase gets the same verdict, so it no longer stays silent on 1.3–2.1. Without a project, nothing changes. +- **An association path whose final attribute is written qualified is no longer stored with the entity doubled** (ako/mxcli#2671, upstream mendixlabs/mxcli#1983) — `sort by Mod.Card_Task/Mod.Task.LastActivityAt` was stored as `Mod.Task.Mod.Task.LastActivityAt`. `check` and `exec` passed, then mxbuild crashed loading the project with an `ArgumentNullException` that named no page. The same resolver serves DataGrid 2 columns, dynamic-text parameters and input bindings, so they were affected too. The qualifier is now accepted when it names the entity the path arrives at, or one it inherits from. An entity the path does not reach is refused. Re-running the same `create or modify` script repairs a page that was stored broken. ## [0.34.0] - 2026-11-27 diff --git a/cmd/mxcli/cmd_fix.go b/cmd/mxcli/cmd_fix.go index e8e1cbb972..252957d571 100644 --- a/cmd/mxcli/cmd_fix.go +++ b/cmd/mxcli/cmd_fix.go @@ -113,8 +113,12 @@ func runFixTool(cmd *cobra.Command, subcommand, what string) error { _ = reader.Disconnect() var mxPath string - if mxOverride != "" || mendixVer == "" { - mxPath, err = docker.ResolveMxForVersion(mxOverride, mendixVer) + if mxOverride != "" { + if mxPath, err = fixOverrideMx(mxOverride, mendixVer); err != nil { + return fmt.Errorf("locate mx for Mendix %s: %w\nhint: run 'mxcli setup mxbuild -p %s'", mendixVer, err, mprPath) + } + } else if mendixVer == "" { + mxPath, err = docker.ResolveMxForVersion("", mendixVer) if err != nil { return fmt.Errorf("locate mx for Mendix %s: %w\nhint: run 'mxcli setup mxbuild -p %s'", mendixVer, err, mprPath) } diff --git a/cmd/mxcli/cmd_git_merge.go b/cmd/mxcli/cmd_git_merge.go index fa8ce615d3..4032480e68 100644 --- a/cmd/mxcli/cmd_git_merge.go +++ b/cmd/mxcli/cmd_git_merge.go @@ -752,17 +752,7 @@ func pathWithin(path, dir string) bool { // project version is not checked (ResolveMxForVersion had nothing to prefer // either); an mx whose own version cannot be told is a problem. func mergeMxProblem(mxPath, version string) string { - if version == "" { - return "" - } - got := mergeMxVersion(mxPath) - if docker.SameMendixRelease(got, version) { - return "" - } - if got == "" { - return fmt.Sprintf("cannot tell which Mendix version %s is, and the project is Mendix %s", mxPath, version) - } - return fmt.Sprintf("the mx found, %s, is Mendix %s, but the project is Mendix %s", mxPath, got, version) + return mxReleaseProblem(mergeMxVersion, mxPath, version) } // mxRunnersFor wires the real mx invocations to one version-checked lookup. diff --git a/cmd/mxcli/cmd_marketplace_install.go b/cmd/mxcli/cmd_marketplace_install.go index cdc86e0d93..b70deab8d1 100644 --- a/cmd/mxcli/cmd_marketplace_install.go +++ b/cmd/mxcli/cmd_marketplace_install.go @@ -6,6 +6,7 @@ import ( "archive/zip" "context" "encoding/xml" + "errors" "fmt" "io" "os" @@ -291,7 +292,13 @@ func installModuleFromFile(ctx context.Context, mpkPath, mprPath string, allowFo return nil } - mxPath, err := docker.ResolveMxForVersion("", mendixVer) + // module-import writes the project's model, so only its own release's mx + // may run it (ako/mxcli#2681). + mxPath, err := mxForModelWrite(mendixVer) + var releaseErr *mxReleaseError + if errors.As(err, &releaseErr) { + return err + } if err != nil { return fmt.Errorf("locate mx for Mendix %s: %w\nhint: run 'mxcli setup mxbuild -p %s'", mendixVer, err, mprPath) } diff --git a/cmd/mxcli/docker/check.go b/cmd/mxcli/docker/check.go index 9cdf93b165..e495204eea 100644 --- a/cmd/mxcli/docker/check.go +++ b/cmd/mxcli/docker/check.go @@ -459,6 +459,15 @@ func ResolveMxForVersion(mxbuildPath, preferredVersion string) (string, error) { } } + // An installed or cached mx of exactly the requested version comes before an + // mx on PATH, which carries no version guarantee: PATH used to come first, so + // another version's mx there won over the project's own, and every caller + // that checks the version afterwards refused although the right mx was + // installed (ako/mxcli#2681). Without an exact one, PATH keeps its place. + if exact := localMxForVersion(preferredVersion); exact != "" { + return exact, nil + } + // Try PATH if p, err := exec.LookPath("mx"); err == nil { return p, nil diff --git a/cmd/mxcli/docker/resolve_exact_before_path_2681_test.go b/cmd/mxcli/docker/resolve_exact_before_path_2681_test.go new file mode 100644 index 0000000000..687f172394 --- /dev/null +++ b/cmd/mxcli/docker/resolve_exact_before_path_2681_test.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 + +package docker + +import ( + "os" + "path/filepath" + "testing" + + "github.com/mendixlabs/mxcli/internal/testutil" +) + +// ako/mxcli#2681: an installed or cached mx of exactly the requested version is +// taken before an mx on PATH. PATH came first, so another version's mx there +// won over the project's own, and every caller that checked the version after +// the fact refused although the right mx was installed. +func TestResolveMxForVersion_ExactInstallBeatsPath(t *testing.T) { + home := t.TempDir() + testutil.SetHome(t, home) + setTestApplicationsDir(t, t.TempDir()) + pathDir := t.TempDir() + onPath := filepath.Join(pathDir, mxBinaryName()) + if err := os.WriteFile(onPath, []byte("#!/bin/sh\n"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", pathDir) + cached := filepath.Join(home, ".mxcli", "mxbuild", "11.9.0", "modeler", mxBinaryName()) + if err := os.MkdirAll(filepath.Dir(cached), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(cached, []byte("fake"), 0o755); err != nil { + t.Fatal(err) + } + + got, err := ResolveMxForVersion("", "11.9.0") + if err != nil || got != cached { + t.Errorf("ResolveMxForVersion(11.9.0) = %q, %v; want the cached exact version %s, not the PATH mx", got, err, cached) + } + // Control: with no exact install, PATH still comes before the other fallbacks. + got, err = ResolveMxForVersion("", "12.0.0") + if err != nil || got != onPath { + t.Errorf("ResolveMxForVersion(12.0.0) = %q, %v; want the PATH mx %s", got, err, onPath) + } +} diff --git a/cmd/mxcli/marketplace_postinstall.go b/cmd/mxcli/marketplace_postinstall.go index bb58bd1f16..9a1de53e48 100644 --- a/cmd/mxcli/marketplace_postinstall.go +++ b/cmd/mxcli/marketplace_postinstall.go @@ -3,6 +3,7 @@ package main import ( + "errors" "fmt" "io" @@ -46,9 +47,9 @@ var ( // Seams for tests: resolving mx, running a tool, and reading the project's // Mendix version. var ( - postInstallResolveMx = func(mendixVer string) (string, error) { - return docker.ResolveMxForVersion("", mendixVer) - } + // The repairs write the project's model, so only its own release's mx may + // run them (ako/mxcli#2681). + postInstallResolveMx = mxForModelWrite postInstallRunTool = docker.RunToolPreservingFormat postInstallMendixVersion = mendixVersionOf ) @@ -62,6 +63,12 @@ func runPostInstallRepairs(out, stderr io.Writer, mprPath, mendixVer string, rep return } mxPath, err := postInstallResolveMx(mendixVer) + var releaseErr *mxReleaseError + if errors.As(err, &releaseErr) { + fmt.Fprintf(out, "\n Warning: %v\n so the post-install repairs did not run. Once the matching mx is installed:\n", releaseErr) + printManualRepairs(out, mprPath, repairs) + return + } if err != nil { fmt.Fprintf(out, "\n Warning: no mx for Mendix %s (%v), so the post-install repairs did not run.\n", mendixVer, err) fmt.Fprintf(out, " Run 'mxcli setup mxbuild -p %s', then:\n", mprPath) diff --git a/cmd/mxcli/mx_model_writer.go b/cmd/mxcli/mx_model_writer.go new file mode 100644 index 0000000000..b2988c5e5b --- /dev/null +++ b/cmd/mxcli/mx_model_writer.go @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "fmt" + + "github.com/mendixlabs/mxcli/cmd/mxcli/docker" +) + +// The mx a command runs to WRITE the user's project's model must be the +// project's own Mendix release (ako/mxcli#2681). docker.ResolveMxForVersion +// prefers that release but falls back to any mx it can find, which is right +// for reading and wrong for writing: another version's mx would write this +// project's model. git merge (#2644) and marketplace package (#2652) carry the +// same rule with an override flag; the marketplace post-install repairs and +// `install --allow-format-change`'s module-import have none, so they refuse. + +// modelWriterResolveMx and modelWriterMxVersion are injected for tests. +var ( + modelWriterResolveMx = docker.ResolveMxForVersion + modelWriterMxVersion = docker.MxBinaryVersion +) + +// mxReleaseError is a refusal of an mx of another (or an unknown) release, +// told apart from "no mx at all", which callers report differently. +type mxReleaseError struct{ msg string } + +func (e *mxReleaseError) Error() string { return e.msg } + +// mxForModelWrite resolves the mx for mendixVer and refuses one of another +// release with an *mxReleaseError. An unknown project version is not checked: +// the resolver had nothing to prefer either. +func mxForModelWrite(mendixVer string) (string, error) { + mxPath, err := modelWriterResolveMx("", mendixVer) + if err != nil { + return "", err + } + if problem := mxReleaseProblem(modelWriterMxVersion, mxPath, mendixVer); problem != "" { + return "", &mxReleaseError{fmt.Sprintf("%s; another Mendix version's mx must not write this project's model\n"+ + "hint: run 'mxcli setup mxbuild --version %s' to install the matching mx", problem, mendixVer)} + } + return mxPath, nil +} + +// mxReleaseProblem says why the mx at mxPath must not write a project of +// version, or "" when it may: it is the same Mendix release, build number +// aside. An unknown project version is not checked; an mx whose own version +// cannot be told is a problem. versionOf reads an mx's version. +func mxReleaseProblem(versionOf func(string) string, mxPath, version string) string { + if version == "" { + return "" + } + got := versionOf(mxPath) + if docker.SameMendixRelease(got, version) { + return "" + } + if got == "" { + return fmt.Sprintf("cannot tell which Mendix version %s is, and the project is Mendix %s", mxPath, version) + } + return fmt.Sprintf("the mx found, %s, is Mendix %s, but the project is Mendix %s", mxPath, got, version) +} + +// fixOverrideMx resolves the mx `fix --mx ` names. The resolver falls +// back to PATH when the folder holds no mx, which would run an mx nobody +// named, so an mx outside the path is refused. The path is the deliberate +// choice, so its version is not checked. +func fixOverrideMx(override, mendixVer string) (string, error) { + mxPath, err := modelWriterResolveMx(override, mendixVer) + if err != nil { + return "", err + } + if !pathWithin(mxPath, override) { + return "", fmt.Errorf("no mx in %s (the mx found instead, %s, was not named by --mx)", override, mxPath) + } + return mxPath, nil +} diff --git a/cmd/mxcli/mx_model_writer_2681_test.go b/cmd/mxcli/mx_model_writer_2681_test.go new file mode 100644 index 0000000000..bfabdb48e0 --- /dev/null +++ b/cmd/mxcli/mx_model_writer_2681_test.go @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "bytes" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/mendixlabs/mxcli/cmd/mxcli/docker" +) + +// ako/mxcli#2681: the commands that run mx on the user's project to write its +// model — the marketplace post-install repairs and `install +// --allow-format-change`'s module-import — took whatever mx the resolver found, +// another Mendix version's included, and `fix --mx` ran the PATH mx when the +// named folder held none. + +func stubModelWriterMx(t *testing.T, mxPath, mxVersion string) { + t.Helper() + origResolve, origVersion := modelWriterResolveMx, modelWriterMxVersion + t.Cleanup(func() { modelWriterResolveMx, modelWriterMxVersion = origResolve, origVersion }) + modelWriterResolveMx = func(string, string) (string, error) { return mxPath, nil } + modelWriterMxVersion = func(string) string { return mxVersion } +} + +func TestMxForModelWrite_RefusesAnotherRelease(t *testing.T) { + stubModelWriterMx(t, "/usr/local/bin/mx", "11.6.3") + _, err := mxForModelWrite("11.12.5") + if err == nil { + t.Fatal("another release's mx was accepted for writing an 11.12.5 model") + } + for _, want := range []string{"is Mendix 11.6.3, but the project is Mendix 11.12.5", "mxcli setup mxbuild --version 11.12.5"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("refusal lacks %q: %v", want, err) + } + } + stubModelWriterMx(t, "/usr/local/bin/mx", "") + if _, err := mxForModelWrite("11.12.5"); err == nil || !strings.Contains(err.Error(), "cannot tell which Mendix version") { + t.Errorf("an mx of unknown version was accepted: %v", err) + } + // Control: the project's release, build number aside. + stubModelWriterMx(t, "/cache/11.12.5/mx", "11.12.5.1234") + if got, err := mxForModelWrite("11.12.5"); err != nil || got != "/cache/11.12.5/mx" { + t.Errorf("the project's own release was refused: %q, %v", got, err) + } +} + +// The repairs are skipped, with the manual commands, rather than run by +// another version's mx. +func TestPostInstallRepairs_SkippedForAnotherReleasesMx(t *testing.T) { + stubModelWriterMx(t, "/usr/local/bin/mx", "11.6.3") + origRun := postInstallRunTool + t.Cleanup(func() { postInstallRunTool = origRun }) + ran := 0 + postInstallRunTool = func(_, _, _ string, _, _ io.Writer) (*docker.HarvestResult, error) { + ran++ + return nil, nil + } + var out bytes.Buffer + runPostInstallRepairs(&out, &out, "/p/app.mpr", "11.12.5", moduleRepairs) + if ran != 0 { + t.Errorf("a repair ran %d time(s) with another release's mx", ran) + } + for _, want := range []string{"is Mendix 11.6.3, but the project is Mendix 11.12.5", "post-install repairs did not run", "mxcli fix widgets -p /p/app.mpr"} { + if !strings.Contains(out.String(), want) { + t.Errorf("output lacks %q:\n%s", want, out.String()) + } + } +} + +// `fix --mx ` runs only an mx that folder holds. +func TestFixOverrideMx_MustHoldAnMx(t *testing.T) { + empty := t.TempDir() + stubModelWriterMx(t, "/usr/local/bin/mx", "11.12.5") + if _, err := fixOverrideMx(empty, "11.12.5"); err == nil || !strings.Contains(err.Error(), "no mx in "+empty) { + t.Errorf("want a refusal naming %s, got %v", empty, err) + } + // Control: an mx under the named folder is used. + dir := t.TempDir() + mx := filepath.Join(dir, "modeler", "mx") + if err := os.MkdirAll(filepath.Dir(mx), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(mx, nil, 0o755); err != nil { + t.Fatal(err) + } + stubModelWriterMx(t, mx, "11.12.5") + if got, err := fixOverrideMx(dir, "11.12.5"); err != nil || got != mx { + t.Errorf("an mx under --mx was refused: %q, %v", got, err) + } +} diff --git a/cmd/mxcli/project_tree.go b/cmd/mxcli/project_tree.go index 2a27b432c8..42259fc7da 100644 --- a/cmd/mxcli/project_tree.go +++ b/cmd/mxcli/project_tree.go @@ -5,6 +5,7 @@ package main import ( "encoding/json" "fmt" + "io" "os" "sort" "strings" @@ -65,15 +66,21 @@ Example: } markDescribable(tree) - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - if err := enc.Encode(tree); err != nil { + if err := writeProjectTree(os.Stdout, tree); err != nil { fmt.Fprintf(os.Stderr, "Error encoding JSON: %v\n", err) os.Exit(1) } }, } +// writeProjectTree prints the tree as one line of JSON. It is not indented: +// the desktop app cuts a plugin command's output at 4 MB, and on a large app +// indentation alone pushed the tree past it (#2601). Pipe through +// `python3 -m json.tool` to read it. +func writeProjectTree(w io.Writer, tree []*TreeNode) error { + return json.NewEncoder(w).Encode(tree) +} + // treeTypesWithoutSource lists the node types project-tree emits that have no // MDL of their own, with the reason. Every other type it emits must be one // `describe` answers; TestProjectTree_EveryNodeTypeIsDescribableOrDeclaredWithoutSource diff --git a/cmd/mxcli/project_tree_output_test.go b/cmd/mxcli/project_tree_output_test.go new file mode 100644 index 0000000000..e7584fa603 --- /dev/null +++ b/cmd/mxcli/project_tree_output_test.go @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "bytes" + "strings" + "testing" +) + +// TestWriteProjectTree_IsCompact holds #2601: the desktop app cuts a plugin +// command's output at 4 MB, and a large app's indented tree was 4.5 MB, so the +// companion pane got half a JSON document. Indentation was about half the +// bytes; nothing that reads the tree needs it. +func TestWriteProjectTree_IsCompact(t *testing.T) { + tree := []*TreeNode{{ + Label: "Sales", Type: "module", QualifiedName: "Sales", + Children: []*TreeNode{{Label: "Home", Type: "page", QualifiedName: "Sales.Home", Describable: true}}, + }} + var buf bytes.Buffer + if err := writeProjectTree(&buf, tree); err != nil { + t.Fatal(err) + } + out := buf.String() + want := `[{"label":"Sales","type":"module","qualifiedName":"Sales","children":[{"label":"Home","type":"page","qualifiedName":"Sales.Home","describable":true}]}]` + "\n" + if out != want { + t.Fatalf("project-tree output is not compact:\n got %q\nwant %q", out, want) + } + if strings.Count(out, "\n") != 1 { + t.Fatalf("want one line, got %d", strings.Count(out, "\n")) + } +} diff --git a/docs-site/src/appendixes/error-messages.md b/docs-site/src/appendixes/error-messages.md index 65dc44d170..7f39c34d48 100644 --- a/docs-site/src/appendixes/error-messages.md +++ b/docs-site/src/appendixes/error-messages.md @@ -370,7 +370,7 @@ import of every agent; Studio Pro reports AE018 "Model version is required for a ``` **Severity:** an error, refusing `exec`, when the agent names a `Model` — Studio Pro's AE018 -(ako/mxcli#2289). A warning when it has no `Model` at all. +(ako/mxcli#2289). A warning when it has no `Model` at all. With a project, the verdict follows its AgentEditorCommons version (ako/mxcli#2294): before 1.3 nothing is reported (neither AE018 nor the import reads it), from 1.3 to 2.1 only the AE018 error for an agent with a `Model`, from 2.2 both. **Cause:** Agent Editor 2.2+ (AgentEditorCommons `AgentFromModel_Validate`) requires the agent's `selectedModel` id and retrieves the deployed model by it. mxbuild does not read agent diff --git a/docs-site/src/reference/agent/create-agent.md b/docs-site/src/reference/agent/create-agent.md index 45e2cf2b43..f40c90a571 100644 --- a/docs-site/src/reference/agent/create-agent.md +++ b/docs-site/src/reference/agent/create-agent.md @@ -90,7 +90,7 @@ If `OR MODIFY` is specified and the agent already exists, its properties and bod : Qualified reference to the model document the agent uses. `SelectedModel` -: The id of the model the agent uses, one the Model document's resource offers (e.g. `'eu.anthropic.claude-sonnet-5'`). Required in practice from Agent Editor 2.2: its import refuses an agent without one ("Model with name is referenced but could not be found for the Agent"), and that refusal stops the import of every agent document at startup. Studio Pro reports an agent with a `Model` and no selected model as AE018 ("Model version is required for an agent"), so for such an agent MDL-AGENT02 is an error and `exec` refuses it: `mxcli check` on a `create agent` without it, `check --references` and `exec` on a `create or modify` that leaves the agent without one. With no `Model` it is a warning. `mxcli lint` reports a stored agent without one (MPR014). Only the id is read at runtime; it is matched against `GenAICommons.DeployedModel.Model`. To list the ids, with the app running: `mxcli oql "select Model from MxGenAIConnector.MxCloudDeployedModel"` (reported to work in ako/mxcli#2031). `''` clears it. +: The id of the model the agent uses, one the Model document's resource offers (e.g. `'eu.anthropic.claude-sonnet-5'`). Required in practice from Agent Editor 2.2: its import refuses an agent without one ("Model with name is referenced but could not be found for the Agent"), and that refusal stops the import of every agent document at startup. Studio Pro reports an agent with a `Model` and no selected model as AE018 ("Model version is required for an agent"), so for such an agent MDL-AGENT02 is an error and `exec` refuses it: `mxcli check` on a `create agent` without it, `check --references` and `exec` on a `create or modify` that leaves the agent without one. With no `Model` it is a warning. With a project, the verdict follows its AgentEditorCommons version (ako/mxcli#2294): before 1.3 nothing is reported (neither AE018 nor the import reads it), from 1.3 to 2.1 only the AE018 error for an agent with a `Model`, from 2.2 both. `mxcli lint` reports a stored agent without one (MPR014). Only the id is read at runtime; it is matched against `GenAICommons.DeployedModel.Model`. To list the ids, with the app running: `mxcli oql "select Model from MxGenAIConnector.MxCloudDeployedModel"` (reported to work in ako/mxcli#2031). `''` clears it. `SelectedModelName` : Optional. The display name Studio Pro stores next to the id (e.g. `'Anthropic Claude Sonnet 5'`); nothing at runtime reads it. Defaults to the id, or keeps the stored name while the id is unchanged. diff --git a/mdl-examples/bug-tests/2676-odata-edm-date-not-localized.mdl b/mdl-examples/bug-tests/2676-odata-edm-date-not-localized.mdl new file mode 100644 index 0000000000..80a82d5aa8 --- /dev/null +++ b/mdl-examples/bug-tests/2676-odata-edm-date-not-localized.mdl @@ -0,0 +1,36 @@ +mdl 1; +-- Bug ako/mxcli#2676: `create external entities from …` imports an Edm.Date +-- property as a localized DateTime. +-- +-- Symptom, verbatim: "Mendix allows an `Edm.Date` attribute only unlocalized, +-- so the build fails: CE4598 Cannot localize this attribute." +-- +-- Measured on mx check 11.14.0. Before the fix this script built with one +-- CE4598 "Cannot localize this attribute. The remote type of this attribute is +-- 'Edm.Date', which does not support Localize" at 'Issue2676.Client.dateOfBirth'; +-- after it, 0 errors. Edm.DateTimeOffset (lastSeen) stays localized, as Studio +-- Pro imports it. Re-running the import with a fixed build repairs an entity an +-- earlier build imported localized. +-- +-- Run it (MetadataUrl resolves relative to the project directory): +-- +-- mkdir -p /path/to/app/mdl-examples/odata-local-metadata +-- cp mdl-examples/odata-local-metadata/edm-date-metadata.xml /path/to/app/mdl-examples/odata-local-metadata/ +-- mxcli exec mdl-examples/bug-tests/2676-odata-edm-date-not-localized.mdl -p app.mpr +-- mxcli docker check -p app.mpr + +create module Issue2676; + +create constant Issue2676.SvcUrl + ( Type: string, DefaultValue: 'http://localhost:18765/' ); + +create consumed odata service Issue2676.Crm ( + ODataVersion: OData4, + MetadataUrl: './mdl-examples/odata-local-metadata/edm-date-metadata.xml', + ServiceUrl: '@Issue2676.SvcUrl' +); + +create external entities from Issue2676.Crm into Issue2676; + +-- Expect: dateOfBirth: DateTime not localized, lastSeen: DateTime +describe entity Issue2676.Client; diff --git a/mdl-examples/bug-tests/2677-page-shows-itself-after-drop.mdl b/mdl-examples/bug-tests/2677-page-shows-itself-after-drop.mdl new file mode 100644 index 0000000000..cf08b388f8 --- /dev/null +++ b/mdl-examples/bug-tests/2677-page-shows-itself-after-drop.mdl @@ -0,0 +1,63 @@ +mdl 1; +-- Bug ako/mxcli#2677: a page that shows itself cannot be created after +-- `drop page`. +-- +-- Symptom, verbatim: "Error: failed to build page: failed to build widget: +-- failed to resolve page: page not found: M.Driver" +-- +-- The page is built before it is created, and its show page action looked its +-- own name up among the stored pages. Measured on dae7f09 against a project made +-- with `mxcli new --version 11.14.0`: the first `create` of such a page fails +-- the same way, with no drop at all, and so does a drop + create (in one script +-- or in two runs). Only an in-place rewrite worked, because the old page was +-- still stored. This script did not even reach exec: the reference check called +-- the page's link to itself a forward reference, "statement 3: page +-- Issue2677.Driver references page Issue2677.Driver before it is created". +-- After the fix it prints "Created page", "Dropped page", "Created page" on +-- every run, and mx check 11.14.0 reports 0 errors. +-- +-- Run it against a project that has Atlas_Core: +-- +-- mxcli exec mdl-examples/bug-tests/2677-page-shows-itself-after-drop.mdl -p app.mpr +-- mxcli exec mdl-examples/bug-tests/2677-page-shows-itself-after-drop.mdl -p app.mpr # again: drop, then create +-- mxcli docker check -p app.mpr + +create module Issue2677; + +create or modify persistent entity Issue2677.Driver ( + Name: String(100) +); + +-- A list of peers, each opening the page it is on. +create or modify page Issue2677.Driver ( + Title: 'Driver', + Layout: Atlas_Core.Atlas_Default, + Params: ($Driver: Issue2677.Driver) +) { + dataview dvDriver (datasource: $Driver) { + dynamictext txtName (content: '{1}', contentparams: ({1} = Name)) + } + listview lvPeers (datasource: database Issue2677.Driver) { + container cPeer (action: show page Issue2677.Driver (Driver = $currentObject)) { + dynamictext txtPeer (content: '{1}', contentparams: ({1} = Name)) + } + } +}; + +-- The documented remedy when an in-place rewrite of a page fails. +drop page Issue2677.Driver; + +create or modify page Issue2677.Driver ( + Title: 'Driver', + Layout: Atlas_Core.Atlas_Default, + Params: ($Driver: Issue2677.Driver) +) { + dataview dvDriver (datasource: $Driver) { + dynamictext txtName (content: '{1}', contentparams: ({1} = Name)) + } + listview lvPeers (datasource: database Issue2677.Driver) { + container cPeer (action: show page Issue2677.Driver (Driver = $currentObject)) { + dynamictext txtPeer (content: '{1}', contentparams: ({1} = Name)) + } + } +}; diff --git a/mdl-examples/bug-tests/page-1983-sort-qualified-final-attribute.mdl b/mdl-examples/bug-tests/page-1983-sort-qualified-final-attribute.mdl new file mode 100644 index 0000000000..752b744062 --- /dev/null +++ b/mdl-examples/bug-tests/page-1983-sort-qualified-final-attribute.mdl @@ -0,0 +1,27 @@ +mdl 1; +-- mendixlabs/mxcli#1983 — a page data source's `sort by Assoc/Module.Entity.Attr`. +-- +-- The attribute after an association may be written fully qualified, the +-- spelling a microflow retrieve's sort uses (see +-- microflow-1152-sort-association-path.mdl). On a page it was prefixed with the +-- hop's destination a second time and stored as +-- `Sort1983.Task.Sort1983.Task.LastActivityAt`: check and exec passed, and +-- mxbuild 11.12.6 aborted loading the project with ArgumentNullException +-- ("An error occurred when trying to set the 'Attribute' property"). Measured on +-- v0.34.0 for a pluggable widget's data source and for the list view below, +-- which go through the same resolver. Both spellings below must store +-- `Sort1983.Task.LastActivityAt` with one Card_Task hop. + +create persistent entity Sort1983.Task ( Title: String(200), LastActivityAt: DateTime ); +create persistent entity Sort1983.Card ( Revision: Integer ); + +create association Sort1983.Card_Task from Sort1983.Card to Sort1983.Task; + +create or modify page Sort1983.Cards (title: 'Cards', layout: Atlas_Core.Atlas_Default) { + listview qualified (datasource: database Sort1983.Card sort by Sort1983.Card_Task/Sort1983.Task.LastActivityAt desc) { + dynamictext t1 (content: 'qualified') + } + listview bare (datasource: database Sort1983.Card sort by Sort1983.Card_Task/LastActivityAt desc) { + dynamictext t2 (content: 'bare') + } +}; diff --git a/mdl-examples/odata-local-metadata/edm-date-metadata.xml b/mdl-examples/odata-local-metadata/edm-date-metadata.xml new file mode 100644 index 0000000000..635ad80591 --- /dev/null +++ b/mdl-examples/odata-local-metadata/edm-date-metadata.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/mdl/executor/cmd_contract.go b/mdl/executor/cmd_contract.go index 20edf6b836..d0d4343eec 100644 --- a/mdl/executor/cmd_contract.go +++ b/mdl/executor/cmd_contract.go @@ -1413,11 +1413,17 @@ func edmToDomainModelAttrType(p *types.EdmProperty, isKey bool) domainmodel.Attr return &domainmodel.DecimalAttributeType{} case "Edm.Boolean": return &domainmodel.BooleanAttributeType{} - case "Edm.DateTime", "Edm.DateTimeOffset", "Edm.Date": + case "Edm.DateTime", "Edm.DateTimeOffset": // LocalizeDate true is what the writer emitted before it wrote the // property at all (#743), and what Studio Pro stores for an imported // Edm.DateTimeOffset. return &domainmodel.DateTimeAttributeType{LocalizeDate: true} + case "Edm.Date": + // A date has no time of day to shift: Mendix refuses it localized, CE4598 + // "Cannot localize this attribute. The remote type of this attribute is + // 'Edm.Date', which does not support Localize" (ako/mxcli#2676). Studio + // Pro's import sets Localize off. + return &domainmodel.DateTimeAttributeType{LocalizeDate: false} case "Edm.Guid": return &domainmodel.StringAttributeType{Length: 36} case "Edm.Binary": @@ -1427,6 +1433,21 @@ func edmToDomainModelAttrType(p *types.EdmProperty, isKey bool) domainmodel.Attr } } +// unlocalizeEdmDates turns Localize off on each attribute mapped to an Edm.Date. +// Mendix accepts no other value there (CE4598, ako/mxcli#2676), so it overrides +// a stored LocalizeDate the rewrite carried, which an import by an earlier build +// left true; without this, re-running the import could not repair it. +func unlocalizeEdmDates(attrs []*domainmodel.Attribute) { + for _, a := range attrs { + if a == nil || a.RemoteType != "Edm.Date" { + continue + } + if dt, ok := a.Type.(*domainmodel.DateTimeAttributeType); ok { + dt.LocalizeDate = false + } + } +} + // edmToAstDataType converts an Edm property to an AST data type. func edmToAstDataType(p *types.EdmProperty) ast.DataType { switch p.Type { diff --git a/mdl/executor/cmd_odata.go b/mdl/executor/cmd_odata.go index 6fccdd30e3..87d9733274 100644 --- a/mdl/executor/cmd_odata.go +++ b/mdl/executor/cmd_odata.go @@ -950,6 +950,7 @@ func execCreateExternalEntity(ctx *ExecContext, s *ast.CreateExternalEntityStmt) return err } carryStoredAttributeState(existingEntity, attrs, statedLocalize(s.Attributes)) + unlocalizeEdmDates(attrs) existingEntity.Attributes = attrs } // A rewrite that carried no doc comment keeps the stored one; an diff --git a/mdl/executor/cmd_pages_builder.go b/mdl/executor/cmd_pages_builder.go index 146900f289..a43f9cad81 100644 --- a/mdl/executor/cmd_pages_builder.go +++ b/mdl/executor/cmd_pages_builder.go @@ -47,6 +47,14 @@ type pageBuilder struct { themeRegistry *ThemeRegistry // Theme design property definitions (may be nil) widgetBackend backend.WidgetBuilderBackend // Backend for pluggable widget construction + // selfPage is the page being built, by qualified name, and selfPageID the + // ID it will be stored under. A page that shows itself (a list of peers, + // each opening the same page) resolves its own name before the page is + // created, so it cannot be found among the stored pages after a drop or on + // a first create (ako/mxcli#2677). + selfPage string + selfPageID model.ID + // dataViewVariables: enclosing data view name -> the Forms$PageVariable a // binding read through it (`$dataView1.Attr`) stores. Holds only the data // views around the widget being built (ako/mxcli#826). diff --git a/mdl/executor/cmd_pages_builder_input.go b/mdl/executor/cmd_pages_builder_input.go index 920b8e1a7b..bb9fc001e4 100644 --- a/mdl/executor/cmd_pages_builder_input.go +++ b/mdl/executor/cmd_pages_builder_input.go @@ -544,6 +544,14 @@ func (pb *pageBuilder) resolvePageRef(pageRef string) (model.ID, error) { pageName = pageRef } + // The page being built names itself (ako/mxcli#2677). + if pb.selfPageID != "" && pb.selfPage != "" { + selfModule, selfName, _ := strings.Cut(pb.selfPage, ".") + if pageName == selfName && (moduleName == "" || moduleName == selfModule) { + return pb.selfPageID, nil + } + } + // First, check if the page was created during this session // (not yet visible via reader) if pb.execCache != nil && pb.execCache.createdPages != nil { diff --git a/mdl/executor/cmd_pages_builder_qualified_final_1983_test.go b/mdl/executor/cmd_pages_builder_qualified_final_1983_test.go new file mode 100644 index 0000000000..b77bad9d6c --- /dev/null +++ b/mdl/executor/cmd_pages_builder_qualified_final_1983_test.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/sdk/pages" +) + +// mendixlabs/mxcli#1983 (ako/mxcli#2671): a page data source's +// +// sort by Process.Card_Task/Process.Task.LastActivityAt desc +// +// stored the sort attribute as `Process.Task.Process.Task.LastActivityAt`, and +// mxbuild aborted loading the project. The resolver's cases are +// cmd_pages_builder_qualified_final_attr_2671_test.go's; this file keeps the +// sort-by route the report took. + +// The report's own route: a data source's `sort by` goes through the same +// resolver, and an unreachable qualified attribute is refused instead of being +// stored as an attribute mxbuild cannot load. +func TestDatabaseSortBy_QualifiedFinalSegment_1983(t *testing.T) { + sortBy := func(attr string) (*pages.DatabaseSource, error) { + src := &pages.DatabaseSource{} + err := specializationStepPB("").applyDatabaseClausesV3(src, &ast.DataSourceV3{ + OrderBy: []ast.OrderByItemV3{{Attribute: attr, Associations: []string{"System.Session_User"}, Direction: "DESC"}}, + }, "System.Session") + return src, err + } + + src, err := sortBy("System.User.Name") + if err != nil { + t.Fatalf("sort by System.Session_User/System.User.Name: %v", err) + } + if len(src.Sorting) != 1 || src.Sorting[0].AttributePath != "System.User.Name" { + t.Fatalf("sorting = %+v, want one item on System.User.Name (not System.User.System.User.Name)", src.Sorting) + } + + if _, err := sortBy("MyFirstModule.Other.FullName"); err == nil { + t.Errorf("sort by an attribute of an entity the association does not reach was accepted") + } +} diff --git a/mdl/executor/cmd_pages_builder_qualified_final_attr_2671_test.go b/mdl/executor/cmd_pages_builder_qualified_final_attr_2671_test.go new file mode 100644 index 0000000000..ba4786fe7a --- /dev/null +++ b/mdl/executor/cmd_pages_builder_qualified_final_attr_2671_test.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import "testing" + +// ako/mxcli#2671 (mendixlabs/mxcli#1983): `sort by Mod.Card_Task/Mod.Task.LastActivityAt` +// was stored as the attribute `Mod.Task.Mod.Task.LastActivityAt`. The path +// resolver qualified the final segment with the hop's destination whether or not +// it was qualified already. check and exec passed, mxbuild crashed loading the +// project (ArgumentNullException, no CE to point at the page), and `fix widgets` +// crashed on it too. The resolver is shared, so a DataGrid 2 column, a dynamic +// text parameter and an input binding wrote the same doubled name. +func TestResolveAssociationAttributePath_QualifiedFinalAttribute_2671(t *testing.T) { + tests := []struct { + name, path, wantFinal, wantDest string + }{ + {"fully qualified (the report)", "System.Session_User/System.User.Name", "System.User.Name", "System.User"}, + {"entity-qualified, read in the destination's module", "System.Session_User/User.Name", "System.User.Name", "System.User"}, + {"qualified with the specialization stepped to", "System.Session_User/MyFirstModule.Account/MyFirstModule.Account.FullName", "MyFirstModule.Account.FullName", "MyFirstModule.Account"}, + {"inherited, qualified with the declaring generalization", "System.Session_User/MyFirstModule.Account/System.User.Name", "System.User.Name", "MyFirstModule.Account"}, + {"inherited, qualified with the specialization", "System.Session_User/MyFirstModule.Account/MyFirstModule.Account.Name", "System.User.Name", "MyFirstModule.Account"}, + {"bare (control)", "System.Session_User/Name", "System.User.Name", "System.User"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + finalQN, steps, ok := specializationStepPB("System.Session").resolveAssociationAttributePath(tc.path) + if !ok { + t.Fatalf("path %q unresolved", tc.path) + } + if finalQN != tc.wantFinal { + t.Errorf("finalQN = %q, want %q", finalQN, tc.wantFinal) + } + if len(steps) != 1 || steps[0].Association != "System.Session_User" || steps[0].DestinationEntity != tc.wantDest { + t.Errorf("steps = %+v, want one {System.Session_User → %s}", steps, tc.wantDest) + } + }) + } + + // An attribute qualified with an entity the path does not arrive at is not + // one the runtime can read there. Unresolved, rather than written as an + // attribute of the wrong entity. + for _, path := range []string{ + "System.Session_User/MyFirstModule.Other.FullName", + "System.Session_User/MyFirstModule.Account.FullName", // a specialization, not stepped to + } { + if final, _, ok := specializationStepPB("System.Session").resolveAssociationAttributePath(path); ok { + t.Errorf("%q resolved to %q; the path does not reach that entity", path, final) + } + } +} diff --git a/mdl/executor/cmd_pages_builder_v3.go b/mdl/executor/cmd_pages_builder_v3.go index 27ae9ab3f3..59140290e0 100644 --- a/mdl/executor/cmd_pages_builder_v3.go +++ b/mdl/executor/cmd_pages_builder_v3.go @@ -38,9 +38,13 @@ func (pb *pageBuilder) buildPageV3(s *ast.CreatePageStmtV3) (*pages.Page, error) containerID = folderID } + pageID := pb.selfPageID + if pageID == "" { + pageID = model.ID(types.GenerateID()) + } page := &pages.Page{ BaseElement: model.BaseElement{ - ID: model.ID(types.GenerateID()), + ID: pageID, TypeName: "Forms$Page", }, ContainerID: containerID, @@ -2667,6 +2671,25 @@ func (pb *pageBuilder) resolveAssociationPathFrom(path, start string) (finalQN s afterAssociation = true } + // A final attribute written qualified (`Assoc/Mod.Entity.Attr`, or + // `Assoc/Entity.Attr` in the destination's module) names the entity the + // path arrived at or one it inherits from. Qualified again below, it was + // stored as `Mod.Entity.Mod.Entity.Attr` and mxbuild crashed loading the + // project (ako/mxcli#2671). An entity the path does not reach is not one + // the runtime can read the attribute on: unresolved. + if i := strings.LastIndex(attrName, "."); i >= 0 { + qual := attrName[:i] + if !strings.Contains(qual, ".") { + if dot := strings.Index(current, "."); dot > 0 { + qual = current[:dot] + "." + qual + } + } + if !pb.entityIsOrDescendsFrom(current, qual) { + return "", nil, false + } + attrName = attrName[i+1:] + } + // The final attribute is qualified with the entity that DECLARES it, which // for an inherited attribute is an ancestor of the association's destination // — same rule (and same CE1613 when broken) as a direct binding. diff --git a/mdl/executor/cmd_pages_create_v3.go b/mdl/executor/cmd_pages_create_v3.go index 6e07192b0b..acdcf6ef78 100644 --- a/mdl/executor/cmd_pages_create_v3.go +++ b/mdl/executor/cmd_pages_create_v3.go @@ -7,6 +7,7 @@ import ( "github.com/mendixlabs/mxcli/mdl/ast" mdlerrors "github.com/mendixlabs/mxcli/mdl/errors" + "github.com/mendixlabs/mxcli/mdl/types" "github.com/mendixlabs/mxcli/model" "github.com/mendixlabs/mxcli/sdk/pages" ) @@ -128,6 +129,16 @@ func execCreatePageV3(ctx *ExecContext, s *ast.CreatePageStmtV3) error { tolerateDanglingRefs: s.Excluded || existingExcluded, } + // The ID the page is stored under, known before the build so the page can + // resolve a reference to itself (ako/mxcli#2677). A rewrite reuses the first + // stored page's ID, as the write below does. + pb.selfPage = s.Name.Module + "." + s.Name.Name + if len(pagesToDelete) > 0 { + pb.selfPageID = pagesToDelete[0] + } else { + pb.selfPageID = model.ID(types.GenerateID()) + } + // A rewrite of one stored page keeps the pluggable widgets the statement // did not change (#721 L4). Duplicates are skipped: which one describe // would print is then not the one being rewritten. diff --git a/mdl/executor/external_entity_edm_date_2676_test.go b/mdl/executor/external_entity_edm_date_2676_test.go new file mode 100644 index 0000000000..570d11d64a --- /dev/null +++ b/mdl/executor/external_entity_edm_date_2676_test.go @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/backend/mock" + "github.com/mendixlabs/mxcli/mdl/types" + "github.com/mendixlabs/mxcli/mdl/visitor" + "github.com/mendixlabs/mxcli/model" + "github.com/mendixlabs/mxcli/sdk/domainmodel" +) + +// ako/mxcli#2676: "`create external entities from …` imports an `Edm.Date` +// property as a **localized** DateTime. Mendix allows an `Edm.Date` attribute +// only unlocalized, so the build fails: CE4598 Cannot localize this attribute." +// Measured on mx check 11.14.0: "Cannot localize this attribute. The remote +// type of this attribute is 'Edm.Date', which does not support Localize." +// Edm.DateTimeOffset stays localized, as Studio Pro imports it. +const clientContract2676 = ` + + + + + + + + + + + + +` + +type import2676 struct { + created map[string]*domainmodel.Entity + updated map[string]*domainmodel.Entity +} + +func backend2676(t *testing.T, existing []*domainmodel.Entity) (*ExecContext, import2676) { + t.Helper() + mod := mkModule("M") + svc := &model.ConsumedODataService{BaseElement: model.BaseElement{ID: nextID("cos")}, ContainerID: mod.ID, + Name: "Crm", MetadataUrl: "http://localhost/$metadata", ODataVersion: "4.0", Metadata: clientContract2676} + h := mkHierarchy(mod) + withContainer(h, svc.ContainerID, mod.ID) + dm := &domainmodel.DomainModel{Entities: existing} + dm.ID = nextID("dm") + r := import2676{created: map[string]*domainmodel.Entity{}, updated: map[string]*domainmodel.Entity{}} + mb := &mock.MockBackend{ + IsConnectedFunc: func() bool { return true }, + ListModulesFunc: func() ([]*model.Module, error) { return []*model.Module{mod}, nil }, + ListConsumedODataServicesFunc: func() ([]*model.ConsumedODataService, error) { + return []*model.ConsumedODataService{svc}, nil + }, + GetDomainModelFunc: func(model.ID) (*domainmodel.DomainModel, error) { return dm, nil }, + CreateEntityFunc: func(_ model.ID, e *domainmodel.Entity) error { + r.created[e.Name] = e + dm.Entities = append(dm.Entities, e) + return nil + }, + UpdateEntityFunc: func(_ model.ID, e *domainmodel.Entity) error { r.updated[e.Name] = e; return nil }, + ProjectVersionFunc: func() *types.ProjectVersion { + return &types.ProjectVersion{MajorVersion: 11, MinorVersion: 14, ProductVersion: "11.14.0"} + }, + } + ctx, _ := newMockCtx(t, withBackend(mb), withHierarchy(h)) + return ctx, r +} + +// assertDateLocalize2676 checks dateOfBirth (Edm.Date) is not localized and +// lastSeen (Edm.DateTimeOffset) still is. +func assertDateLocalize2676(t *testing.T, e *domainmodel.Entity) { + t.Helper() + if e == nil { + t.Fatal("entity not written") + } + want := map[string]bool{"dateOfBirth": false, "lastSeen": true} + for _, a := range e.Attributes { + w, ok := want[a.Name] + if !ok { + continue + } + delete(want, a.Name) + dt, isDT := a.Type.(*domainmodel.DateTimeAttributeType) + if !isDT { + t.Errorf("%s: type %T, want DateTime", a.Name, a.Type) + continue + } + if dt.LocalizeDate != w { + t.Errorf("%s (%s): LocalizeDate = %v, want %v — CE4598 Cannot localize this attribute", + a.Name, a.RemoteType, dt.LocalizeDate, w) + } + } + if len(want) != 0 { + t.Errorf("attributes missing: %v", want) + } +} + +func TestBulkImportEdmDateNotLocalized_2676(t *testing.T) { + ctx, r := backend2676(t, nil) + stmt := &ast.CreateExternalEntitiesStmt{ + ServiceRef: ast.QualifiedName{Module: "M", Name: "Crm"}, + TargetModule: "M", + CreateOrModify: true, + } + assertNoError(t, createExternalEntities(ctx, stmt)) + assertDateLocalize2676(t, r.created["Client"]) +} + +func runSingle2676(t *testing.T, existing []*domainmodel.Entity) import2676 { + t.Helper() + ctx, r := backend2676(t, existing) + prog, errs := visitor.Build(`create or modify external entity M.Client from consumed odata service M.Crm (EntitySet: 'Clients') ( + ClientId: Long, + dateOfBirth: DateTime, + lastSeen: DateTime +);`) + if len(errs) > 0 { + t.Fatalf("parse: %v", errs) + } + assertNoError(t, execCreateExternalEntity(ctx, prog.Statements[0].(*ast.CreateExternalEntityStmt))) + return r +} + +func TestSingleExternalEntityEdmDateNotLocalized_2676(t *testing.T) { + assertDateLocalize2676(t, runSingle2676(t, nil).created["Client"]) +} + +// An entity imported by an earlier build holds dateOfBirth localized. A rewrite +// that does not state `localized` keeps a stored LocalizeDate (#1373), which +// would keep the CE4598 an import put there: the remote type decides instead. +func TestSingleExternalEntityRewriteRepairsEdmDate_2676(t *testing.T) { + stored := &domainmodel.Entity{ + Name: "Client", + Source: "Rest$ODataRemoteEntitySource", + RemoteServiceName: "M.Crm", + RemoteEntitySet: "Clients", + RemoteEntityName: "Client", + Attributes: []*domainmodel.Attribute{ + {Name: "ClientId", Type: &domainmodel.LongAttributeType{}, RemoteName: "Id", RemoteType: "Edm.Int64"}, + {Name: "dateOfBirth", Type: &domainmodel.DateTimeAttributeType{LocalizeDate: true}, RemoteName: "dateOfBirth", RemoteType: "Edm.Date"}, + {Name: "lastSeen", Type: &domainmodel.DateTimeAttributeType{LocalizeDate: true}, RemoteName: "lastSeen", RemoteType: "Edm.DateTimeOffset"}, + }, + } + stored.ID = nextID("ent") + for _, a := range stored.Attributes { + a.ID = nextID("attr") + } + assertDateLocalize2676(t, runSingle2676(t, []*domainmodel.Entity{stored}).updated["Client"]) +} diff --git a/mdl/executor/page_shows_itself_2677_test.go b/mdl/executor/page_shows_itself_2677_test.go new file mode 100644 index 0000000000..bd88cd3c32 --- /dev/null +++ b/mdl/executor/page_shows_itself_2677_test.go @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/backend/mock" + "github.com/mendixlabs/mxcli/mdl/types" + "github.com/mendixlabs/mxcli/mdl/visitor" + "github.com/mendixlabs/mxcli/model" + "github.com/mendixlabs/mxcli/sdk/pages" +) + +// ako/mxcli#2677: "A page that opens itself … cannot be created after a `drop +// page`: Error: failed to build page: failed to build widget: failed to resolve +// page: page not found: M.Driver". The page is built before it is created, and +// its show page action looked itself up among the stored pages. Measured on +// dae7f09: a plain `create page` of such a page fails the same way, with no drop +// at all; only a rewrite in place worked, because the old page was still listed. +const pageShowsItself2677 = `create or modify page M.Driver (Title: 'Driver', Layout: M.Default) { + actionbutton btnPeer (Caption: 'Peer', action: show page M.Driver) +}` + +func runPageShowsItself(t *testing.T, stored []*pages.Page) (created, updated *pages.Page) { + t.Helper() + return runPageShowsItselfIn(t, mkModule("M"), stored) +} + +// After `drop page M.Driver` (or before it ever existed) no page of that name +// is stored: the page must still resolve its own name. +func TestPageThatShowsItselfCanBeCreated_2677(t *testing.T) { + created, _ := runPageShowsItself(t, nil) + if created == nil { + t.Fatal("page not created") + } + if created.Name != "Driver" || created.ID == "" { + t.Errorf("created = %q (%q)", created.Name, created.ID) + } +} + +// Control: the in-place rewrite, which worked before, keeps the stored ID. +func TestPageThatShowsItselfRewriteInPlace_2677(t *testing.T) { + mod := mkModule("M") + old := &pages.Page{BaseElement: model.BaseElement{ID: nextID("page"), TypeName: "Forms$Page"}, + ContainerID: mod.ID, Name: "Driver"} + _, updated := runPageShowsItselfIn(t, mod, []*pages.Page{old}) + if updated == nil || updated.ID != old.ID { + t.Fatalf("updated = %+v, want the stored page %q rewritten", updated, old.ID) + } +} + +func runPageShowsItselfIn(t *testing.T, mod *model.Module, stored []*pages.Page) (created, updated *pages.Page) { + t.Helper() + h := mkHierarchy(mod) + mb := &mock.MockBackend{ + IsConnectedFunc: func() bool { return true }, + ListModulesFunc: func() ([]*model.Module, error) { return []*model.Module{mod}, nil }, + ListPagesFunc: func() ([]*pages.Page, error) { return stored, nil }, + ListLayoutsFunc: func() ([]*pages.Layout, error) { + return []*pages.Layout{{BaseElement: model.BaseElement{ID: nextID("layout")}, ContainerID: mod.ID, Name: "Default"}}, nil + }, + CreatePageFunc: func(p *pages.Page) error { created = p; return nil }, + UpdatePageFunc: func(p *pages.Page) error { updated = p; return nil }, + ProjectVersionFunc: func() *types.ProjectVersion { + return &types.ProjectVersion{MajorVersion: 11, MinorVersion: 14, ProductVersion: "11.14.0"} + }, + } + ctx, _ := newMockCtx(t, withBackend(mb), withHierarchy(h)) + prog, errs := visitor.Build(pageShowsItself2677) + if len(errs) > 0 { + t.Fatalf("parse: %v", errs) + } + assertNoError(t, execCreatePageV3(ctx, prog.Statements[0].(*ast.CreatePageStmtV3))) + return created, updated +} + +// The same page in the script that #2677 reports: created, dropped, created +// again. Each create's reference to itself resolves in that statement, so +// neither the project-aware check nor MDL-PAGE01 may call it a forward +// reference. Before the fix --references refused it: "statement 1: page +// M.Driver references page M.Driver before it is created". +const pageShowsItselfDropCreate2677 = `create page M.Driver (title: 'Driver', layout: Atlas_Core.Atlas_Default) { + actionbutton btnPeer (caption: 'Peer', action: show page M.Driver) +} +drop page M.Driver; +create page M.Driver (title: 'Driver', layout: Atlas_Core.Atlas_Default) { + actionbutton btnPeer (caption: 'Peer', action: show page M.Driver) +}` + +func TestValidateSelfPageRefIsNotForward_2677(t *testing.T) { + prog, errs := visitor.Build(pageShowsItselfDropCreate2677) + if len(errs) > 0 { + t.Fatalf("parse: %v", errs) + } + if got := validateForwardPageRefs(forwardRefCtx(t), prog); len(got) != 0 { + t.Errorf("--references: %v", got) + } + if got := ValidateScriptPageOrder(prog); len(got) != 0 { + t.Errorf("MDL-PAGE01: %+v", got) + } +} + +// Control: a reference to ANOTHER page created later is still reported. +func TestValidateForwardRefToOtherPageStillReported_2677(t *testing.T) { + prog, errs := visitor.Build(`create page M.Driver (title: 'Driver', layout: Atlas_Core.Atlas_Default) { + actionbutton btnTeam (caption: 'Team', action: show page M.Team) +} +create page M.Team (title: 'Team', layout: Atlas_Core.Atlas_Default) { + actionbutton btnDriver (caption: 'Driver', action: show page M.Driver) +}`) + if len(errs) > 0 { + t.Fatalf("parse: %v", errs) + } + if got := validateForwardPageRefs(forwardRefCtx(t), prog); len(got) != 1 { + t.Errorf("--references: want 1 forward reference (M.Team), got %v", got) + } + if got := ValidateScriptPageOrder(prog); len(got) != 1 { + t.Errorf("MDL-PAGE01: want 1 forward reference (M.Team), got %+v", got) + } +} diff --git a/mdl/executor/validate.go b/mdl/executor/validate.go index 42b09a3083..c35ff0368d 100644 --- a/mdl/executor/validate.go +++ b/mdl/executor/validate.go @@ -707,8 +707,9 @@ func validateForwardPageRefs(ctx *ExecContext, prog *ast.Program) []error { refs := &widgetRefCollector{} refs.collectFromWidgets(widgets) refs.dedupe() + self := selfPageName(stmt) for _, ref := range refs.pages { - if known[ref] || definedEarlier[ref] { + if known[ref] || definedEarlier[ref] || ref == self { continue } // Unknown to both project and earlier-in-script. A truly-missing page @@ -728,6 +729,16 @@ func validateForwardPageRefs(ctx *ExecContext, prog *ast.Program) []error { return errors } +// selfPageName is the qualified name of the page a statement creates, or "" for +// any other statement. A page's reference to itself resolves in the statement +// that creates it, so it is never a forward reference (ako/mxcli#2677). +func selfPageName(stmt ast.Statement) string { + if s, ok := stmt.(*ast.CreatePageStmtV3); ok && s.Name.Module != "" { + return s.Name.String() + } + return "" +} + // pageDefinedAfter reports whether a page named ref is created by a // CreatePageStmtV3 at a statement index greater than fromIdx. func pageDefinedAfter(prog *ast.Program, ref string, fromIdx int) bool { diff --git a/mdl/executor/validate_agent_left_unset.go b/mdl/executor/validate_agent_left_unset.go index a5e516fb6e..f03e7ffc7e 100644 --- a/mdl/executor/validate_agent_left_unset.go +++ b/mdl/executor/validate_agent_left_unset.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/linter" ) // validateAgentDocumentsLeftUnset is the project half of MDL-AGENT02 and @@ -23,8 +24,8 @@ import ( // keep, an earlier create or alter decides what a later statement keeps. // A plain create is the static rules' case and is not reported twice. // -// The agent half applies only when AgentEditorCommons reads selectedModel -// (2.2 and later); every measured version reads the endpoint. +// The agent half follows the project's Agent Editor version +// (agentSelectedModelVerdict); every measured version reads the endpoint. func validateAgentDocumentsLeftUnset(ctx *ExecContext, prog *ast.Program, sc *scriptContext) []error { if ctx == nil || prog == nil || sc == nil || !ctx.Connected() { return nil @@ -32,7 +33,7 @@ func validateAgentDocumentsLeftUnset(ctx *ExecContext, prog *ast.Program, sc *sc var errs []error agentHas := map[string]bool{} svcHas := map[string]bool{} - readsSelected := -1 // unknown until an agent needs it + commons, versionKnown := "", false // read when an agent first needs it for i, stmt := range prog.Statements { switch s := stmt.(type) { case *ast.CreateAgentStmt: @@ -51,18 +52,16 @@ func validateAgentDocumentsLeftUnset(ctx *ExecContext, prog *ast.Program, sc *sc if has || !s.CreateOrModify { continue } - if readsSelected < 0 { - readsSelected = 0 - if agentEditorReadsSelectedModel(ctx) { - readsSelected = 1 - } + if !versionKnown { + commons, versionKnown = agentEditorCommonsVersion(ctx.Backend), true } - if readsSelected != 1 { + sev, report := agentSelectedModelVerdict(commons, s.Model != nil) + if !report { continue } msg := fmt.Sprintf("%s: %s. Add SelectedModel: ''", agentSelectedModelRule, agentSelectedModelMissing("is left with", qn, s.Model != nil)) - if s.Model != nil { + if sev == linter.SeverityError { errs = append(errs, fmt.Errorf("statement %d: %s", i+1, msg)) } else { sc.warnings = append(sc.warnings, msg) @@ -105,21 +104,3 @@ func validateAgentDocumentsLeftUnset(ctx *ExecContext, prog *ast.Program, sc *sc } return errs } - -// agentEditorReadsSelectedModel reports whether the project's -// AgentEditorCommons requires an agent's selectedModel: 2.2.1 and 2.6.0 -// validate it, 1.1.0 does not read it (ako/mxcli#2031). A project whose -// version is unknown (no Marketplace version recorded) counts as reading it, -// as every current release does. -func agentEditorReadsSelectedModel(ctx *ExecContext) bool { - modules, err := ctx.Backend.ListModules() - if err != nil { - return true - } - for _, m := range modules { - if m.Name == "AgentEditorCommons" && m.AppStoreVersion != "" { - return compareVersion(m.AppStoreVersion, "2.2.0") >= 0 - } - } - return true -} diff --git a/mdl/executor/validate_agent_selected_model.go b/mdl/executor/validate_agent_selected_model.go index ebfeb9af95..01ade72e36 100644 --- a/mdl/executor/validate_agent_selected_model.go +++ b/mdl/executor/validate_agent_selected_model.go @@ -7,6 +7,7 @@ import ( "github.com/mendixlabs/mxcli/mdl/ast" "github.com/mendixlabs/mxcli/mdl/linter" + "github.com/mendixlabs/mxcli/model" ) // agentSelectedModelRule flags an agent created without a selected model @@ -35,18 +36,53 @@ func agentSelectedModelMissing(verb string, name string, hasModel bool) string { return msg } +// agentSelectedModelVerdict is MDL-AGENT02's severity for an agent with no +// selected model, given the project's AgentEditorCommons version ("" when +// there is no project or it records none: judged as the current releases). +// ok is false when that version has nothing to say. Measured from the +// packages' extension code and startup flows (ako/mxcli#2294): +// +// - before 1.3: neither AE018 nor the import reads selectedModel; +// - 1.3 to 2.1: AE018 ("Model version is required for an agent") for an +// agent with a Model — the extension's `model && !selectedModel`; +// - 2.2 and later: AE018, and the startup import refuses any agent without +// one, which stops the import of every agent. +// +// Both phases ask this, so check -p, exec and the project phase agree. +func agentSelectedModelVerdict(commonsVersion string, hasModel bool) (sev linter.Severity, ok bool) { + ae018, importReads := true, true + if commonsVersion != "" { + ae018 = compareVersion(commonsVersion, "1.3.0") >= 0 + importReads = compareVersion(commonsVersion, "2.2.0") >= 0 + } + switch { + case hasModel && ae018: + return linter.SeverityError, true + case importReads: + return linter.SeverityWarning, true + } + return 0, false +} + // ValidateAgentSelectedModel flags a create agent with no SelectedModel: an -// error when it names a Model, a warning when it does not. -func ValidateAgentSelectedModel(prog *ast.Program) []linter.Violation { +// error when it names a Model, a warning when it does not, as far as the +// project's Agent Editor version cares (agentSelectedModelVerdict). +// commonsVersion reports that version; it is asked only when an agent needs +// it, and nil means no project. +func ValidateAgentSelectedModel(prog *ast.Program, commonsVersion func() string) []linter.Violation { var out []linter.Violation + version, asked := "", false for _, stmt := range prog.Statements { s, ok := stmt.(*ast.CreateAgentStmt) if !ok || s.CreateOrModify || (s.SelectedModel != nil && *s.SelectedModel != "") { continue } - sev := linter.SeverityWarning - if s.Model != nil { - sev = linter.SeverityError + if !asked && commonsVersion != nil { + version, asked = commonsVersion(), true + } + sev, report := agentSelectedModelVerdict(version, s.Model != nil) + if !report { + continue } out = append(out, linter.Violation{ RuleID: agentSelectedModelRule, @@ -55,8 +91,28 @@ func ValidateAgentSelectedModel(prog *ast.Program) []linter.Violation { Location: linter.Location{DocumentType: "agent", DocumentName: s.Name.String()}, Suggestion: "Add SelectedModel: '', the id of a model the Model document's resource offers " + "(e.g. 'eu.anthropic.claude-sonnet-5'). With the app running, MxGenAIConnector.MxCloudDeployedModel " + - "lists them. Only Agent Editor 1.x ignores it.", + "lists them. Agent Editor before 1.3 ignores it.", }) } return out } + +// agentEditorCommonsVersion is the Marketplace version of the project's +// AgentEditorCommons, or "" when there is none or it records no version. +func agentEditorCommonsVersion(b interface { + ListModules() ([]*model.Module, error) +}) string { + if b == nil { + return "" + } + modules, err := b.ListModules() + if err != nil { + return "" + } + for _, m := range modules { + if m.Name == "AgentEditorCommons" { + return m.AppStoreVersion + } + } + return "" +} diff --git a/mdl/executor/validate_agent_selected_model_test.go b/mdl/executor/validate_agent_selected_model_test.go index bf4da66fb5..7e2b2a096f 100644 --- a/mdl/executor/validate_agent_selected_model_test.go +++ b/mdl/executor/validate_agent_selected_model_test.go @@ -22,7 +22,7 @@ create agent M.NoModel (UsageType: Task); `) got := map[string]string{} sev := map[string]linter.Severity{} - for _, v := range ValidateAgentSelectedModel(prog) { + for _, v := range ValidateAgentSelectedModel(prog, nil) { if v.RuleID != agentSelectedModelRule { t.Errorf("rule %s", v.RuleID) } diff --git a/mdl/executor/validate_agent_selected_model_version_test.go b/mdl/executor/validate_agent_selected_model_version_test.go new file mode 100644 index 0000000000..f0e15d0638 --- /dev/null +++ b/mdl/executor/validate_agent_selected_model_version_test.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "testing" + + "github.com/mendixlabs/mxcli/mdl/linter" +) + +// ako/mxcli#2294: the syntax phase errored for every Agent Editor version, so +// check -p and exec refused a create agent on a 1.x project that the project +// phase accepted. Measured from the packages' own extension code: AE018 (an +// agent with a Model and no selectedModel) first appears in 1.3.0, and the +// startup import reads selectedModel from 2.2. With a project the syntax phase +// now gives the same verdict as the project phase; without one it is unchanged. +func TestValidateAgentSelectedModel_FollowsTheProjectsAgentEditor(t *testing.T) { + prog := parseMDL(t, ` +create agent M.WithModel (UsageType: Task, Model: M.Model); +create agent M.NoModel (UsageType: Task); +`) + none := linter.Severity(-1) + for _, tc := range []struct { + version string // "" = no project, or no version recorded + withModel linter.Severity + noModel linter.Severity + }{ + {"", linter.SeverityError, linter.SeverityWarning}, // control: unchanged without a project + {"1.1.0", none, none}, // neither AE018 nor the import reads it + {"1.2.0", none, none}, // + {"1.3.0", linter.SeverityError, none}, // AE018 only + {"2.1.0", linter.SeverityError, none}, // + {"2.2.1", linter.SeverityError, linter.SeverityWarning}, // AE018 and the import refusal + {"2.6.0", linter.SeverityError, linter.SeverityWarning}, // + } { + v := tc.version + got := map[string]linter.Severity{"M.WithModel": none, "M.NoModel": none} + for _, viol := range ValidateAgentSelectedModel(prog, func() string { return v }) { + got[viol.Location.DocumentName] = viol.Severity + } + if got["M.WithModel"] != tc.withModel || got["M.NoModel"] != tc.noModel { + t.Errorf("Agent Editor %q: with Model %v, no Model %v; want %v, %v", + v, got["M.WithModel"], got["M.NoModel"], tc.withModel, tc.noModel) + } + } +} + +// The project phase used one threshold, 2.2, and so stayed silent on 1.3–2.1, +// where Studio Pro reports AE018 for an agent with a Model. +func TestLeftUnset_AE018FromAgentEditor13(t *testing.T) { + withModel := `create or modify agent M.Stored ( UsageType: Task, Model: M.Model, SystemPrompt: 'x', UserPrompt: 'y' );` + assertLeftUnset(t, leftUnsetWarnings(t, "1.3.0", false, "mdl 1;\n"+withModel), + "ERROR statement 1: MDL-AGENT02: agent M.Stored") + // No Model: AE018 does not apply, and 1.3 does not read selectedModel at import. + assertLeftUnset(t, leftUnsetWarnings(t, "1.3.0", false, "mdl 1;\n"+newAgent)) + // Before 1.3: nothing. + assertLeftUnset(t, leftUnsetWarnings(t, "1.2.0", false, "mdl 1;\n"+withModel)) +} diff --git a/mdl/executor/validate_page_order.go b/mdl/executor/validate_page_order.go index 4e6d7e886d..d6980e053b 100644 --- a/mdl/executor/validate_page_order.go +++ b/mdl/executor/validate_page_order.go @@ -40,8 +40,9 @@ func ValidateScriptPageOrder(prog *ast.Program) []linter.Violation { refs := &widgetRefCollector{} refs.collectFromWidgets(widgets) refs.dedupe() + self := selfPageName(stmt) for _, ref := range refs.pages { - if createdEarlier(prog, ref, i) || !plainCreateAfter(prog, ref, i) { + if ref == self || createdEarlier(prog, ref, i) || !plainCreateAfter(prog, ref, i) { continue } out = append(out, linter.Violation{ diff --git a/mdl/executor/validate_program.go b/mdl/executor/validate_program.go index 69d2a19a66..357251fc37 100644 --- a/mdl/executor/validate_program.go +++ b/mdl/executor/validate_program.go @@ -390,7 +390,14 @@ func ValidateProgram(prog *ast.Program, projectPath string) []linter.Violation { // shows in Studio Pro (ako/mxcli#2023). violations = append(violations, ValidateAgentProviders(prog)...) violations = append(violations, ValidateAgentUsageTypes(prog)...) - violations = append(violations, ValidateAgentSelectedModel(prog)...) + // MDL-AGENT02 depends on the project's Agent Editor version; without a + // project it judges as the current releases (ako/mxcli#2294). + violations = append(violations, ValidateAgentSelectedModel(prog, func() string { + if b := project(); b != nil { + return agentEditorCommonsVersion(b) + } + return "" + })...) violations = append(violations, ValidateConsumedMCPEndpoint(prog)...) // An agent value longer than the Agent Commons attribute it is copied // into fails the startup import and leaves the old agent in use (#2211). diff --git a/mdl/executor/widget_describe.go b/mdl/executor/widget_describe.go index 9ecaaafe8b..40cfc0a596 100644 --- a/mdl/executor/widget_describe.go +++ b/mdl/executor/widget_describe.go @@ -63,6 +63,7 @@ func DescribeWidget(arg, projectPath string) (*WidgetDescription, error) { desc.Name = wd.Name desc.Version = wd.Version desc.Source = "project .mpk" + desc.VersionNote = installedVersionNote(filepath.Base(mpkPath), wd.Version) desc.Properties = propsFromMPK(wd) desc.Rules, desc.RuleCoverage = rulesFromProject(mpkPath, widgetID) } @@ -81,6 +82,7 @@ func DescribeWidget(arg, projectPath string) (*WidgetDescription, error) { desc.Name = tmpl.Name desc.Version = tmpl.Version desc.Source = "embedded template" + desc.VersionNote = embeddedVersionNote(tmpl.Version) desc.Properties = propsFromTemplate(tmpl.Type) if def != nil { desc.Rules = rulesFromDef(def.PropertyVisibility) @@ -140,6 +142,9 @@ type WidgetDescription struct { Properties []DescribedProperty `json:"properties"` Rules []DescribedRule `json:"dynamicRules"` RuleCoverage string `json:"ruleCoverage,omitempty"` + // VersionNote says which version of the widget the properties and the + // example were read from, and how to get another version's (#2586). + VersionNote string `json:"versionNote,omitempty"` // Containers a widget's body can hold: child slots (a curly-brace block of // widgets) and object lists (repeating entries). Reported with whether MDL // can currently express each one, which is NOT a given — see @@ -169,6 +174,30 @@ type WidgetDescription struct { evaluated bool } +// installedVersionNote is the note for a description read from the project's +// package. Another version can add, drop or rename properties (Maps 5.0.0 has +// no `advanced`, 3.2.2 does), and the example names them, so it holds for this +// version alone. A replaced package is picked up on the next read: the +// project's widget definitions refresh when it changes (#2155), so describing +// again is all an upgrade needs. +func installedVersionNote(mpk, version string) string { + v := version + if v == "" { + v = "of unknown version" + } + return fmt.Sprintf("read from %s (%s) installed in this project; the properties and the example hold for that version only. After installing another version, describe again", mpk, v) +} + +// embeddedVersionNote is the note for a description from mxcli's own template, +// which is one version, not necessarily the project's. +func embeddedVersionNote(version string) string { + v := "" + if version != "" { + v = " (" + version + ")" + } + return "read from mxcli's embedded template" + v + "; the project may have another version installed. Pass -p to describe the installed one" +} + // evaluatedCoverageText is the coverage note once the package's getProperties // has run: the listed rules are what could be READ from the source, and are no // longer the limit of what check and exec know — they run the function itself. @@ -516,6 +545,9 @@ func PrintWidgetDescription(out io.Writer, d WidgetDescription) { } fmt.Fprintf(out, " Kind: %s\n", d.Kind) fmt.Fprintf(out, " Source: %s\n", d.Source) + if d.VersionNote != "" { + fmt.Fprintf(out, " Note: %s\n", d.VersionNote) + } fmt.Fprintf(out, "\nProperties (%d):\n", countProps(d.Properties)) printProps(out, d.Properties, 0) diff --git a/mdl/executor/widget_describe_version_note_test.go b/mdl/executor/widget_describe_version_note_test.go new file mode 100644 index 0000000000..4d6bf32632 --- /dev/null +++ b/mdl/executor/widget_describe_version_note_test.go @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" +) + +// The example and properties are read from ONE version of the widget: the +// installed package with -p, mxcli's embedded template without. Shown with no +// note, an example from Maps 3.2.2 (`advanced: false`) read as valid for the +// 5.0.0 about to be installed, which has no such property (ako/mxcli#2586). +func TestDescribeWidget_SaysWhichVersionTheExampleHoldsFor(t *testing.T) { + desc, err := DescribeWidget("com.mendix.widget.custom.Maps.Maps", "../../testdata/expr-checker/minimal.mpr") + if err != nil { + t.Fatalf("DescribeWidget maps: %v", err) + } + if desc.Source != "project .mpk" || desc.Version == "" { + t.Fatalf("want the fixture's installed Maps.mpk with a version, got source %q version %q", desc.Source, desc.Version) + } + for _, want := range []string{desc.Version, "Maps.mpk", "describe again"} { + if !strings.Contains(desc.VersionNote, want) { + t.Errorf("version note %q does not mention %q", desc.VersionNote, want) + } + } + var sb strings.Builder + PrintWidgetDescription(&sb, *desc) + if !strings.Contains(sb.String(), desc.VersionNote) { + t.Errorf("the note is not printed:\n%s", sb.String()) + } +} + +// Without a project the answer is the embedded template, which need not be the +// version the project has: the note says so and how to get the installed one. +func TestDescribeWidget_EmbeddedTemplateNoteNamesTheProjectFlag(t *testing.T) { + desc, err := DescribeWidget("combobox", "") + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"embedded", "-p"} { + if !strings.Contains(desc.VersionNote, want) { + t.Errorf("version note %q does not mention %q", desc.VersionNote, want) + } + } +} diff --git a/mods/companion/hooks/tree.ts b/mods/companion/hooks/tree.ts index 4c03547011..aafeea51de 100644 --- a/mods/companion/hooks/tree.ts +++ b/mods/companion/hooks/tree.ts @@ -100,11 +100,26 @@ export const diagramView = (svg: string, view: DiagramZoom, columnPx: number) => return { svg: newHead + rest, canPan: true, atStart: x <= 0, atEnd: x >= maxX, width: vw, height: Math.round(h) } } +// The desktop app keeps this much of a plugin command's output and drops the +// rest, so a tree that reaches it arrived cut off (#2601). +export const OUTPUT_LIMIT_BYTES = 4 * 1024 * 1024 + // parseTree reads `mxcli project-tree` output. export const parseTree = (stdout: string): TreeNode[] => { const start = stdout.indexOf('[') if (start < 0) throw new Error('project-tree printed no JSON') - const parsed: unknown = JSON.parse(stdout.slice(start)) + let parsed: unknown + try { + parsed = JSON.parse(stdout.slice(start)) + } catch (err) { + // Bytes, not characters: the limit counts what the process wrote. + const size = new TextEncoder().encode(stdout).length + if (size >= OUTPUT_LIMIT_BYTES * 0.99) { + const mb = (size / (1024 * 1024)).toFixed(1) + throw new Error(`project-tree output was cut off at ${mb} MB, the most a plugin command may print; this project is too large for the Project pane`) + } + throw new Error(`project-tree printed JSON that does not parse: ${err instanceof Error ? err.message : String(err)}`) + } if (!Array.isArray(parsed)) throw new Error('project-tree did not print a list') return parsed as TreeNode[] } diff --git a/mods/companion/tests/tree.test.ts b/mods/companion/tests/tree.test.ts index cbf7c071cf..0d15a64ef1 100644 --- a/mods/companion/tests/tree.test.ts +++ b/mods/companion/tests/tree.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from 'claude-code/testing' import type { TreeNode } from '../types' -import { assumeDescribable, changesModel, diagramView, nodeId, pageOf, parseDescribe, parseTree, pickMpr, touchesProjectFile, visibleRows } from '../hooks/tree' +import { assumeDescribable, changesModel, diagramView, nodeId, OUTPUT_LIMIT_BYTES, pageOf, parseDescribe, parseTree, pickMpr, touchesProjectFile, visibleRows } from '../hooks/tree' const TREE: TreeNode[] = [ { @@ -51,6 +51,15 @@ describe('parsing mxcli output', () => { expect(() => parseTree('Error: nope')).toThrow('no JSON') }) + test('parseTree says a tree cut off at the output limit is too large', () => { + const big = '[{"label":"' + 'x'.repeat(OUTPUT_LIMIT_BYTES) + expect(() => parseTree(big)).toThrow('cut off at 4.0 MB') + }) + + test('parseTree names malformed JSON below the limit as such', () => { + expect(() => parseTree('[{"label":')).toThrow('does not parse') + }) + test('parseDescribe returns the mdl field', () => { expect(parseDescribe('{"name":"M.X","type":"microflow","mdl":"mdl 1;\\n","executable":true}')).toBe('mdl 1;\n') })