From 2ea675654fa230f20b6e762d21bb94b53fcede73 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 13:28:55 +0000 Subject: [PATCH 1/5] fix: drop-down filter emptyOptionCaption follows its visibility (#2518) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every Data grid Drop-down filter mxcli created failed mx check with CE0463. Its editorConfig hides emptyOptionCaption behind `(filterable||multiSelect)`, a disjunctive guard the extractor did not lift, so the text template was never nulled while hidden; and while visible Studio Pro stores the shipped default text, where mxcli wrote an empty template. - lift a statement-level `(A||B…)&&hide(P)` as one rule per disjunct - carry DefaultTranslations on top-level property entries and use them when filling a visible, unset conditional text template - give the embedded template's emptyOptionCaption the shipped text Measured on mx check 11.14.0, 68 testapp pages copied as new pages: CE0463 9 -> 0, no new errors. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QiMsnXa9crge2qnSk9S7Zn --- ...ter-disjunctive-hide-and-shipped-text.json | 1 + CHANGELOG.md | 1 + .../bug-patterns/widget-type-object-drift.md | 13 ++ mdl/backend/widgetobj/builder.go | 8 ++ ...ble_texttemplate_translations_2518_test.go | 77 +++++++++++ .../editorconfig_disjunction_2518_test.go | 89 +++++++++++++ mdl/executor/editorconfig_extract.go | 121 ++++++++++++++++++ modelsdk/widgets/loader.go | 21 ++- .../mendix-11.6/datagrid-dropdown-filter.json | 14 +- ...template_default_translations_2518_test.go | 91 +++++++++++++ 10 files changed, 428 insertions(+), 8 deletions(-) create mode 100644 .claude/skills/fix-issue/findings/mdl-executor/2026-11-22-dropdown-filter-disjunctive-hide-and-shipped-text.json create mode 100644 mdl/backend/widgetobj/visible_texttemplate_translations_2518_test.go create mode 100644 mdl/executor/editorconfig_disjunction_2518_test.go create mode 100644 modelsdk/widgets/texttemplate_default_translations_2518_test.go diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-22-dropdown-filter-disjunctive-hide-and-shipped-text.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-22-dropdown-filter-disjunctive-hide-and-shipped-text.json new file mode 100644 index 0000000000..ff95a71f60 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-22-dropdown-filter-disjunctive-hide-and-shipped-text.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-11-22", "symptom": "every Data grid Drop-down filter mxcli created failed mx check 11.14.0 with CE0463 (9 on the 68-page testapp copy); mxcli docker check labelled them stale and update-widgets cleared them", "cause": "two gaps on emptyOptionCaption: the editorConfig hides it with `(e.filterable||e.multiSelect)&&hidePropertyIn(…)`, a disjunctive guard the extractor did not lift, so the hidden template was never nulled; and while visible Studio Pro stores the shipped default text (None/Niets) where the embedded template held an empty template and the visible fill wrote an empty one, because top-level property entries did not carry DefaultTranslations", "file": "mdl/executor/editorconfig_extract.go (disjunctiveGuard), modelsdk/widgets/loader.go (top-level DefaultTranslations), mdl/backend/widgetobj/builder.go (ApplyVisibilityRules), modelsdk/widgets/templates/mendix-11.6/datagrid-dropdown-filter.json", "fix": "lift a statement-level `(A||B…)&&hide(P)` as one rule per disjunct (exact: any firing rule hides); fill a visible unset conditional text template with the declared translations; give the template's emptyOptionCaption the shipped text", "insight": "the first path diff (Studio vs mxcli) showed only Object.Properties ORDER differences — a red herring, update-widgets does not reorder them. Diffing mxcli's widget against the same widget after `mx update-widgets` gave the one real change. Nulling the template alone moved the failures to the other filters, which is what showed the value depends on configuration; then the editorConfig named the rule. An empty template is not wrong everywhere: the text/number filters' screenReaderInputCaption ships text and mx check accepts an empty one", "refs": ["ako/mxcli#2518"], "test": "mdl/executor/editorconfig_disjunction_2518_test.go, mdl/backend/widgetobj/visible_texttemplate_translations_2518_test.go, modelsdk/widgets/texttemplate_default_translations_2518_test.go"} diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b336867cd..e8c4e140e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] ### Fixed +- **Data grid Drop-down filters no longer fail CE0463** (ako/mxcli#2518) — every drop-down filter mxcli created failed with "the definition of this widget has changed". Its `emptyOptionCaption` was written with an empty text, where Studio Pro stores none while `filterable` or `multiSelect` hides it and the widget's default text ("None") while it is visible. Rules that the widget editor writes as `(a || b) && hide(…)` are now read, and a visible text property that is left unset gets the widget's default text. Measured on mx check 11.14.0: 68 pages copied from the testapp went from 9 × CE0463 to 0. - **`check` rejects a JSON structure custom name that Mendix refuses** (ako/mxcli#1258) — a `custom name map` or `item of` name such as `1bad`, `has space`, `Größe`, `_`, an empty string, or a reserved word in any case (`Owner`, `ChangedDate`, `Type`, `Id`, `class`, `null`) passed `check` and `exec`, and the build reported CE9524 "invalid custom name". New MDL-JSON03, which needs no project. A member whose JSON key is invalid (`$type`, `research%3Aread`) still needs no custom name: its default is sanitised. Measured on MxBuild 11.16.1 over 90 names. - **Lint MPR017 and MPR019 no longer report external entities, and MPR017 counts mappings as writes** (ako/mxcli#2501, ako/mxcli#2502) — MPR019 told the owner of a frontend app to add 39 indexes, every one on an external entity whose table lives in the publishing app. MPR017 reported "can only ever be false" for an attribute assigned by a database-connection query's `Map:`, by an import mapping, or by an external service, none of which is a Change activity. External entities are skipped by both, and an import mapping's value elements and a query's mapped columns count as unknown writes. Export mappings, message definitions and view entities are not yet covered. - **A published REST service rewrite says which operations it removes** (ako/mxcli#2449, mendixlabs/mxcli#1903) — `create or modify published rest service` naming only a new operation deleted the stored ones, and exec said only "Modified". `check` and exec now warn with the operations removed (MDL-REST06), and `check` refuses `alter … add resource` with a stored resource's name and `drop resource` of a missing one, as exec does. diff --git a/docs-wiki/bug-patterns/widget-type-object-drift.md b/docs-wiki/bug-patterns/widget-type-object-drift.md index 903b886da6..f757c3942e 100644 --- a/docs-wiki/bug-patterns/widget-type-object-drift.md +++ b/docs-wiki/bug-patterns/widget-type-object-drift.md @@ -84,6 +84,19 @@ it should not. The corollary for fixtures: a test whose helper restates the default under test is not a fixture, it is the hypothesis wearing a test's clothes. +**A rule the extractor cannot read fails silently, and only in the configuration +it governs.** An unread editorConfig hide becomes "always visible", so the +template's value is written wherever the property should be null — or the reverse. +The value Studio Pro stores also depends on the configuration: one text property +held `null` on the filters where it was hidden and the shipped default text on the +others. A fix that copies one Studio Pro instance's value just moves the failures +to the other filters (#2518). `mxcli widget describe` prints "N of M editor +hide-rules recognized", and each one it misses is a candidate. The fastest way to +find the property is to diff mxcli's widget against **the same widget after +`mx update-widgets`**, not against a Studio Pro reference. That diff contains only +what the package rejects; the reference diff also carries order and copy +differences that do not matter. + **Where a property is an enumeration, compare against the package's `enumerationValue` *keys*, not its captions.** Both sides are plain strings, so nothing else compares them and a caption-shaped value is stored and built without diff --git a/mdl/backend/widgetobj/builder.go b/mdl/backend/widgetobj/builder.go index 52b929f11d..11c21d0a4f 100644 --- a/mdl/backend/widgetobj/builder.go +++ b/mdl/backend/widgetobj/builder.go @@ -988,12 +988,20 @@ func ApplyVisibilityRules(object bson.D, propertyTypeIDs map[string]pages.Proper for _, key := range conditional { isHidden := hidden[key] + shipped := propertyTypeIDs[key].DefaultTranslations object = updateWidgetPropertyValue(object, propertyTypeIDs, key, func(val bson.D) bson.D { if isHidden { return setBSONField(val, "TextTemplate", nil) } // Never clobber real content — only fill in the absent template. + // With shipped default text, the template carries it: that is what + // `mx update-widgets` writes for the Drop-down filter's visible + // emptyOptionCaption, and an empty one there is CE0463 too + // (ako/mxcli#2518). if bsonFieldIsNil(val, "TextTemplate") { + if len(shipped) > 0 { + return setBSONField(val, "TextTemplate", buildClientTemplateWithTranslations(shipped)) + } return setBSONField(val, "TextTemplate", BuildEmptyClientTemplate()) } return val diff --git a/mdl/backend/widgetobj/visible_texttemplate_translations_2518_test.go b/mdl/backend/widgetobj/visible_texttemplate_translations_2518_test.go new file mode 100644 index 0000000000..922e767e04 --- /dev/null +++ b/mdl/backend/widgetobj/visible_texttemplate_translations_2518_test.go @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 + +package widgetobj + +import ( + "testing" + + "go.mongodb.org/mongo-driver/v2/bson" + + "github.com/mendixlabs/mxcli/mdl/types" + "github.com/mendixlabs/mxcli/sdk/pages" +) + +// ako/mxcli#2518: a conditional text template that is VISIBLE and unset is +// written with the property's shipped default text when it declares one. +// `mx update-widgets` writes the Drop-down filter's visible emptyOptionCaption +// as en_US "None" / nl_NL "Niets" (mx 11.14.0); an empty template there is +// CE0463 just as a null one is. +func TestVisibleConditionalTextTemplateGetsDeclaredTranslations(t *testing.T) { + const ( + multiID = "77777777-7777-7777-7777-777777777777" // boolean "multiSelect" + captionID = "88888888-8888-8888-8888-888888888888" // TextTemplate "emptyOptionCaption" + ) + mkProp := func(id, primitiveVal string) bson.D { + return bson.D{ + {Key: "$Type", Value: "CustomWidgets$WidgetProperty"}, + {Key: "TypePointer", Value: types.UUIDToBlob(id)}, + {Key: "Value", Value: bson.D{ + {Key: "$Type", Value: "CustomWidgets$WidgetValue"}, + {Key: "PrimitiveValue", Value: primitiveVal}, + {Key: "TextTemplate", Value: nil}, + }}, + } + } + ids := map[string]pages.PropertyTypeIDEntry{ + "multiSelect": {PropertyTypeID: multiID, ValueType: "Boolean"}, + "emptyOptionCaption": {PropertyTypeID: captionID, ValueType: "TextTemplate", + DefaultTranslations: []pages.PropertyTranslation{{LanguageCode: "en_US", Text: "None"}, {LanguageCode: "nl_NL", Text: "Niets"}}}, + } + rules := []types.WidgetVisibilityRule{{ + PropertyKey: "emptyOptionCaption", + HiddenWhen: &types.WidgetVisibilityCondition{PropertyKey: "multiSelect", Operator: "truthy"}, + }} + object := func(multi string) bson.D { + return bson.D{{Key: "Properties", Value: bson.A{int32(2), mkProp(multiID, multi), mkProp(captionID, "")}}} + } + + tt, ok := templateOf(t, ApplyVisibilityRules(object("false"), ids, rules), captionID).(bson.D) + if !ok { + t.Fatal("a visible conditional text template was left null") + } + tmpl, _ := docField(tt, "Template").(bson.D) + items, _ := docField(tmpl, "Items").(bson.A) + var got []string + for _, it := range items { + if d, ok := it.(bson.D); ok { + got = append(got, docField(d, "LanguageCode").(string)+"="+docField(d, "Text").(string)) + } + } + if len(got) != 2 || got[0] != "en_US=None" || got[1] != "nl_NL=Niets" { + t.Errorf("visible emptyOptionCaption = %v, want the declared translations [en_US=None nl_NL=Niets]", got) + } + + // Control: hidden, it is null whatever it declares. + if tt := templateOf(t, ApplyVisibilityRules(object("true"), ids, rules), captionID); tt != nil { + t.Errorf("a hidden text template was filled: %v", tt) + } +} + +func docField(d bson.D, key string) any { + for _, e := range d { + if e.Key == key { + return e.Value + } + } + return nil +} diff --git a/mdl/executor/editorconfig_disjunction_2518_test.go b/mdl/executor/editorconfig_disjunction_2518_test.go new file mode 100644 index 0000000000..4c1d1955cb --- /dev/null +++ b/mdl/executor/editorconfig_disjunction_2518_test.go @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "testing" + + "github.com/mendixlabs/mxcli/mdl/types" +) + +// ako/mxcli#2518: the Data grid Drop-down filter (DatagridDropdownFilter 3.4.0) +// hides emptyOptionCaption behind a disjunction, +// +// (e.filterable||e.multiSelect)&&A.hidePropertyIn(t,e,"emptyOptionCaption") +// +// and the extractor lifted no rule for it, so mxcli never nulled the text +// template while the property was hidden — CE0463 on every multi-select filter. +// `mx update-widgets` stores null when either is set and the declared default +// translations when neither is (measured on mx 11.14.0, 7 filters, 2 pages). + +// hiddenBy reports whether any rule for key fires on values, and whether the +// rules could decide it at all. +func hiddenBy(rules []types.WidgetVisibilityRule, key string, values map[string]string) (hidden, decided bool) { + for _, r := range rules { + if r.PropertyKey != key || r.Nested() { + continue + } + fires, det := r.Fires(func(c types.WidgetVisibilityCondition) (string, bool) { + v, ok := values[c.PropertyKey] + return v, ok + }) + if det { + decided = true + } + if det && fires { + hidden = true + } + } + return hidden, decided +} + +// The drop-down filter's getProperties, as the 3.4.0 package ships it. +const dropdownFilterGetProperties = `getProperties=function(e,t){var r=e.filterable&&e.multiSelect,n=r&&"boxes"===e.selectedItemsStyle;return"attr"===e.baseType?t=function(e,t){A.hidePropertiesIn(t,e,["fetchOptionsLazy","refCaption","refCaptionExp","refCaptionSource","refEntity","refOptions","refSearchAttr"]),"auto"===e.attrChoice&&(A.hidePropertyIn(t,{},"linkedDs"),A.hidePropertyIn(t,e,"attr"));e.auto&&A.hidePropertyIn(t,e,"filterOptions");return t}(e,t):A.hidePropertiesIn(t,e,["attr","attrChoice","filterOptions","auto"]),(e.filterable||e.multiSelect)&&A.hidePropertyIn(t,e,"emptyOptionCaption"),e.filterable?A.hidePropertyIn(t,e,"clearable"):(A.hidePropertyIn(t,e,"refSearchAttr"),A.hidePropertyIn(t,e,"filterInputPlaceholderCaption")),"attr"===e.refCaptionSource?A.hidePropertiesIn(t,e,["refCaptionExp","refSearchAttr"]):A.hidePropertyIn(t,e,"refCaption"),r||A.hidePropertyIn(t,e,"selectedItemsStyle"),n||A.hidePropertyIn(t,e,"selectionMethod"),t};` + +func TestExtractVisibility_DisjunctiveGuard(t *testing.T) { + rules, _ := extractVisibilityRulesFromJS(dropdownFilterGetProperties) + for _, c := range []struct { + filterable, multiSelect string + hidden bool + }{ + {"false", "false", false}, + {"true", "false", true}, + {"false", "true", true}, + {"true", "true", true}, + } { + got, decided := hiddenBy(rules, "emptyOptionCaption", map[string]string{"filterable": c.filterable, "multiSelect": c.multiSelect}) + if !decided || got != c.hidden { + t.Errorf("filterable=%s multiSelect=%s: emptyOptionCaption hidden=%v (decided %v), want %v", + c.filterable, c.multiSelect, got, decided, c.hidden) + } + } +} + +// A disjunction is lifted only where it is the whole condition: inside a guarded +// group, or as one conjunct of a longer chain, a rule per disjunct would hide the +// property in configurations the editor shows. +func TestExtractVisibility_DisjunctionOnlyAtStatementLevel(t *testing.T) { + for _, js := range []string{ + `getProperties=function(e,t){return e.g?((e.a||e.b)&&A.hidePropertyIn(t,e,"p"),t):t};`, + `getProperties=function(e,t){return e.c&&(e.a||e.b)&&A.hidePropertyIn(t,e,"p"),t};`, + `getProperties=function(e,t){return(e.a||e.b)&&e.c&&A.hidePropertyIn(t,e,"p"),t};`, + `getProperties=function(e,t){return(e.a||e.b&&e.c)&&A.hidePropertyIn(t,e,"p"),t};`, + } { + rules, _ := extractVisibilityRulesFromJS(js) + if hidden, _ := hiddenBy(rules, "p", map[string]string{"a": "true", "b": "false", "c": "false", "g": "false"}); hidden { + t.Errorf("hides p where the editor shows it:\n%s\n%+v", js, rules) + } + } + // Control: the same disjunction at statement level, with a comparison term. + rules, _ := extractVisibilityRulesFromJS(`getProperties=function(e,t){return("x"===e.k||e.b)&&A.hidePropertiesIn(t,e,["p","q"]),t};`) + for _, key := range []string{"p", "q"} { + if hidden, _ := hiddenBy(rules, key, map[string]string{"k": "x", "b": "false"}); !hidden { + t.Errorf("%s: not hidden when k is \"x\": %+v", key, rules) + } + if hidden, _ := hiddenBy(rules, key, map[string]string{"k": "y", "b": "false"}); hidden { + t.Errorf("%s: hidden when neither disjunct holds: %+v", key, rules) + } + } +} diff --git a/mdl/executor/editorconfig_extract.go b/mdl/executor/editorconfig_extract.go index b96da3476d..41833c20d9 100644 --- a/mdl/executor/editorconfig_extract.go +++ b/mdl/executor/editorconfig_extract.go @@ -260,6 +260,26 @@ func extractVisibilityRulesFromJS(js string) ([]types.WidgetVisibilityRule, edit keys = kept } } + if !ok && len(condKeys) == 0 { + // `(A || B) && hide(…)`: hidden when ANY disjunct holds, which is one + // rule per disjunct — "any rule hiding it wins" is exactly a + // disjunction, so nothing is approximated (ako/mxcli#2518). + if terms, dok := disjunctiveGuard(js, callStart, itemIdent); dok { + stats.Recognized++ + for _, key := range keys { + for _, term := range terms { + sig := listKey + "\x00" + key + "\x00" + term.PropertyKey + term.Operator + term.Value + term.Scope + if seen[sig] { + continue + } + seen[sig] = true + c := term + rules = append(rules, types.WidgetVisibilityRule{PropertyKey: key, ListPropertyKey: listKey, HiddenWhen: &c}) + } + } + continue + } + } if !ok { // ` ? && hide(...)` — a ternary THEN branch carrying a // second condition. Held back and resolved after the loop, once the @@ -396,6 +416,107 @@ type ternaryThenCandidate struct { inner, outer types.WidgetVisibilityCondition } +// disjunctiveGuard reads the guard of a hide written `(A || B || …) && hide(…)` +// as a statement of its own, returning one condition per disjunct. The Data +// grid Drop-down filter hides emptyOptionCaption this way: +// +// (e.filterable||e.multiSelect)&&A.hidePropertyIn(t,e,"emptyOptionCaption") +// +// It is exact or it fails: the parenthesized disjunction must be the whole +// guard (bounded by a statement separator, not inside a guarded group, not one +// conjunct of a chain), and every disjunct must be a condition the vocabulary +// represents on its own — a disjunct that is itself a conjunction fails. +func disjunctiveGuard(js string, callStart int, itemIdent string) ([]types.WidgetVisibilityCondition, bool) { + pre := strings.TrimRight(js[:callStart], " ") + if at := nsPrefix(pre); at >= 0 { + pre = pre[:at] + } + pre = stripGroupSiblings(strings.TrimRight(pre, " ")) + if strings.HasSuffix(pre, "(") { + pre = strings.TrimRight(pre[:len(pre)-1], " ") + } + if !strings.HasSuffix(pre, "&&") { + return nil, false + } + pre = strings.TrimRight(pre[:len(pre)-2], " ") + if !strings.HasSuffix(pre, ")") { + return nil, false + } + open := matchingOpenParen(pre) + if open < 0 { + return nil, false + } + head := strings.TrimRight(stripReturnPrefixHead(pre[:open]), " ") + switch { + case head == "", strings.HasSuffix(head, ";"), strings.HasSuffix(head, "{"): + case strings.HasSuffix(head, ","): + if insideOpenGroup(head) { + return nil, false + } + default: + return nil, false + } + terms := splitTopLevelOr(pre[open+1 : len(pre)-1]) + if len(terms) < 2 { + return nil, false + } + aliases := enclosingAliases(js, callStart) + out := make([]types.WidgetVisibilityCondition, 0, len(terms)) + for _, term := range terms { + c, ok := guardToCondition(strings.TrimSpace(term), false, aliases, itemIdent) + if !ok { + return nil, false + } + out = append(out, c) + } + return out, true +} + +// stripReturnPrefixHead drops a trailing `return` keyword from the text before +// a guard: `return(A||B)&&hide(…)` is a statement-level guard. +func stripReturnPrefixHead(head string) string { + trimmed := strings.TrimRight(head, " ") + if strings.HasSuffix(trimmed, "return") { + before := trimmed[:len(trimmed)-len("return")] + if before == "" || !isIdentByte(before[len(before)-1]) { + return before + } + } + return head +} + +// splitTopLevelOr splits s at each `||` outside parentheses, brackets and +// string literals. +func splitTopLevelOr(s string) []string { + var out []string + depth, start := 0, 0 + inStr := byte(0) + for i := 0; i < len(s); i++ { + c := s[i] + if inStr != 0 { + if c == inStr && s[i-1] != '\\' { + inStr = 0 + } + continue + } + switch c { + case '"', '\'': + inStr = c + case '(', '[', '{': + depth++ + case ')', ']', '}': + depth-- + case '|': + if depth == 0 && i+1 < len(s) && s[i+1] == '|' { + out = append(out, s[start:i]) + start = i + 2 + i++ + } + } + } + return append(out, s[start:]) +} + // splitTernaryThenGuard recognises ` ? ` in a guard parseGuard could // not read, returning the two halves. The split is on the LAST `?`, so a nested // ternary yields the innermost then-branch, which is the one guarding this call. diff --git a/modelsdk/widgets/loader.go b/modelsdk/widgets/loader.go index 0d496aa06c..0b5048244c 100644 --- a/modelsdk/widgets/loader.go +++ b/modelsdk/widgets/loader.go @@ -353,6 +353,7 @@ func jsonToBSONWithMappingAndObjectType(data map[string]any, idMapping map[strin var valueType string var required bool var isLinked bool + var translations []types.PropertyTranslation var dataSourceProp string var nestedObjectTypeID string var nestedPropertyIDs map[string]PropertyTypeIDEntry @@ -398,6 +399,11 @@ func jsonToBSONWithMappingAndObjectType(data map[string]any, idMapping map[strin } else if key == "ValueType" && isPropertyType { // For PropertyTypes, extract ValueType info including nested ObjectType, DefaultValue, Type, Required nestedPropertyIDs = make(map[string]PropertyTypeIDEntry) + // The widget-shipped default text, for a visible text template the + // author leaves unset (ako/mxcli#2518) as for an item's (#891). + if vt, ok := val.(map[string]any); ok { + translations = readPropertyTranslations(vt["Translations"]) + } elem.Value = jsonValueToBSONWithNestedObjectType(val, idMapping, &valueTypeID, &nestedObjectTypeID, nestedPropertyIDs, &nestedKeyOrder, &defaultValue, &valueType, &required, &isLinked, &dataSourceProp) } else { elem.Value = jsonValueToBSONWithMappingAndObjectType(val, idMapping, propertyTypeIDs, &valueTypeID, key == "ValueType", objectTypeID) @@ -409,13 +415,14 @@ func jsonToBSONWithMappingAndObjectType(data map[string]any, idMapping map[strin // Record PropertyType IDs if isPropertyType && propertyKey != "" { entry := PropertyTypeIDEntry{ - PropertyTypeID: propertyTypeIDVal, - ValueTypeID: valueTypeID, - DefaultValue: defaultValue, - ValueType: valueType, - Required: required, - IsLinked: isLinked, - DataSourceProperty: dataSourceProp, + PropertyTypeID: propertyTypeIDVal, + ValueTypeID: valueTypeID, + DefaultValue: defaultValue, + ValueType: valueType, + Required: required, + IsLinked: isLinked, + DataSourceProperty: dataSourceProp, + DefaultTranslations: translations, } if nestedObjectTypeID != "" { entry.ObjectTypeID = nestedObjectTypeID diff --git a/modelsdk/widgets/templates/mendix-11.6/datagrid-dropdown-filter.json b/modelsdk/widgets/templates/mendix-11.6/datagrid-dropdown-filter.json index 9e2f4efb3a..37e1a2c372 100644 --- a/modelsdk/widgets/templates/mendix-11.6/datagrid-dropdown-filter.json +++ b/modelsdk/widgets/templates/mendix-11.6/datagrid-dropdown-filter.json @@ -1661,7 +1661,19 @@ "$ID": "5839c2234c144b4995fcd9df68928e35", "$Type": "Texts$Text", "Items": [ - 3 + 3, + { + "$ID": "d1c6a0f4e2b84c1f9a3e5b7d8c2f4a61", + "$Type": "Texts$Translation", + "LanguageCode": "en_US", + "Text": "None" + }, + { + "$ID": "7e3b9d2a5c4f4e8b8a1d6f0c3b2e9a74", + "$Type": "Texts$Translation", + "LanguageCode": "nl_NL", + "Text": "Niets" + } ] } }, diff --git a/modelsdk/widgets/texttemplate_default_translations_2518_test.go b/modelsdk/widgets/texttemplate_default_translations_2518_test.go new file mode 100644 index 0000000000..568d450672 --- /dev/null +++ b/modelsdk/widgets/texttemplate_default_translations_2518_test.go @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: Apache-2.0 + +package widgets + +import ( + "encoding/json" + "fmt" + "testing" +) + +// ako/mxcli#2518: a widget property's shipped default text reaches the build. +// The object-list items already carried it (#891); a top-level property did +// not, so a visible text template could only ever be written empty. +func TestTopLevelPropertyCarriesDefaultTranslations(t *testing.T) { + n := 0 + _, _, ids, _, _, err := GetTemplateFullBSON("com.mendix.widget.web.datagriddropdownfilter.DatagridDropdownFilter", func() string { + n++ + return fmt.Sprintf("%032x", n) + }, "") + if err != nil { + t.Fatal(err) + } + got := ids["emptyOptionCaption"].DefaultTranslations + if len(got) != 2 || got[0].LanguageCode != "en_US" || got[0].Text != "None" || got[1].Text != "Niets" { + t.Errorf("emptyOptionCaption DefaultTranslations = %+v, want en_US None / nl_NL Niets", got) + } +} + +// The embedded drop-down filter is a freshly dropped widget at its default +// configuration (filterable and multiSelect off), where emptyOptionCaption is +// visible, so it holds the shipped text — what `mx update-widgets` writes there. +// It held an empty template, which update-widgets rewrites and mx check reports +// as CE0463. (An empty template is not wrong everywhere: the text and number +// filters' screenReaderInputCaption ships text too, and mx check accepts both +// Studio Pro's empty translation and mxcli's empty template there.) +func TestDropdownFilterTemplate_EmptyOptionCaptionHoldsShippedText(t *testing.T) { + data, err := templateFS.ReadFile("templates/mendix-11.6/datagrid-dropdown-filter.json") + if err != nil { + t.Fatal(err) + } + var tmpl struct { + Type map[string]any `json:"type"` + Object map[string]any `json:"object"` + } + if err := json.Unmarshal(data, &tmpl); err != nil { + t.Fatal(err) + } + var ptID string + walkJSON(tmpl.Type, func(m map[string]any) { + if m["$Type"] == "CustomWidgets$WidgetPropertyType" && m["PropertyKey"] == "emptyOptionCaption" { + ptID, _ = m["$ID"].(string) + } + }) + var texts []string + found := false + walkJSON(tmpl.Object, func(m map[string]any) { + if m["$Type"] != "CustomWidgets$WidgetProperty" || m["TypePointer"] != ptID { + return + } + found = true + val, _ := m["Value"].(map[string]any) + tt, _ := val["TextTemplate"].(map[string]any) + tpl, _ := tt["Template"].(map[string]any) + items, _ := tpl["Items"].([]any) + for _, it := range items { + if tr, ok := it.(map[string]any); ok { + texts = append(texts, fmt.Sprint(tr["LanguageCode"], "=", tr["Text"])) + } + } + }) + if !found { + t.Fatal("no emptyOptionCaption property in the template object") + } + if len(texts) != 2 || texts[0] != "en_US=None" || texts[1] != "nl_NL=Niets" { + t.Errorf("emptyOptionCaption template = %v, want [en_US=None nl_NL=Niets]", texts) + } +} + +func walkJSON(v any, fn func(map[string]any)) { + switch x := v.(type) { + case map[string]any: + fn(x) + for _, c := range x { + walkJSON(c, fn) + } + case []any: + for _, c := range x { + walkJSON(c, fn) + } + } +} From 0cac148c1f2d0ea933170c108ad116b5cda2c900 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:14:28 +0000 Subject: [PATCH 2/5] style: gofmt splice_handler_test.go with the pinned toolchain's gofmt Upstream's 70a6ba454 reformatted it with a gofmt other than the pinned toolchain's, the same change as 1365ba438 before v0.31.0, so the merged tree fails make fmt-check. This restores the fork's version. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AeAyg3qx2my26Q8cvGyW5z --- mdl/backend/mfmutator/splice_handler_test.go | 24 ++++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/mdl/backend/mfmutator/splice_handler_test.go b/mdl/backend/mfmutator/splice_handler_test.go index 4a6ff434ab..7e4eb00991 100644 --- a/mdl/backend/mfmutator/splice_handler_test.go +++ b/mdl/backend/mfmutator/splice_handler_test.go @@ -45,18 +45,18 @@ func handlerFlow() ([]bson.D, []bson.D) { a := withEH(obj("a", "Microflows$ActionActivity", 250, 200), microflows.ErrorHandlingTypeCustomWithoutRollback) dSet(a, "Size", "160;60") // resized in Studio Pro: kept return []bson.D{ - obj("start", "Microflows$StartEvent", 100, 200), - a, - obj("h", "Microflows$ActionActivity", 250, 330), - obj("m", "Microflows$ExclusiveMerge", 400, 200), - obj("end", "Microflows$EndEvent", 550, 200), - }, []bson.D{ - flow("f1", "start", "a", 1, 3, false), - flow("f2", "a", "m", 1, 3, false), - flow("err", "a", "h", 2, 0, true), - flow("fh", "h", "m", 1, 2, false), - flow("f3", "m", "end", 1, 3, false), - } + obj("start", "Microflows$StartEvent", 100, 200), + a, + obj("h", "Microflows$ActionActivity", 250, 330), + obj("m", "Microflows$ExclusiveMerge", 400, 200), + obj("end", "Microflows$EndEvent", 550, 200), + }, []bson.D{ + flow("f1", "start", "a", 1, 3, false), + flow("f2", "a", "m", 1, 3, false), + flow("err", "a", "h", 2, 0, true), + flow("fh", "h", "m", 1, 2, false), + flow("f3", "m", "end", 1, 3, false), + } } func TestSplice_ReplaceKeepsTheErrorHandler(t *testing.T) { From e472dd86caf7ca0723be5ad912d4d146c19c6287 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 19:05:07 +0000 Subject: [PATCH 3/5] docs(report): the journey-log record's `pages` proves a page-only requirement A requirement anchored at a page fed only by database data sources runs no microflow, so the only proof is a journey whose log lists the page in `pages`. The report-tests skill and the report tests / traceability help showed a record without it, so following the docs left such a requirement "nothing to reach" with no way out. - report-tests skill: the full record as the example, with a field table (step, pages, message, run, browserMs, the meta line). - report-traceability skill and both commands' help: name `pages` and show the record. - The "nothing to reach" cell of a page-anchored requirement now says a journey proves it by listing the page in `pages`; the limits text names the field. - A test pins the skills' examples to `pages`. Fixes ako/mxcli#2526 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011oK82qTgUsRMETmzvjS27w --- ...-11-22-journey-log-pages-undocumented.json | 1 + .claude/skills/mendix/report-tests/SKILL.md | 22 +++++-- .../mendix/report-traceability/SKILL.md | 15 +++-- cmd/mxcli/cmd_report_evidence.go | 8 +++ cmd/mxcli/cmd_report_kinds.go | 4 +- cmd/mxcli/projectreport/traceability.go | 16 ++++- cmd/mxcli/projectreport/traceability_test.go | 65 +++++++++++++++++++ 7 files changed, 120 insertions(+), 11 deletions(-) create mode 100644 .claude/skills/fix-issue/findings/cmd-mxcli/2026-11-22-journey-log-pages-undocumented.json diff --git a/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-22-journey-log-pages-undocumented.json b/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-22-journey-log-pages-undocumented.json new file mode 100644 index 0000000000..5e4ce2831a --- /dev/null +++ b/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-22-journey-log-pages-undocumented.json @@ -0,0 +1 @@ +{"area": "cmd/mxcli", "date": "2026-11-22", "symptom": "a requirement anchored at a page fed only by database data sources stays 'nothing to reach' in report traceability although a journey opened the page, because the documented journey-log record has no `pages` field", "cause": "the report-tests skill and the report tests/traceability help showed a five-field record; `pages` (and step, message, run, browserMs) existed only in the JourneyRecord comment, so the one proof for a page-only requirement was undiscoverable", "file": "`.claude/skills/mendix/report-tests/SKILL.md`, `report-traceability/SKILL.md`, `cmd/mxcli/cmd_report_evidence.go`, `cmd_report_kinds.go`, `cmd/mxcli/projectreport/traceability.go` (everyRequirement, hasPageAnchor)", "insight": "An input format documented by example is documented only as far as the example goes: a field missing from it does not exist for a reader. Pin the example to the parser with a test, and make the dead-end cell name the way out", "refs": ["ako/mxcli#2526"], "test": "TestTraceabilityPageOnlyRequirementProvenByJourneyPages, TestJourneyLogExamplesNamePages"} diff --git a/.claude/skills/mendix/report-tests/SKILL.md b/.claude/skills/mendix/report-tests/SKILL.md index 957b3e7350..edf84884df 100644 --- a/.claude/skills/mendix/report-tests/SKILL.md +++ b/.claude/skills/mendix/report-tests/SKILL.md @@ -11,10 +11,10 @@ description: "Produce and read the tests report (mxcli report tests): microflow | lines | section | |---|---| | 31-43 | Preconditions (check every one) | -| 44-66 | Run it | -| 67-83 | Reading it | -| 84-100 | Which gaps deserve a test | -| 101-104 | Related | +| 44-78 | Run it | +| 79-95 | Reading it | +| 96-112 | Which gaps deserve a test | +| 113-116 | Related | # Tests Report @@ -57,9 +57,21 @@ mxcli report tests --from docs/testing/tests.json --annotations docs/testing/not The journey log is JSONL, one line per journey (or step): ```json -{"journey":"Swap a shift","start":"2026-11-12T10:00:01.120Z","end":"2026-11-12T10:00:09.410Z","status":"passed","checks":["sees 3 offers","swap requested"]} +{"journey":"Swap a shift","step":"open marketplace","start":"2026-11-12T10:00:01.120Z","end":"2026-11-12T10:00:02.410Z","status":"passed","checks":["sees 3 offers"],"pages":["Shifts.Marketplace"]} ``` +| Field | Meaning | +|---|---| +| `journey`, `start`, `end`, `status` | required: the name, the time window spans are matched against, `passed` / `failed` / `skipped` | +| `step` | the step within the journey; steps of one journey merge into it | +| `checks` | the script's own assertion messages, shown verbatim | +| `pages` | the qualified names of the pages the step opened. **List them:** a page fed only by database data sources runs no microflow, so this is the only way a journey proves a requirement anchored at it (`report traceability`) | +| `message` | why a failed step failed | +| `run`, `browserMs` | the repeat number and browser time, for `report performance` | + +A line `{"meta":true,"database":"fresh seed 2026-11-12","notes":["…"]}` records the +database state the run used. + Write `checks` from the script's own assertion messages. Prose written from a journey's name drifted from what it checks on the prototype; the page shows the checks verbatim for that reason. diff --git a/.claude/skills/mendix/report-traceability/SKILL.md b/.claude/skills/mendix/report-traceability/SKILL.md index 1f958d3300..661e044fb8 100644 --- a/.claude/skills/mendix/report-traceability/SKILL.md +++ b/.claude/skills/mendix/report-traceability/SKILL.md @@ -12,8 +12,8 @@ description: "Produce and read the PRD-to-app traceability report (mxcli report |---|---| | 25-74 | Preconditions | | 75-85 | Run it | -| 86-103 | Reading it | -| 104-107 | Related | +| 86-110 | Reading it | +| 111-114 | Related | # Traceability Report @@ -92,8 +92,15 @@ seed, tracing on, never commit while tests run). callees, microflows a page/workflow/service calls, microflows that write an anchored entity, use an anchored attribute or association. Helpers with more than three callers are left out — they belong to no single requirement. -- **Tests / journeys** reach the footprint (or the journey log names an anchored - page — needed for pages with only database data sources, which run no microflow). +- **Tests / journeys** reach the footprint, or the journey log lists an anchored + page in a record's `pages` — needed for pages with only database data sources, + which run no microflow. Write the pages each step opened into its record: + + ```json + {"journey":"Browse systems","step":"open overview","start":"…","end":"…","status":"passed","checks":["sees 4 systems"],"pages":["FieldService.LithoSystem_Overview"]} + ``` + + A row "nothing to reach" anchored at a page stays so until a journey lists it. - **Decisions / open questions** share an anchor or cite the id. Linking by shared anchor is noisy around hub elements; cite the id in the body when it matters. diff --git a/cmd/mxcli/cmd_report_evidence.go b/cmd/mxcli/cmd_report_evidence.go index 5ebb6e0049..16561e277f 100644 --- a/cmd/mxcli/cmd_report_evidence.go +++ b/cmd/mxcli/cmd_report_evidence.go @@ -274,6 +274,14 @@ Journeys: run the app with 'mxcli run --local --trace-otlp http://127.0.0.1:4318 then either pass --journeys-cmd "" (this command collects spans while it runs; the script appends its journey log to $MXCLI_JOURNEY_LOG), or collect yourself with 'mxcli report collect-spans' and pass --journeys and --spans. +The journey log has one JSON line per journey or step: + + {"journey":"Swap a shift","step":"open marketplace","start":"…","end":"…", + "status":"passed","checks":["sees 3 offers"],"pages":["Shifts.Marketplace"]} + +List in "pages" the pages each step opened: a page fed only by database data +sources runs no microflow, so it is how a journey proves a requirement +anchored at that page (report traceability). Warns when the working tree carries test-runner files: never commit while 'mxcli test' runs. Annotation keys: gap:, journey:.`, diff --git a/cmd/mxcli/cmd_report_kinds.go b/cmd/mxcli/cmd_report_kinds.go index ec1e805cfb..4ac5c05d36 100644 --- a/cmd/mxcli/cmd_report_kinds.go +++ b/cmd/mxcli/cmd_report_kinds.go @@ -518,7 +518,9 @@ Milestones come from the plan ('mxcli brain milestone "M1" --slice 01-accounts') without any, each slice is a milestone. A milestones file (--milestones, or the older docs/brain/plan/traceability.json) is still read, with a warning; 'mxcli brain milestone --import ' moves it into the plan. Evidence flags -are the tests report's. +are the tests report's. A journey proves a requirement anchored at a page +when a record of its log lists the page in "pages" ('mxcli report tests --help' +shows the record) — the only proof for a page fed by database data sources. Annotation keys: req:.`, example: ` mxcli report traceability -p app.mpr -o traceability.html diff --git a/cmd/mxcli/projectreport/traceability.go b/cmd/mxcli/projectreport/traceability.go index 24e904071c..fc0048d48a 100644 --- a/cmd/mxcli/projectreport/traceability.go +++ b/cmd/mxcli/projectreport/traceability.go @@ -486,6 +486,15 @@ func namesAnchoredPage(pages []string, anchors []brain.AnchorResult) bool { return false } +func hasPageAnchor(anchors []brain.AnchorResult) bool { + for _, a := range anchors { + if strings.EqualFold(a.Kind, "page") { + return true + } + } + return false +} + func sharesAnchor(anchors []string, req []brain.AnchorResult) bool { for _, a := range anchors { an := "@" + strings.TrimPrefix(a, "@") @@ -517,7 +526,7 @@ var TraceabilityMethod = []string{ var TraceabilityLimits = []string{ "A requirement appears only once it is captured in the brain. A PRD item nobody captured is invisible here — the report pushes the brain to be complete, it does not read the PRD.", "\"Built\" means its anchors exist, not that they do what was asked; that is what the tests column and the decisions are for.", - "Pages whose data comes only from database data sources run no microflow, so spans cannot show a journey reaching them unless the journey log names the page.", + "Pages whose data comes only from database data sources run no microflow, so spans cannot show a journey reaching them unless a journey-log record lists the page in `pages`.", "Footprints miss microflows reached only from Java actions (ako/mxcli#1819) and nanoflows.", } @@ -732,6 +741,11 @@ func everyRequirement(d TraceabilityData) Table { // journey can be seen to reach it: say so, rather than leave a // plain "nothing" beside the highlighted ones. p = "nothing to reach (no microflow implements it)" + if hasPageAnchor(r.Anchors) { + // A page fed by database data sources only: a journey + // that lists it proves it (ako/mxcli#2526). + p = "nothing to reach (no microflow implements it; a journey proves it by listing the page in its log's `pages`)" + } default: p = "nothing" } diff --git a/cmd/mxcli/projectreport/traceability_test.go b/cmd/mxcli/projectreport/traceability_test.go index 4fd28826cd..fa534cbd48 100644 --- a/cmd/mxcli/projectreport/traceability_test.go +++ b/cmd/mxcli/projectreport/traceability_test.go @@ -3,7 +3,10 @@ package projectreport import ( + "bytes" + "os" "reflect" + "strings" "testing" "time" @@ -307,3 +310,65 @@ func TestTraceabilityFootprintReachesCalleesAndCalculation(t *testing.T) { t.Errorf("calculated attribute tests = %v", r.Tests) } } + +// A requirement anchored at a page fed only by database data sources runs no +// microflow, so only a journey naming the page in its log's `pages` proves it; +// a row without that proof says how to give it (ako/mxcli#2526). +func TestTraceabilityPageOnlyRequirementProvenByJourneyPages(t *testing.T) { + f := newFixture(t) + f.module("FieldService", "") + f.page("FieldService.LithoSystem_Overview") + reqs := []brain.RequirementResult{ + req("aaaaaa", "01-systems", "See every litho system", true, anchor("@FieldService.LithoSystem_Overview", "page", brain.Resolved)), + req("bbbbbb", "01-systems", "See the systems again", true, anchor("@FieldService.LithoSystem_Overview", "page", brain.Resolved)), + } + dir := t.TempDir() + logPath := dir + "/journeys.jsonl" + if err := os.WriteFile(logPath, []byte(`{"journey":"Browse systems","step":"open overview","start":"2026-11-22T10:00:01Z","end":"2026-11-22T10:00:02Z","status":"passed","checks":["sees 4 systems"],"pages":["FieldService.LithoSystem_Overview"]}`+"\n"), 0o644); err != nil { + t.Fatal(err) + } + log, err := ReadJourneyLog(logPath) + if err != nil { + t.Fatal(err) + } + var journeys []JourneyInfo + for _, j := range log.Journeys() { + journeys = append(journeys, JourneyInfo{Name: j.Name, Status: j.Status, Pages: j.Pages}) + } + d, err := CollectTraceability(f.cat, TraceabilityInput{Requirements: reqs[:1], Evidence: &TestsData{Journeys: journeys}}) + if err != nil { + t.Fatal(err) + } + if got := d.Milestones[0].Requirements[0].Journeys; !reflect.DeepEqual(got, []string{"Browse systems"}) { + t.Errorf("the journey naming the page proves it: journeys %v", got) + } + + // Without a journey naming the page, the row says how one proves it. + d, err = CollectTraceability(f.cat, TraceabilityInput{Requirements: reqs[1:], Evidence: &TestsData{}}) + if err != nil { + t.Fatal(err) + } + env, _ := NewEnvelope("traceability", "FieldService", "now", "t", d, TraceabilityMethod, TraceabilityLimits, nil) + doc, err := RenderTraceability(env, nil) + if err != nil { + t.Fatal(err) + } + var md bytes.Buffer + _ = RenderMarkdown(&md, doc) + mustContain(t, md.String(), "a journey proves it by listing the page in its log's `pages`") +} + +// The skills' journey-log example is the record the reader parses, `pages` +// included: following the docs is enough to prove a page-only requirement +// (ako/mxcli#2526). +func TestJourneyLogExamplesNamePages(t *testing.T) { + for _, skill := range []string{"report-tests", "report-traceability"} { + b, err := os.ReadFile("../../../.claude/skills/mendix/" + skill + "/SKILL.md") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(b), `"pages":[`) { + t.Errorf("%s: the journey-log example shows no `pages`", skill) + } + } +} From dab8af188834db9599fdc38bea1981fc4ff77397 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 19:15:43 +0000 Subject: [PATCH 4/5] fix(check): MDL-WIDGET56 judges a widget's mode with the values exec writes A combo box bound with attribute: was warned about 12 required properties of its association and database modes, and a drop-down filter about refEntity, refSearchAttr and linkedDs; mxbuild builds both clean. - Unset keys take the template's written values before the hide rules are judged, so source/optionsSourceType are known. - A key with any value counts as set (attribute: sets attributeEnumeration). - An isLinked datasource is skipped; the grid fills it. - The editorConfig extractor reads a hide inside a function invoked as a ternary's then-branch under that ternary's condition. Closes #2523 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011oK82qrr1WnXxq1eRn7qRJ --- ...6-11-22-widget56-other-modes-required.json | 1 + CHANGELOG.md | 1 + mdl/executor/editorconfig_extract.go | 90 +++++++++++++++++ .../editorconfig_extract_iife_2523_test.go | 65 ++++++++++++ mdl/executor/validate_widget_required.go | 27 ++++- ...alidate_widget_required_modes_2523_test.go | 99 +++++++++++++++++++ modelsdk/widgets/mpk/mpk.go | 11 ++- 7 files changed, 291 insertions(+), 3 deletions(-) create mode 100644 .claude/skills/fix-issue/findings/mdl-executor/2026-11-22-widget56-other-modes-required.json create mode 100644 mdl/executor/editorconfig_extract_iife_2523_test.go create mode 100644 mdl/executor/validate_widget_required_modes_2523_test.go diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-22-widget56-other-modes-required.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-22-widget56-other-modes-required.json new file mode 100644 index 0000000000..fd035a1637 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-22-widget56-other-modes-required.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-11-22", "symptom": "MDL-WIDGET56 reported every other mode's required properties on a combo box set with `attribute:` (12, attributeEnumeration among them) and refEntity/refSearchAttr/linkedDs on a data grid drop-down filter; mx check 11.16.1 builds both with 0 errors.", "cause": "Three gaps. The hide rules were judged on the statement's values only, so source/optionsSourceType, which exec writes from the template (context, enumeration), were unknown and no mode rule fired. A property set through its MDL keyword (`attribute:` -> attributeEnumeration) was not counted as set. And the drop-down filter hides its association properties in a function invoked as a ternary's then-branch, `\"attr\"===e.baseType?t=function(e,t){hide([...refEntity...]),...}(e,t):...`, which parseGuard read as unguarded (its text ends at `{`) and whose nested hides lost the outer condition.", "file": "mdl/executor/validate_widget_required.go, mdl/executor/editorconfig_extract.go", "fix": "validateWidgetRequired fills unset keys from templateWrittenDefaults before judging hide rules, treats any key with a value as set, and skips an isLinked datasource (the grid fills it; mpk.PropertyDef.IsLinked). ternaryThenIIFECondition gives a hide in such a function the ternary's condition (first statement) or adds it as an And term, only when the function is invoked with its own parameter names.", "insight": "Pick the fixture by what the package ships: PedApp's Combobox 2.5.0 and drop-down filter mpk carry no editorConfig.js, so no hide rule exists there and a correct fix still fails the test. `unzip -l` on the fixture's mpk before debugging the extractor would have saved the detour. Control: the association-mode combo box still reports optionsSourceAssociationCaptionAttribute, which mx check reports as CE0642.", "refs": ["ako/mxcli#2523"], "test": "mdl/executor/validate_widget_required_modes_2523_test.go (enumeration combo + attribute filter: none; association combo: its caption only), mdl/executor/editorconfig_extract_iife_2523_test.go TestTernaryThenIIFEHidesCarryTheTernaryCondition_2523"} diff --git a/CHANGELOG.md b/CHANGELOG.md index ce3255220c..8157e1d2d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] ### Fixed +- **`check` no longer reports the required properties of a widget mode the statement did not choose** (ako/mxcli#2523) — a combo box bound with `attribute:` was warned (MDL-WIDGET56) about 12 properties of the association and database modes, and a data grid drop-down filter about `refEntity`, `refSearchAttr` and `linkedDs`; mxbuild builds both clean. The widget's hide rules are now judged with the values exec writes for unset properties, a property set through its MDL keyword counts as set, and the drop-down filter's association-mode hide rules are read. A combo box in association mode still reports the caption attribute it needs (CE0642). - **Data grid Drop-down filters no longer fail CE0463** (ako/mxcli#2518) — every drop-down filter mxcli created failed with "the definition of this widget has changed". Its `emptyOptionCaption` was written with an empty text, where Studio Pro stores none while `filterable` or `multiSelect` hides it and the widget's default text ("None") while it is visible. Rules that the widget editor writes as `(a || b) && hide(…)` are now read, and a visible text property that is left unset gets the widget's default text. Measured on mx check 11.14.0: 68 pages copied from the testapp went from 9 × CE0463 to 0. - **`docker check` and `fix widgets` say when update-widgets resets a value instead of resyncing a widget** (ako/mxcli#2507) — a CE0463 caused by a script value in a property the widget's editorConfig hides was labelled "stale widget definition — `mxcli fix widgets` fixes it", and `fix widgets` cleared it by resetting the value to the widget's default without a word. `docker check` now names the properties update-widgets resets on that widget, and `fix widgets` lists every value it replaced. - **`widget describe` says when a widget's hide rules could not be read** (ako/mxcli#2507) — a widget whose editorConfig.js hides properties through its own helper listed "(none discovered)", which read as "hides nothing", and a script value in such a property was CE0463 with no pointer to why. It now says the editorConfig.js is there and none of its hide calls is one mxcli reads. diff --git a/mdl/executor/editorconfig_extract.go b/mdl/executor/editorconfig_extract.go index 41833c20d9..72cd40756a 100644 --- a/mdl/executor/editorconfig_extract.go +++ b/mdl/executor/editorconfig_extract.go @@ -205,6 +205,18 @@ func extractVisibilityRulesFromJS(js string) ([]types.WidgetVisibilityRule, edit // and a rule keeping only the innermost term claims hidden in // configurations the editor shows. var extra []types.WidgetVisibilityCondition + // A hide in a function invoked as a ternary's then-branch runs only on + // that ternary's condition (ako/mxcli#2523). Its first statement has no + // guard of its own; later ones carry the condition as a further term. + iife, firstStmt, inIIFE := ternaryThenIIFECondition(js, callStart, itemIdent) + if inIIFE && !inSwitchArm { + switch { + case !ok && firstStmt: + cond, ok = iife, true + case ok && len(chain) == 0 && !conjunctive: + extra = dedupeConditions(cond, []types.WidgetVisibilityCondition{iife}) + } + } if ok && len(chain) > 0 { // An else-if branch: its own condition, the negated earlier // branches, and whatever groups enclose the chain. Exact or not @@ -2130,3 +2142,81 @@ func splitTopLevelCommas(args string) []string { parts = append(parts, args[start:]) return parts } + +// ternaryThenIIFERE matches the head of a function invoked as a ternary's +// then-branch, up to its body's `{`: `? t=function(e,t){` (the assignment is +// optional). Group 1 is the parameter list. +var ternaryThenIIFERE = regexp.MustCompile(`\?\s*(?:[A-Za-z_$][\w$]*\s*=\s*)?function\s*\(([\w$,\s]*)\)\s*$`) + +// ternaryThenIIFECondition reports whether the hide at callStart is in the +// body of a function that is the then-branch of a ternary and is invoked on +// the spot with its own parameter names — the Datagrid drop-down filter's +// +// "attr"===e.baseType ? t=function(e,t){ hide([…]), … ; return t }(e,t) : … +// +// and returns that ternary's condition. firstStmt marks a hide that opens the +// body (or is a comma sibling of the one that does), whose guard is then the +// condition alone. A body with any other block between it and the hide, an +// invocation with other arguments (which would rename `e`), or a condition +// that does not read gives no result, so the rule stays as before. +func ternaryThenIIFECondition(js string, callStart int, itemIdent string) (types.WidgetVisibilityCondition, bool, bool) { + pos := callStart + open := -1 + for i := 0; i < 8; i++ { + o := enclosingOpener(js, pos) + if o < 0 { + return types.WidgetVisibilityCondition{}, false, false + } + if js[o] == '{' { + open = o + break + } + pos = o + } + if open < 0 { + return types.WidgetVisibilityCondition{}, false, false + } + start := open - 120 + if start < 0 { + start = 0 + } + head := js[start:open] + m := ternaryThenIIFERE.FindStringSubmatchIndex(head) + if m == nil { + return types.WidgetVisibilityCondition{}, false, false + } + params := strings.ReplaceAll(head[m[2]:m[3]], " ", "") + close := matchingBrace(js, open) + if close < 0 || !strings.HasPrefix(strings.ReplaceAll(js[close+1:min(len(js), close+2+len(params)+8)], " ", ""), "("+params+")") { + return types.WidgetVisibilityCondition{}, false, false + } + q := start + m[0] // the ternary's `?` + guard := stripReturnPrefix(trailingExpr(js[:q])) + c, ok := guardToCondition(guard, false, enclosingAliases(js, q), itemIdent) + if !ok { + return types.WidgetVisibilityCondition{}, false, false + } + pre := strings.TrimRight(js[:callStart], " ") + if at := nsPrefix(pre); at >= 0 { + pre = pre[:at] + } + pre = strings.TrimRight(stripGroupSiblings(strings.TrimRight(pre, " ")), " ") + return c, len(pre) == open+1, true +} + +// matchingBrace returns the index of the `}` closing the `{` at open, or -1. +func matchingBrace(js string, open int) int { + depth := 0 + for i := open; i < len(js); i++ { + switch js[i] { + case '{': + depth++ + case '}': + depth-- + if depth == 0 { + return i + } + } + } + return -1 +} diff --git a/mdl/executor/editorconfig_extract_iife_2523_test.go b/mdl/executor/editorconfig_extract_iife_2523_test.go new file mode 100644 index 0000000000..7d696fc791 --- /dev/null +++ b/mdl/executor/editorconfig_extract_iife_2523_test.go @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/types" +) + +// The Datagrid drop-down filter (DatagridDropdownFilter.editorConfig.js, the +// line shipped since 2.x) hides its association properties in a function +// invoked as a ternary's then-branch: +// +// return "attr"===e.baseType ? t=function(e,t){ hide([… "refEntity" …]), +// "auto"===e.attrChoice && (hide("linkedDs"), hide("attr")); …; return t }(e,t) +// : hide(["attr","attrChoice","filterOptions","auto"]), … +// +// The first hide was read as having no guard at all (its text ends at the +// function's `{`), so refEntity — required — read as always shown and +// MDL-WIDGET56 reported it on every attribute filter (ako/mxcli#2523). The +// nested attrChoice hides were lifted without the outer condition, claiming +// linkedDs hidden in association mode too. +const iifeThenJS = `function getProperties(e,t){var r=e.filterable&&e.multiSelect;return"attr"===e.baseType?t=function(e,t){A.hidePropertiesIn(t,e,["refEntity","refSearchAttr"]),"auto"===e.attrChoice&&(A.hidePropertyIn(t,{},"linkedDs"),A.hidePropertyIn(t,e,"attr"));return t}(e,t):A.hidePropertiesIn(t,e,["attr","attrChoice"]),t}` + +func TestTernaryThenIIFEHidesCarryTheTernaryCondition_2523(t *testing.T) { + rules, _ := extractVisibilityRulesFromJS(iifeThenJS) + byKey := map[string][]string{} + for _, r := range rules { + byKey[r.PropertyKey] = append(byKey[r.PropertyKey], iifeRuleText(r)) + } + want := map[string]string{ + "refEntity": "baseType eq attr", + "refSearchAttr": "baseType eq attr", + "linkedDs": "attrChoice eq auto & baseType eq attr", + "attr": "attrChoice eq auto & baseType eq attr | baseType ne attr", + "attrChoice": "baseType ne attr", + } + for k, w := range want { + if got := strings.Join(sortedCopy(byKey[k]), " | "); got != w { + t.Errorf("%s: rules %q, want %q", k, got, w) + } + } +} + +func iifeRuleText(r types.WidgetVisibilityRule) string { + parts := []string{r.HiddenWhen.PropertyKey + " " + r.HiddenWhen.Operator + " " + r.HiddenWhen.Value} + for _, c := range r.And { + parts = append(parts, c.PropertyKey+" "+c.Operator+" "+c.Value) + } + return strings.Join(parts, " & ") +} + +func sortedCopy(s []string) []string { + out := append([]string(nil), s...) + for i := range out { + for j := i + 1; j < len(out); j++ { + if out[j] < out[i] { + out[i], out[j] = out[j], out[i] + } + } + } + return out +} diff --git a/mdl/executor/validate_widget_required.go b/mdl/executor/validate_widget_required.go index 9e9cbe2722..d2c20fa1d0 100644 --- a/mdl/executor/validate_widget_required.go +++ b/mdl/executor/validate_widget_required.go @@ -41,6 +41,27 @@ func validateWidgetRequired(w *ast.WidgetV3, registry *WidgetRegistry, locationP return nil } values, explicit := widgetValueMap(w, def) + // What the statement wrote, through whichever keyword: `attribute:` + // writes attributeEnumeration in a combo box's enumeration mode, and + // that property is set although the script never names it + // (ako/mxcli#2523). + stated := map[string]bool{} + for k, v := range values { + if v != "" { + stated[k] = true + } + } + // The hide rules are judged on the configuration exec writes: what the + // statement says, and the template's value for everything else. Judged + // on the statement alone, a combo box's `source` and `optionsSourceType` + // were unknown, no rule could decide, and every other mode's required + // properties were reported — 12 on one combo box, which mxbuild builds + // clean (ako/mxcli#2523). + for k, v := range templateWrittenDefaults(def.WidgetID) { + if lk := strings.ToLower(k); values[lk] == "" { + values[lk] = v + } + } rules := visibilityRulesFor(def, registry) slots, lists := filledSlotsAndLists(w, def) @@ -55,7 +76,11 @@ func validateWidgetRequired(w *ast.WidgetV3, registry *WidgetRegistry, locationP continue case p.Type == "object" && lists[key]: continue - case explicit[key]: + case explicit[key], stated[key]: + continue + case p.Type == "datasource" && p.IsLinked: + // The containing widget fills it — a Data Grid 2 filter's + // `linkedDs` is the grid's list (ako/mxcli#2523). continue } if hiddenByConfiguration(rules, p.Key, values) { diff --git a/mdl/executor/validate_widget_required_modes_2523_test.go b/mdl/executor/validate_widget_required_modes_2523_test.go new file mode 100644 index 0000000000..cb917f8601 --- /dev/null +++ b/mdl/executor/validate_widget_required_modes_2523_test.go @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "os" + "path/filepath" + "sort" + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/visitor" +) + +// ako/mxcli#2523: MDL-WIDGET56 reported every other mode's required properties +// on a combo box (12 of them, `attributeEnumeration` among them although +// `attribute:` set it) and `refEntity`, `refSearchAttr` on a drop-down filter, +// and mxbuild builds both clean. Two causes: the hide rules were judged with +// only the statement's values, so `source` and `optionsSourceType` — which +// exec writes from the widget's template (context, enumeration) — were +// unknown and no rule could fire; and a property set through its MDL keyword +// (`attribute:` → attributeEnumeration) was not counted as set. + +func shippedWidgetsRegistry2523(t *testing.T) *WidgetRegistry { + t.Helper() + proj, err := filepath.Abs(filepath.Join("..", "..", "testdata", "expr-checker", "minimal.mpr")) + if err != nil { + t.Fatal(err) + } + if _, err := os.Stat(proj); err != nil { + t.Skipf("fixture not found: %v", err) + } + reg := LoadWidgetRegistry(proj) + if reg == nil { + t.Fatal("no registry") + } + return reg +} + +func requiredWarnings2523(t *testing.T, reg *WidgetRegistry, src string, names ...string) []string { + t.Helper() + prog, errs := visitor.Build(src) + if len(errs) > 0 { + t.Fatalf("parse: %v", errs) + } + // The walker check runs, so a filter gets its column's context as it does + // there; only this rule's findings, for the named widgets. + var out []string + for _, v := range validateWidgetTree(prog.Statements[0].(*ast.CreatePageStmtV3).Widgets, reg, "page M.P") { + if v.RuleID != widgetRequiredRule { + continue + } + for _, n := range names { + if strings.Contains(v.Message, "`"+n+"`") { + i := strings.Index(v.Message, "`") + out = append(out, v.Message[i:]) + } + } + } + sort.Strings(out) + return out +} + +func TestRequiredPropertiesOfOtherModesAreNotReported_2523(t *testing.T) { + reg := shippedWidgetsRegistry2523(t) + got := requiredWarnings2523(t, reg, `create page M.P (title: 'x', layout: Atlas_Core.Atlas_Default) { + dataview dv (datasource: $X) { + combobox cbTech (label: 'Technology', attribute: Technology) + } + datagrid dg (datasource: database M.E) { + column (attribute: Technology, caption: 'Technology') { dropdownfilter f1 } + } +};`, "cbTech", "f1") + if len(got) != 0 { + t.Errorf("enumeration-mode combo box and attribute drop-down filter: %d warnings, want none:\n %s", + len(got), strings.Join(got, "\n ")) + } +} + +// Control: what the chosen mode needs and the statement leaves out is still +// reported — an association combo box with no caption attribute. +func TestRequiredPropertyOfTheChosenModeIsStillReported_2523(t *testing.T) { + reg := shippedWidgetsRegistry2523(t) + got := requiredWarnings2523(t, reg, `create page M.P (title: 'x', layout: Atlas_Core.Atlas_Default) { + dataview dv (datasource: $X) { + combobox cbOwner (label: 'Owner', association: M.E_Owner, datasource: database M.Owner) + } +};`, "cbOwner") + joined := strings.Join(got, "\n") + if !strings.Contains(joined, "optionsSourceAssociationCaptionAttribute") { + t.Errorf("the association mode's caption attribute is not reported:\n%s", joined) + } + for _, other := range []string{"attributeEnumeration", "attributeBoolean", "staticAttribute", "optionsSourceDatabaseValueAttribute"} { + if strings.Contains(joined, "`"+other+"`") { + t.Errorf("another mode's %s is reported:\n%s", other, joined) + } + } +} diff --git a/modelsdk/widgets/mpk/mpk.go b/modelsdk/widgets/mpk/mpk.go index f74ed66f66..47476403ca 100644 --- a/modelsdk/widgets/mpk/mpk.go +++ b/modelsdk/widgets/mpk/mpk.go @@ -39,8 +39,12 @@ type PropertyDef struct { // datasource defaulting to an association ("Association"). Like OnChange it // is part of the widget DEFINITION, so storing "None" where the package // declares one is CE0463 (mendixlabs/mxcli#956, File Uploader 2.5.0). - DefaultType string - IsList bool + DefaultType string + IsList bool + // IsLinked is a datasource's isLinked="true": the containing widget fills + // it (a Data Grid 2 filter's `linkedDs` is the grid's own list), so a + // script never sets it and leaving it unset is no defect (ako/mxcli#2523). + IsLinked bool Multiline bool // for string/textTemplate: multiline="true" SelectionTypes []string // for selection properties: IsSystem bool // true for elements @@ -247,6 +251,7 @@ type xmlProperty struct { OnChange string `xml:"onChange,attr"` AllowUpload string `xml:"allowUpload,attr"` IsList string `xml:"isList,attr"` + IsLinked string `xml:"isLinked,attr"` Multiline string `xml:"multiline,attr"` DataSource string `xml:"dataSource,attr"` SelectableObjects string `xml:"selectableObjects,attr"` @@ -476,6 +481,7 @@ func walkPropertyGroup(pg xmlPropGroup, parentCategory string, def *WidgetDefini DefaultValue: p.DefaultValue, DefaultType: p.DefaultType, IsList: p.IsList == "true", + IsLinked: p.IsLinked == "true", Multiline: p.Multiline == "true", SelectionTypes: toSelectionTypes(p.SelectionTypes), DataSource: p.DataSource, @@ -570,6 +576,7 @@ func collectNestedProperties(pg xmlPropGroup, parent *PropertyDef, parentCategor DefaultValue: p.DefaultValue, DefaultType: p.DefaultType, IsList: p.IsList == "true", + IsLinked: p.IsLinked == "true", Multiline: p.Multiline == "true", SelectionTypes: toSelectionTypes(p.SelectionTypes), DataSource: p.DataSource, From d29d9520d0442c64552dd8445397fa35d4d12aa1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 19:20:30 +0000 Subject: [PATCH 5/5] brain: --from-json items take accepts, changes and partly_meets `capture --from-json` refused any item carrying "accepts" (unknown field), so a decision accepting a lint finding, or changing or partly meeting a requirement, could only be captured one at a time with the flags. The three options had no batch spelling. - BatchItem gains `accepts`, `changes` and `partly_meets`: string arrays in the flags' "[:]" form, snake_case like every other brain JSON key. They are written exactly as the flags write them (verdicts, then acceptances), so the two spellings of one decision produce the same entry. - Validated per item before anything is queued, with the flags' own refusals: an acceptance on a requirement or open question, a verdict on a requirement, a bad rule id, a requirement the plan lacks. - The requirement-id check moves from applyVerdictFlags into brain.CheckRequirementIDs, shared by both paths, and checks the id's shape first ("nope" is not an id, not a missing requirement). Its message now says a staged requirement must be promoted first. - BuildBatch's last parameter becomes BatchChecks (source normaliser plus known requirement ids). - `staged --json` reports `accepts` and `verdicts` as `list --json` already does. - The BatchItem comment claimed staged/list output could be fed back in; it cannot (id, kind, date and shard are refused). Corrected rather than extended: a round trip needs its own design. Fixes ako/mxcli#2524 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011oK82sxYNXAhaYkijzRwae --- ...11-22-brain-batch-no-accepts-verdicts.json | 1 + .claude/skills/mendix/project-brain/SKILL.md | 2 +- cmd/mxcli/brain/batch.go | 55 ++++++-- cmd/mxcli/brain/batch_test.go | 12 +- cmd/mxcli/brain/batch_verdict_test.go | 127 ++++++++++++++++++ cmd/mxcli/brain/verdict.go | 20 +++ cmd/mxcli/cmd_brain.go | 51 ++++--- cmd/mxcli/cmd_brain_batch_verdict_test.go | 85 ++++++++++++ docs-site/src/tools/project-brain.md | 22 ++- 9 files changed, 341 insertions(+), 34 deletions(-) create mode 100644 .claude/skills/fix-issue/findings/cmd-mxcli/2026-11-22-brain-batch-no-accepts-verdicts.json create mode 100644 cmd/mxcli/brain/batch_verdict_test.go create mode 100644 cmd/mxcli/cmd_brain_batch_verdict_test.go diff --git a/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-22-brain-batch-no-accepts-verdicts.json b/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-22-brain-batch-no-accepts-verdicts.json new file mode 100644 index 0000000000..70a5128231 --- /dev/null +++ b/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-22-brain-batch-no-accepts-verdicts.json @@ -0,0 +1 @@ +{"area": "cmd/mxcli", "date": "2026-11-22", "symptom": "`brain capture --from-json` refused a whole batch with `json: unknown field \"accepts\"`: --accepts, --changes and --partly-meets had no batch spelling, so a decision accepting a lint finding (or changing a requirement) could only be captured one at a time with the flag", "cause": "`BatchItem` (cmd/mxcli/brain/batch.go) mirrored only the text/anchor/slice/open/source flags; the three later flags were added to the single form only, and the requirement-id check lived in the command layer (`applyVerdictFlags`) where `BuildBatch` could not reach it", "file": "`cmd/mxcli/brain/batch.go` (`BatchItem`, `BatchChecks`, `addVerdictsAndAcceptances`), `cmd/mxcli/brain/verdict.go` (`CheckRequirementIDs`), `cmd/mxcli/cmd_brain.go` (`applyVerdictFlags`, `stagedEntry`)", "insight": "**When a command has two input spellings (flags and a batch), every flag added to one is a gap in the other — and the dangerous fix is the one that parses the field but drops it.** Acceptances and verdicts are body lines read by regex, so a batch that accepted `accepts` without writing the line would capture the decision and leave lint reporting the finding: stubbing the write makes the batch succeed with empty bodies. The test that pins it compares the batch entry's body to the flag path's (same order: verdicts, then acceptances) and, through the CLI, the flag form of the same decision is reported 'Already queued' as the batch one. Workaround before the fix: the exact `Accepts lint `RULE` on `@El`: reason` line in `body` is read; prose is not. The BatchItem comment promised list/staged output could be fed back in — false (id/kind/date/shard are refused), so corrected rather than extended", "refs": ["ako/mxcli#2524"]} diff --git a/.claude/skills/mendix/project-brain/SKILL.md b/.claude/skills/mendix/project-brain/SKILL.md index 6060297a74..92a2f133c8 100644 --- a/.claude/skills/mendix/project-brain/SKILL.md +++ b/.claude/skills/mendix/project-brain/SKILL.md @@ -317,7 +317,7 @@ cap: the cap is what stops the store becoming a file nobody reads. | `mxcli brain init -p app.mpr` | Creates `docs/brain/`. Refuses a `docs/brain/` it did not write | | `mxcli brain capture "" [-a @Anchor]…` | Queues an entry. Never commits | | `mxcli brain staged [--since ] [--slice ] [--fail-if-empty]` | Lists the queue with the shard each entry would land in. `--since` is the slice boundary — see below | -| `mxcli brain capture --from-json ` | Queues a JSON array of entries as one act: every item validated first, duplicates skipped. Use it for a list, not a loop of captures | +| `mxcli brain capture --from-json ` | Queues a JSON array of entries as one act: every item validated first, duplicates skipped. Use it for a list, not a loop of captures. Per item: `text` (or `title`+`body`), `anchors`, `slice`, `open`, `source`, and `accepts` / `changes` / `partly_meets` — the values of `--accepts` / `--changes` / `--partly-meets`, e.g. `"accepts": ["CONV010:demo app"]` | | `mxcli brain promote … [--to ]` | Writes them into their shards, all or none. The human step. Re-run after an interruption completes it | | `mxcli brain drop ` | Removes it from the queue or from its shard | | `mxcli brain capture "" --slice [-a @Anchor]…` | Queues a **requirement** of that slice | diff --git a/cmd/mxcli/brain/batch.go b/cmd/mxcli/brain/batch.go index 2b0683977c..318abe5228 100644 --- a/cmd/mxcli/brain/batch.go +++ b/cmd/mxcli/brain/batch.go @@ -20,9 +20,14 @@ import ( "time" ) -// BatchItem is one entry of `brain capture --from-json`. The fields are the -// input half of what `staged --json` and `list --json` print, so a caller can -// feed a list straight back in. +// BatchItem is one entry of `brain capture --from-json`, with a field for each +// capture flag that describes an entry. +// +// It is NOT the shape `staged --json` or `list --json` prints, and their output +// cannot be fed back in: it carries id, kind, date and shard, which are refused +// as unknown fields, and it reports acceptances and verdicts as parsed objects +// rather than as the flag specs below. A round trip would need its own design +// (which output fields to ignore, how an object maps back to a spec). type BatchItem struct { // Text is the single-argument form of capture: first line title, the rest // body. Give it or Title (with an optional Body), not both. @@ -33,6 +38,23 @@ type BatchItem struct { Slice string `json:"slice,omitempty"` Open bool `json:"open,omitempty"` Source string `json:"source,omitempty"` + // Accepts, Changes and PartlyMeets are --accepts, --changes and + // --partly-meets: each "" or ":", written into the + // body as the lines lint, check and plan read (ako/mxcli#2524). + Accepts []string `json:"accepts,omitempty"` + Changes []string `json:"changes,omitempty"` + PartlyMeets []string `json:"partly_meets,omitempty"` +} + +// BatchChecks is what BuildBatch needs from outside the items. +type BatchChecks struct { + // NormalizeSource resolves an item's source the way --source does on the + // command line; nil leaves sources as given. + NormalizeSource func(string) (string, error) + // KnownRequirements is the plan's requirement ids, which a verdict must + // name. Nil means there is no plan to check against (no store yet), and + // ids are not checked — as the flags behave. + KnownRequirements map[string]bool } // ParseBatch reads a JSON array of items. Unknown fields are refused: a @@ -59,17 +81,20 @@ func ParseBatch(r io.Reader) ([]BatchItem, error) { // writes anything. The first invalid item fails the whole batch, named by its // index in the array, so nothing is queued from a list that is partly wrong. // -// normalizeSource resolves an item's source the way --source does on the -// command line; nil leaves sources as given. -func BuildBatch(items []BatchItem, now time.Time, normalizeSource func(string) (string, error)) ([]Entry, error) { +// Acceptances and verdicts are added exactly as the flags add them, in the same +// order, so the two spellings of one decision produce the same entry. +func BuildBatch(items []BatchItem, now time.Time, checks BatchChecks) ([]Entry, error) { out := make([]Entry, 0, len(items)) for i, it := range items { e, err := it.entry(now) - if err == nil && it.Source != "" && normalizeSource != nil { - e.Source, err = normalizeSource(it.Source) + if err == nil && it.Source != "" && checks.NormalizeSource != nil { + e.Source, err = checks.NormalizeSource(it.Source) } else if err == nil { e.Source = it.Source } + if err == nil { + e, err = it.addVerdictsAndAcceptances(e, checks.KnownRequirements) + } if err != nil { return nil, fmt.Errorf("items[%d]: %w; nothing was queued", i, err) } @@ -78,6 +103,20 @@ func BuildBatch(items []BatchItem, now time.Time, normalizeSource func(string) ( return out, nil } +func (it BatchItem) addVerdictsAndAcceptances(e Entry, known map[string]bool) (Entry, error) { + if err := CheckRequirementIDs(append(append([]string{}, it.Changes...), it.PartlyMeets...), known); err != nil { + return Entry{}, err + } + e, err := AddVerdicts(e, VerdictChanges, it.Changes) + if err != nil { + return Entry{}, err + } + if e, err = AddVerdicts(e, VerdictPartly, it.PartlyMeets); err != nil { + return Entry{}, err + } + return AddAcceptances(e, it.Accepts) +} + func (it BatchItem) entry(now time.Time) (Entry, error) { text := it.Text switch { diff --git a/cmd/mxcli/brain/batch_test.go b/cmd/mxcli/brain/batch_test.go index 9b86ceddfd..defb7cc6ae 100644 --- a/cmd/mxcli/brain/batch_test.go +++ b/cmd/mxcli/brain/batch_test.go @@ -44,14 +44,14 @@ func queueLen(t *testing.T, q *Queue) int { func TestBuildBatchRefusesTheWholeBatchNamingTheBadItem(t *testing.T) { bad := items("One", "Two", "Three") bad[1].Anchors = []string{"not an anchor"} - if _, err := BuildBatch(bad, day, nil); err == nil || !strings.Contains(err.Error(), "items[1]") { + if _, err := BuildBatch(bad, day, BatchChecks{}); err == nil || !strings.Contains(err.Error(), "items[1]") { t.Fatalf("err = %v, want a refusal naming items[1]", err) } // Control: the same batch without the bad item builds, and queues N-1. s, q := batchStore(t) good := append(bad[:1:1], bad[2]) - es, err := BuildBatch(good, day, nil) + es, err := BuildBatch(good, day, BatchChecks{}) if err != nil { t.Fatalf("control batch refused: %v", err) } @@ -71,12 +71,12 @@ func TestBuildBatchRefusesAmbiguousOrEmptyItems(t *testing.T) { "bare module requirement": {Title: "Needs a module element", Slice: "01-x", Anchors: []string{"@Sales"}}, } { - if _, err := BuildBatch([]BatchItem{it}, day, nil); err == nil { + if _, err := BuildBatch([]BatchItem{it}, day, BatchChecks{}); err == nil { t.Errorf("%s: accepted, want a refusal", name) } } // title + body is the two-field form of text. - es, err := BuildBatch([]BatchItem{{Title: "Head", Body: "Prose"}}, day, nil) + es, err := BuildBatch([]BatchItem{{Title: "Head", Body: "Prose"}}, day, BatchChecks{}) if err != nil || es[0].Title != "Head" || es[0].Body != "Prose" { t.Fatalf("title+body = %+v, %v", es, err) } @@ -100,7 +100,7 @@ func TestCaptureBatchSkipsDuplicatesAndIsIdempotent(t *testing.T) { t.Fatal(err) } - es, err := BuildBatch(items("Fresh one", "Already decided", "Fresh two", "Fresh one"), day, nil) + es, err := BuildBatch(items("Fresh one", "Already decided", "Fresh two", "Fresh one"), day, BatchChecks{}) if err != nil { t.Fatal(err) } @@ -161,7 +161,7 @@ func TestCaptureBatchAssignsIDsAgainstEarlierItems(t *testing.T) { func stage(t *testing.T, s *Store, q *Queue, texts ...string) []string { t.Helper() - es, err := BuildBatch(items(texts...), day, nil) + es, err := BuildBatch(items(texts...), day, BatchChecks{}) if err != nil { t.Fatal(err) } diff --git a/cmd/mxcli/brain/batch_verdict_test.go b/cmd/mxcli/brain/batch_verdict_test.go new file mode 100644 index 0000000000..bde60a4680 --- /dev/null +++ b/cmd/mxcli/brain/batch_verdict_test.go @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: Apache-2.0 + +package brain + +import ( + "strings" + "testing" +) + +// ako/mxcli#2524: --accepts, --changes and --partly-meets had no batch +// spelling, so a decision accepting a lint finding could not be captured with +// --from-json at all. + +// The issue's item, verbatim: the field name the reporter reached for must parse. +func TestParseBatchTakesAcceptsChangesAndPartlyMeets(t *testing.T) { + got, err := ParseBatch(strings.NewReader(`[ + {"text":"Kept deliberately simple: ACT_ microflows do their own object changes.", + "anchors":["@FieldService.ACT_Triage_Complete"], + "accepts":["CONV010:one-happy-path demo app"]}, + {"text":"Approval is per team", "changes":["a1b2c3:per team, not per person"], + "partly_meets":["d4e5f6"]}]`)) + if err != nil { + t.Fatal(err) + } + if len(got) != 2 || got[0].Accepts[0] != "CONV010:one-happy-path demo app" || + got[1].Changes[0] != "a1b2c3:per team, not per person" || got[1].PartlyMeets[0] != "d4e5f6" { + t.Errorf("parsed: %+v", got) + } + // Unknown fields are still refused: the brain's JSON is snake_case, so the + // camelCase spelling is a typo, not an alias. + if _, err := ParseBatch(strings.NewReader(`[{"text":"A","partlyMeets":["d4e5f6"]}]`)); err == nil { + t.Error("partlyMeets was accepted; it must be refused like any other unknown field") + } +} + +// A batch item must produce exactly what the flags produce for the same input, +// or the two spellings of one decision diverge. +func TestBatchItemWritesTheSameLinesAsTheFlags(t *testing.T) { + it := BatchItem{ + Text: "Kept deliberately simple: ACT_ microflows do their own object changes.", + Anchors: []string{"@FieldService.ACT_Triage_Complete", "@FieldService.ACT_Triage_Start"}, + Accepts: []string{"CONV010:one-happy-path demo app"}, + Changes: []string{"a1b2c3:per team"}, + } + got, err := BuildBatch([]BatchItem{it}, day, BatchChecks{}) + if err != nil { + t.Fatal(err) + } + + want, err := NewEntry(it.Text, it.Anchors, day) + if err != nil { + t.Fatal(err) + } + if want, err = AddVerdicts(want, VerdictChanges, it.Changes); err != nil { + t.Fatal(err) + } + if want, err = AddAcceptances(want, it.Accepts); err != nil { + t.Fatal(err) + } + if got[0].Body != want.Body { + t.Errorf("batch body:\n%s\nflag body:\n%s", got[0].Body, want.Body) + } + // And the readers see them: one acceptance per anchor, one verdict. + if n := len(Acceptances(got[0])); n != 2 { + t.Errorf("acceptances = %d, want 2 (one per anchor)", n) + } + if v := Verdicts(got[0]); len(v) != 1 || v[0].RequirementID != "a1b2c3" || v[0].Reason != "per team" { + t.Errorf("verdicts = %+v", v) + } + // Control: an item without them builds the plain entry. + plain, err := BuildBatch([]BatchItem{{Text: it.Text, Anchors: it.Anchors}}, day, BatchChecks{}) + if err != nil || plain[0].Body != "" { + t.Errorf("plain item: body %q, %v", plain[0].Body, err) + } +} + +// Validated per item, like the rest of the batch: the first bad one fails the +// whole batch, named by index, with the reason the flag form gives. +func TestBatchRefusesAnInvalidAcceptanceOrVerdict(t *testing.T) { + known := map[string]bool{"a1b2c3": true} + good := BatchItem{Text: "Fine", Anchors: []string{"@Sales.Order"}} + for _, tc := range []struct { + name string + bad BatchItem + want string + }{ + {"accepts on a requirement", BatchItem{Text: "R", Slice: "01-x", Anchors: []string{"@Sales.ACT_X"}, Accepts: []string{"SEC001"}}, "is a decision"}, + {"accepts on an open question", BatchItem{Text: "Q", Open: true, Accepts: []string{"SEC001"}}, "is a decision"}, + {"not a rule id", BatchItem{Text: "D", Anchors: []string{"@Sales.Order"}, Accepts: []string{"sec 001:x"}}, "not a lint rule id"}, + {"verdict on a requirement", BatchItem{Text: "R", Slice: "01-x", Anchors: []string{"@Sales.ACT_X"}, Changes: []string{"a1b2c3"}}, "not on a requirement"}, + {"not a requirement id", BatchItem{Text: "D", Changes: []string{"nope"}}, "not a requirement id"}, + {"unknown requirement", BatchItem{Text: "D", PartlyMeets: []string{"ffffff:x"}}, "no requirement ffffff"}, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := BuildBatch([]BatchItem{good, tc.bad}, day, BatchChecks{KnownRequirements: known}) + if err == nil || !strings.Contains(err.Error(), "items[1]") || !strings.Contains(err.Error(), tc.want) { + t.Errorf("err = %v, want items[1] and %q", err, tc.want) + } + }) + } + + // Control: the known requirement passes, and with no plan to check + // against (no store yet) the id is not checked — as the flags behave. + ok := BatchItem{Text: "D", Changes: []string{"a1b2c3"}, PartlyMeets: []string{"ffffff"}} + if _, err := BuildBatch([]BatchItem{{Text: "D", Changes: []string{"a1b2c3"}}}, day, BatchChecks{KnownRequirements: known}); err != nil { + t.Errorf("a verdict on a known requirement was refused: %v", err) + } + if _, err := BuildBatch([]BatchItem{ok}, day, BatchChecks{}); err != nil { + t.Errorf("with no plan to check against, ids are not checked: %v", err) + } +} + +// A requirement queued earlier in the SAME batch is not in the plan yet, so a +// verdict cannot name it — as `capture --changes` cannot name a staged one. +// The message says what to do. +func TestBatchVerdictCannotNameARequirementOnlyStaged(t *testing.T) { + req := BatchItem{Text: "Orders must be approvable", Slice: "01-approvals", Anchors: []string{"@Sales.ACT_Approve"}} + built, err := BuildBatch([]BatchItem{req}, day, BatchChecks{}) + if err != nil { + t.Fatal(err) + } + dec := BatchItem{Text: "Approval is per team", Changes: []string{built[0].ID}} + _, err = BuildBatch([]BatchItem{req, dec}, day, BatchChecks{KnownRequirements: map[string]bool{}}) + if err == nil || !strings.Contains(err.Error(), "items[1]") || !strings.Contains(err.Error(), "promote") { + t.Errorf("err = %v, want items[1] refused with a pointer to promoting the requirement first", err) + } +} diff --git a/cmd/mxcli/brain/verdict.go b/cmd/mxcli/brain/verdict.go index 9103a7b2bd..b23306fda3 100644 --- a/cmd/mxcli/brain/verdict.go +++ b/cmd/mxcli/brain/verdict.go @@ -260,6 +260,26 @@ func AddVerdicts(e Entry, kind string, specs []string) (Entry, error) { return e, nil } +// CheckRequirementIDs refuses a verdict spec ("" or ":") +// naming a requirement the plan does not have. A nil known set means there is +// no plan to check against, and nothing is refused. Shared by the flags and +// --from-json, so both refuse with the same words. +func CheckRequirementIDs(specs []string, known map[string]bool) error { + for _, spec := range specs { + id, _, _ := strings.Cut(spec, ":") + // Shape first: "nope" is not an id at all, and "no requirement nope + // in the plan" would send the reader looking for it. + if _, err := VerdictLine(VerdictChanges, id, ""); err != nil { + return err + } + if known != nil && !known[strings.ToLower(strings.TrimSpace(id))] { + return fmt.Errorf("no requirement %s in the plan ('brain list --kind requirement' lists them; "+ + "one that is only staged must be promoted before a verdict can name it)", strings.TrimSpace(id)) + } + } + return nil +} + // RequirementIDs is the set of requirement ids the plan has. func (s *Store) RequirementIDs() (map[string]bool, error) { vs, err := s.loadVerdicts() diff --git a/cmd/mxcli/cmd_brain.go b/cmd/mxcli/cmd_brain.go index f48ad32875..9de2a5b279 100644 --- a/cmd/mxcli/cmd_brain.go +++ b/cmd/mxcli/cmd_brain.go @@ -100,7 +100,11 @@ var brainCaptureCmd = &cobra.Command{ Long: `Queue an entry for a person to review and promote. --from-json queues a JSON array of entries in one act, each -{"text" | "title"+"body", "anchors": [...], "slice"?, "open"?, "source"?}. +{"text" | "title"+"body", "anchors": [...], "slice"?, "open"?, "source"?, + "accepts"?: [...], "changes"?: [...], "partly_meets"?: [...]} — the last three +take the values of --accepts, --changes and --partly-meets ("" or +":"). This is not the shape 'staged --json' prints, which cannot +be fed back in. Every item is validated before anything is queued, so one bad item fails the batch with its index named. A duplicate of something committed, queued or earlier in the batch is skipped and reported with the existing id, so the same @@ -360,8 +364,13 @@ func runBrainCaptureBatch(dir, from string) { if err != nil { brainFatal(err) } - entries, err := brain.BuildBatch(items, time.Now(), func(raw string) (string, error) { - return brainSource(dir, raw) + known, err := brainKnownRequirements(dir) + if err != nil { + brainFatal(err) + } + entries, err := brain.BuildBatch(items, time.Now(), brain.BatchChecks{ + NormalizeSource: func(raw string) (string, error) { return brainSource(dir, raw) }, + KnownRequirements: known, }) if err != nil { brainFatal(err) @@ -1457,6 +1466,10 @@ type promoteReport struct { type stagedEntry struct { brain.Entry Shard string `json:"shard"` + // As 'list --json' reports them, so a queued decision shows what it will + // accept or change before anyone promotes it (ako/mxcli#2524). + Verdicts []brain.EntryVerdict `json:"verdicts,omitempty"` + Accepts []brain.EntryAcceptance `json:"accepts,omitempty"` } // stagedReport renders the queue for a machine. `all` is the unfiltered queue @@ -1469,7 +1482,8 @@ func stagedReport(all, shown []brain.Entry, filter brain.StagedFilter) map[strin // Explicit, as 'list' gives it: a consumer must not have to know // that an empty kind means a decision. e.Kind = e.EntryKind() - out = append(out, stagedEntry{Entry: e, Shard: shard}) + out = append(out, stagedEntry{Entry: e, Shard: shard, + Verdicts: brain.EntryVerdicts(e), Accepts: brain.EntryAcceptances(e)}) } rep := map[string]any{"staged": out, "count": len(out)} @@ -1564,25 +1578,30 @@ func applyVerdictFlags(cmd *cobra.Command, dir string, e brain.Entry) (brain.Ent if len(changes) == 0 && len(partly) == 0 { return e, nil } - if store := brain.NewStore(dir); store.Exists() { - known, err := store.RequirementIDs() - if err != nil { - return e, err - } - for _, spec := range append(append([]string{}, changes...), partly...) { - id, _, _ := strings.Cut(spec, ":") - if !known[strings.ToLower(strings.TrimSpace(id))] { - return e, fmt.Errorf("no requirement %s in the plan ('brain list --kind requirement' lists them)", id) - } - } + known, err := brainKnownRequirements(dir) + if err != nil { + return e, err + } + if err := brain.CheckRequirementIDs(append(append([]string{}, changes...), partly...), known); err != nil { + return e, err } - e, err := brain.AddVerdicts(e, brain.VerdictChanges, changes) + e, err = brain.AddVerdicts(e, brain.VerdictChanges, changes) if err != nil { return e, err } return brain.AddVerdicts(e, brain.VerdictPartly, partly) } +// brainKnownRequirements is the plan's requirement ids, or nil when there is +// no store yet and so no plan to check a verdict against. +func brainKnownRequirements(dir string) (map[string]bool, error) { + store := brain.NewStore(dir) + if !store.Exists() { + return nil, nil + } + return store.RequirementIDs() +} + func verdictFlag(kind string) string { if kind == brain.VerdictChanges { return "changes" diff --git a/cmd/mxcli/cmd_brain_batch_verdict_test.go b/cmd/mxcli/cmd_brain_batch_verdict_test.go new file mode 100644 index 0000000000..1327defe66 --- /dev/null +++ b/cmd/mxcli/cmd_brain_batch_verdict_test.go @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "os" + "path/filepath" + "testing" + + "github.com/mendixlabs/mxcli/cmd/mxcli/brain" +) + +type stagedVerdictJSON struct { + Staged []struct { + ID string `json:"id"` + Accepts []struct { + Rule string `json:"rule"` + Element string `json:"element"` + Reason string `json:"reason"` + } `json:"accepts"` + Verdicts []struct { + Requirement string `json:"requirement"` + Kind string `json:"kind"` + } `json:"verdicts"` + } `json:"staged"` +} + +// ako/mxcli#2524 end to end: the reporter's item is captured by --from-json +// instead of failing the batch, `staged --json` shows what each queued decision +// accepts and changes, and they survive promotion into what `list --json` reads. +func TestBrainBatchCapturesAcceptancesAndVerdicts(t *testing.T) { + mpr := brainJSONProject(t) + dir := filepath.Dir(mpr) + store := brain.NewStore(dir) + req, err := brain.NewRequirement("Orders must be approvable", []string{"@Sales.ACT_Approve"}, "01-approvals", brainTestDay()) + if err != nil { + t.Fatal(err) + } + if err := store.Promote(req, req.Shard()); err != nil { + t.Fatal(err) + } + + in := filepath.Join(t.TempDir(), "decisions.json") + if err := os.WriteFile(in, []byte(`[ + {"text":"Kept deliberately simple: ACT_ microflows do their own object changes.", + "anchors":["@FieldService.ACT_Triage_Complete"], + "accepts":["CONV010:one-happy-path demo app"]}, + {"text":"Approval is per team, not per person", "anchors":["@Sales.ACT_Approve"], + "changes":["`+req.ID+`:per team"]}, + {"text":"Is the export needed for v1?", "open":true, "partly_meets":["`+req.ID+`"]} + ]`), 0o644); err != nil { + t.Fatal(err) + } + args := []string{"brain", "capture", "--from-json", in, "-p", mpr, "--json"} + if c := decodeJSON[captureBatchJSON](t, args, runBrainForTest(t, args)); c.Added != 3 { + t.Fatalf("capture --from-json = %+v, want all three queued", c) + } + + sargs := []string{"brain", "staged", "-p", mpr, "--json"} + st := decodeJSON[stagedVerdictJSON](t, sargs, runBrainForTest(t, sargs)) + if len(st.Staged) != 3 { + t.Fatalf("staged: %+v", st) + } + if a := st.Staged[0].Accepts; len(a) != 1 || a[0].Rule != "CONV010" || a[0].Element != "FieldService.ACT_Triage_Complete" || a[0].Reason != "one-happy-path demo app" { + t.Errorf("staged accepts = %+v", a) + } + if v := st.Staged[1].Verdicts; len(v) != 1 || v[0].Requirement != req.ID || v[0].Kind != brain.VerdictChanges { + t.Errorf("staged changes = %+v", v) + } + if v := st.Staged[2].Verdicts; len(v) != 1 || v[0].Kind != brain.VerdictPartly { + t.Errorf("staged partly_meets = %+v", v) + } + + pargs := []string{"brain", "promote", st.Staged[0].ID, st.Staged[1].ID, st.Staged[2].ID, "-p", mpr, "--json"} + if p := decodeJSON[promoteBatchJSON](t, pargs, runBrainForTest(t, pargs)); p.Promoted != 3 { + t.Fatalf("promote = %+v", p) + } + accepted, _, err := store.LoadAcceptances() + if err != nil { + t.Fatal(err) + } + if len(accepted) != 1 || accepted[0].Rule != "CONV010" { + t.Errorf("after promote, lint would read acceptances %+v", accepted) + } +} diff --git a/docs-site/src/tools/project-brain.md b/docs-site/src/tools/project-brain.md index 69c1a1d2c4..83bef02f32 100644 --- a/docs-site/src/tools/project-brain.md +++ b/docs-site/src/tools/project-brain.md @@ -556,9 +556,25 @@ mxcli brain promote 1a2b3c 4d5e6f 7a8b9c -p app.mpr ``` `--from-json` reads a JSON array (`-` for stdin) of -`{"text" | "title"+"body", "anchors": [...], "slice"?, "open"?, "source"?}`, -the input fields `staged --json` prints. Every item is checked before anything -is queued, so one bad item fails the batch and names its index (`items[3]`). +`{"text" | "title"+"body", "anchors": [...], "slice"?, "open"?, "source"?, +"accepts"?: [...], "changes"?: [...], "partly_meets"?: [...]}`. The last three +are `--accepts`, `--changes` and `--partly-meets`, with the same values +(`""` or `":"`) and the same effect, so a batch can record +a decision that accepts a lint finding: + +```json +[{"text": "Kept deliberately simple: ACT_ microflows do their own object changes.", + "anchors": ["@FieldService.ACT_Triage_Complete"], + "accepts": ["CONV010:one-happy-path demo app"]}] +``` + +This is not the shape `staged --json` or `list --json` prints — their output +carries `id`, `kind`, `date` and `shard`, and reports acceptances and verdicts +as parsed objects — so it cannot be fed back in as it stands. Every item is +checked before anything is queued, so one bad item fails the batch and names its +index (`items[3]`): an unknown field, an acceptance on a requirement, a verdict +naming a requirement the plan does not have. A requirement queued earlier in +the same batch is not in the plan yet; promote it before a verdict names it. A duplicate — of a committed entry, a queued one, or an earlier item — is skipped and reported with the existing id, so the same list twice is a no-op.