A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
model-apps 2.7.1: authored page keys, in-tag comments, value-less view operators, a lint CLI, and the session-start hook warning (#562)
Akshay Maloo433a5fd37391
diff --git a/.github/workflows/validate-repository-metadata.yml b/.github/workflows/validate-repository-metadata.ymlindex e092575e4..6a5ae41e4 100644--- a/.github/workflows/validate-repository-metadata.yml+++ b/.github/workflows/validate-repository-metadata.yml@@ -32,6 +32,15 @@ jobs:- name: validate-telemetry-ikeysrun: node scripts/validate-telemetry-ikeys.js+ # A hooks.json key the host does not recognise fails nothing — it just+ # prints "unknown key ... ignored" in every user's terminal at every+ # session start, so no test and no reviewer catches it.+ - name: test-hooks-manifests-validator+ run: node --test scripts/tests/validate-hooks-manifests.test.js++ - name: validate-hooks-manifests+ run: node scripts/validate-hooks-manifests.js+- name: test-secure-process-execution-validatorrun: node --test scripts/tests/validate-secure-process-execution.test.jsdiff --git a/plugins/mobile-apps/.claude-plugin/plugin.json b/plugins/mobile-apps/.claude-plugin/plugin.jsonindex c624fb5fd..67c5fe1d4 100644--- a/plugins/mobile-apps/.claude-plugin/plugin.json+++ b/plugins/mobile-apps/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "mobile-app",- "version": "0.3.1",+ "version": "0.3.2","description": "Build and deploy Power Apps code apps for mobile using Expo (React Native), with native device functionality and Power Platform connectors","author": {"name": "Microsoft",diff --git a/plugins/mobile-apps/.plugin/plugin.json b/plugins/mobile-apps/.plugin/plugin.jsonindex c624fb5fd..67c5fe1d4 100644--- a/plugins/mobile-apps/.plugin/plugin.json+++ b/plugins/mobile-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "mobile-app",- "version": "0.3.1",+ "version": "0.3.2","description": "Build and deploy Power Apps code apps for mobile using Expo (React Native), with native device functionality and Power Platform connectors","author": {"name": "Microsoft",diff --git a/plugins/mobile-apps/hooks/README.md b/plugins/mobile-apps/hooks/README.mdnew file mode 100644index 000000000..cd56f6671--- /dev/null+++ b/plugins/mobile-apps/hooks/README.md@@ -0,0 +1,15 @@+# mobile-apps hooks++What `hooks.json` wires up, and why.++Telemetry-only start hooks. They never validate, mutate, or block tool calls. File validation stays+owned by each workflow through `scripts/validate-mobile-files.js`.++This prose lived in a `_comment` key inside `hooks.json` itself. Claude Code validates that file+against a closed schema and prints `mobile-apps: hooks.json: unknown key "_comment" ignored` at+**every session start**, which reads as a plugin misconfiguration to the user (#555, #558). The+documentation belongs here instead; `scripts/validate-hooks-manifests.js` keeps it from drifting+back.++Telemetry is fail-closed and honours the `POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT`+environment variable, which disables transmission for automation and CI.diff --git a/plugins/mobile-apps/hooks/hooks.json b/plugins/mobile-apps/hooks/hooks.jsonindex 411fccbdc..829ed374c 100644--- a/plugins/mobile-apps/hooks/hooks.json+++ b/plugins/mobile-apps/hooks/hooks.json@@ -1,5 +1,4 @@{- "_comment": "Telemetry-only start hooks. They never validate, mutate, or block tool calls. File validation stays owned by each workflow through scripts/validate-mobile-files.js.","hooks": {"PreToolUse": [{diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex 747450d4e..48bcc0e23 100644--- a/plugins/model-apps/.claude-plugin/plugin.json+++ b/plugins/model-apps/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.7.0",+ "version": "2.7.1","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.jsonindex 747450d4e..48bcc0e23 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.7.0",+ "version": "2.7.1","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.mdindex 104b220ac..8cea367cd 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -99,6 +99,14 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo- **`scripts/lib/spec-lint.js`** — pure App Spec guardrail (`lintAppSpec → { ok, errors,warnings }`): errors block the plan gate (e.g. the relationship-name-vs-lookup-namecollision Dataverse rejects), warnings teach.+- **`scripts/lint-app-spec.js`** — the CLI surface for both gates, for a headless author or a CI+ job (#560). Runs `migrateAppSpec` → `validateAppSpec` (what the build runs on load) → `lintAppSpec`+ (guardrails the builder does **not** run), and exits non-zero on errors (`--strict` also fails on+ warnings). Prefer it over calling the library through `node -e`: linting the file **as written**+ rather than the migrated shape is what let a spec pass the lint and then fail the build (#545).+ `--profile` defaults to **`plan`**, not `deploy`, because the authoring flow runs this while pages+ are still intents — a deploy default rejects a normal work-in-progress spec. `plan` relaxes only+ that rule. Gate a final, deployable spec with `--profile deploy`.- **`scripts/build-model-app.js` → `scripts/lib/sdk-build.js`** — the deterministic, **idempotent**build engine, run after approval. Runs in two engine invocations (staged flow): (1) `--stage data--apply` materializes tables + columns + relationships (solution·data-model only; sample-datadiff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex d7c5c8d7c..085cb5794 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -5,7 +5,59 @@ All notable changes to the **model-apps** plugin.Entries are deliberately short: what changed and why it matters to you. The reasoning,evidence and trade-offs behind a change live in its PR, in `docs/`, or in the linked issue.-## [Unreleased] — 2.7.0+## [Unreleased] — 2.7.1++Three defects an author hits before reaching an environment, and a session-start warning.++### Added++- **`scripts/lint-app-spec.js` — lint and validate a spec without touching an environment** ([#560]).+ `validateAppSpec` (the gate `--apply` enforces) and `lintAppSpec` (the authoring guardrails) were+ library exports with no entry point, so a headless author or a CI job had to reach in with+ `node -e`. The CLI runs migrate → validate → lint, tags each finding `schema:` or `lint:`, and+ exits non-zero on errors. `--profile` defaults to `plan` (pages may still be intents), so gate a+ final, deployable spec with `--profile deploy`. `--strict` also fails on warnings; `--json`+ emits the report. Argument handling is deliberately strict — an unknown flag, or `--spec`/+ `--profile` given without a value, is a usage error, never a silent fall back to the default+ profile a CI job did not ask for.++### Fixed++- **A spec that declares `schemaVersion` per page but not at the top level no longer breaks every+ page reference** ([#545]). Migration mints a stable key per page, and it did so *unconditionally* —+ overwriting hand-authored keys with a slug of the page name. The references hold keys, not names,+ so nothing rewrote them and validation reported one "not a known page key" / "unknown page" error+ per page, none of which named the cause. Authored keys now survive migration; a key is minted only+ for a page that has none, and every authored key is reserved first so a minted one cannot steal it.+- **A `//` or `/* */` comment inside a JSX opening tag no longer makes a valid page look truncated**+ ([#542]). `jsxTag` mode had no comment handling, so an apostrophe in the comment prose was read as+ an attribute-value quote — and that scanner does not stop at a newline, because a JSX attribute+ value legitimately may span lines. It ran to end of file, blanking the real `export default` and+ miscounting every bracket after it, so `promote-intent-pages` rejected a complete page as+ truncated. Promotion is transactional, so one such page blocked the whole batch. Block comments+ had the same defect, which the report did not cover.+- **`eq-businessid` / `ne-businessid` are accepted in a view filter** ([#546]). Both are value-less+ FetchXML operators — the business-unit equivalents of `eq-userid` / `ne-userid` — and the lint+ demanded a value they must not carry. The operator list is now the documented value-less set,+ which also adds `eq-userlanguage`, the user-hierarchy operators, and the relative fiscal-period+ ones. The reverse case now warns: a value-less operator that *carries* a value is not rejected by+ Dataverse, it is ignored — so the filter silently does not do what the value says. An operator+ outside the documented set also warns, with a "did you mean" hint, instead of being reported as+ needing a value it cannot take.+- **No more `hooks.json: unknown key "_comment" ignored` at every session start** ([#555], [#558],+ affects `model-apps` and `mobile-apps`). The hooks manifest is validated against a closed schema,+ so the documentation key it carried was reported as a misconfiguration on every launch. The prose+ moved to `hooks/README.md`, and a repo-wide CI check now fails any manifest with an unrecognised+ top-level key — the symptom is otherwise invisible to both tests and review.++[#542]: https://github.com/microsoft/power-platform-skills/issues/542+[#545]: https://github.com/microsoft/power-platform-skills/issues/545+[#546]: https://github.com/microsoft/power-platform-skills/issues/546+[#555]: https://github.com/microsoft/power-platform-skills/issues/555+[#558]: https://github.com/microsoft/power-platform-skills/issues/558+[#560]: https://github.com/microsoft/power-platform-skills/issues/560++## [2.7.0]Multi-language Dataverse labels, granting access on roles this spec does not own, and theapp-builder defects found while rebuilding a real app into a second environment.diff --git a/plugins/model-apps/hooks/README.md b/plugins/model-apps/hooks/README.mdnew file mode 100644index 000000000..30f16bd63--- /dev/null+++ b/plugins/model-apps/hooks/README.md@@ -0,0 +1,35 @@+# model-apps hooks++What `hooks.json` wires up, and why.++This prose lived in a `_comment` key inside `hooks.json` itself. Claude Code validates that file+against a closed schema and prints `model-apps: hooks.json: unknown key "_comment" ignored` at+**every session start**, which reads as a plugin misconfiguration to the user (#555, #558). The+documentation belongs here instead; `scripts/validate-hooks-manifests.js` keeps it from drifting+back.++## PreToolUse++| Matcher | Hook | Behaviour |+| --- | --- | --- |+| `Write\|Edit\|MultiEdit` | `validate-write-safety.js` | **Flags** (non-blocking, exit 1) a write outside the cwd, and only during an active model-apps authoring session — that is, when a `genpage-plan.md`, `app-spec.json`, or `model-app-plan.md` marker exists at or under the cwd, which covers both `/genpage` and `/app-builder`. |+| `Skill\|skill` | `run-skill-pretool-telemetry.js` | Emits the `skill_started` usage event. Ships disabled until an instrumentation key is provisioned. |++## PostToolUse++| Matcher | Hook | Behaviour |+| --- | --- | --- |+| `Skill\|skill` | `run-skill-posttool-validation.js` | Runs the invoked skill's own `scripts/validate*.js`, if it has one. |+| `Write\|Edit\|MultiEdit` | `validate-icon-imports.js` | On every code write, validates `@fluentui/react-icons` imports against `references/verified-icons.txt`. |++## UserPromptSubmit++`run-user-prompt-telemetry.js` emits `skill_started` for `/model-apps:<skill>` slash commands.+Tracked skills are derived from `skills/*/SKILL.md`, so a new skill is picked up automatically.++## Notes++- All telemetry is fail-closed and default-off in `ikey.json`; a missing executable, a timeout, or an+ unparseable response resolves to "no event" rather than throwing into the hook it runs inside.+- Run the host from the target project folder, or pass that folder as the cwd — the write-safety+ session markers are resolved relative to it.diff --git a/plugins/model-apps/hooks/hooks.json b/plugins/model-apps/hooks/hooks.jsonindex 871f0e04c..ed5ed8e2d 100644--- a/plugins/model-apps/hooks/hooks.json+++ b/plugins/model-apps/hooks/hooks.json@@ -1,5 +1,4 @@{- "_comment": "PreToolUse: write-safety FLAGS (non-blocking, exit 1) Write/Edit/MultiEdit outside the cwd only during an active model-apps authoring session (a genpage-plan.md, app-spec.json, or model-app-plan.md marker at/under cwd — covering both /genpage and /app-builder); skill-pretool-telemetry emits skill_started usage telemetry (ships disabled until provisioned). PostToolUse: per-skill validator + on every code write validate @fluentui/react-icons imports against references/verified-icons.txt. UserPromptSubmit: emit skill_started for /model-apps:<skill> slash commands. Tracked skills are derived from skills/*/SKILL.md, so a new skill is picked up automatically. All telemetry is fail-closed and default-off in ikey.json. Run the host from the target project folder (or pass it as cwd).","hooks": {"PreToolUse": [{diff --git a/plugins/model-apps/references/authoring-flow.md b/plugins/model-apps/references/authoring-flow.mdindex f8c0a08a3..7ba0124c9 100644--- a/plugins/model-apps/references/authoring-flow.md+++ b/plugins/model-apps/references/authoring-flow.md@@ -387,7 +387,7 @@ relationship-name-vs-lookup-name collision Dataverse rejects) **before** the useon top of a broken model, the most expensive point to unwind:```bash-node -e "const{lintAppSpec}=require('${PLUGIN_ROOT}/scripts/lib/spec-lint.js');const s=require('<abs-path-to-app-spec.json>');const r=lintAppSpec(s);console.log(JSON.stringify(r,null,2));"+node "${PLUGIN_ROOT}/scripts/lint-app-spec.js" --spec @<abs-path-to-app-spec.json> --json```On a data-model-only spec the linter surfaces **only** data-model findings (the forms/views/app checks@@ -628,12 +628,17 @@ spec — the data model was already gated by the early lint at the end of Levelvalidating the artifacts/sample-data/app layered on top):```bash-node -e "const{lintAppSpec}=require('${PLUGIN_ROOT}/scripts/lib/spec-lint.js');const s=require('<abs-path-to-app-spec.json>');const r=lintAppSpec(s);console.log(JSON.stringify(r,null,2));"+node "${PLUGIN_ROOT}/scripts/lint-app-spec.js" --spec @<abs-path-to-app-spec.json> --json```Replace `<abs-path-to-app-spec.json>` with the actual absolute path to-`<working-dir>/app-spec.json`. Use `require()` with an absolute path so Node-resolves it regardless of cwd.+`<working-dir>/app-spec.json`. Pass an absolute path so it resolves regardless of cwd.+The CLI runs migration and `validateAppSpec` — the gates the build itself runs on load — plus+the `lintAppSpec` authoring guardrails, which the builder does **not** run. It exits non-zero on+errors. It validates under the `plan` profile, which allows pages that are still intents (they+are generated in Phase 1.5, after this gate); `plan` relaxes only that rule. Errors are tagged+`schema:` (the hard gate) or `lint:` (authoring guardrails); fix the `schema:` ones first,+because lint advice on a spec that fails the gate is advice on a spec that cannot build.**Interpret the result:**diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.jsindex 5fb357e9d..e95eba4eb 100644--- a/plugins/model-apps/scripts/lib/app-spec.js+++ b/plugins/model-apps/scripts/lib/app-spec.js@@ -2777,29 +2777,77 @@ function migrateAppSpec(spec) {// defensively — but do NOT rewrite the value, or validateAppSpec would see a repaired spec and// report nothing. The shape error stays for the gate to find.const arr = (v) => (Array.isArray(v) ? v : []);- // Pass 1: mint every key and wrap legacy codeFile→source. nameToKey is fully populated- // after this loop so the rewrite pass below needs only a single scan (no forward-ref gaps).+ // A key the author actually wrote AND that is usable as an identifier. A present-but-malformed+ // `key` (42, null, "", " ") is deliberately NOT usable: it is neither reserved nor used to+ // resolve a reference, but it is still preserved on the page (see pass 1) so validateAppSpec+ // reports the author's real mistake instead of this pass papering over it.+ const usableKey = (p) => (typeof p.key === 'string' && p.key.trim() ? p.key : '');+ const authoredKeys = new Set();+ // Pass 0: RESERVE every hand-authored key before minting anything.+ //+ // A spec can declare `schemaVersion: 2` on each PAGE — with hand-authored stable keys and+ // key-based `navigatesTo`/appShell refs — while omitting the TOP-LEVEL `schemaVersion`, which is+ // precisely what routes it here. Minting `slugify(name)` over an authored key silently re-keys+ // the page, and because the refs hold KEYS (not names) pass 2 never rewrites them, so every+ // reference dangles and validation reports one "not a known page key" / "unknown page" error per+ // page — none of them naming the real cause. Reserving first also stops a key minted for an+ // earlier page from stealing a key that a later page authored. See #545.for (const p of arr(out.pages)) {if (!p || typeof p !== 'object') continue;- let key = slugify(p.name);- let n = 1;- while (used.has(key)) { n += 1; key = `${slugify(p.name)}-${n}`; }- used.add(key);+ const k = usableKey(p);+ if (k) { used.add(k); authoredKeys.add(k); }+ }+ // Pass 1: mint keys for KEYLESS pages only, and wrap legacy codeFile→source. nameToKey is fully+ // populated after this loop so the rewrite pass below needs only a single scan (no forward-ref gaps).+ for (const p of arr(out.pages)) {+ if (!p || typeof p !== 'object') continue;+ // An authored key is kept verbatim — including a malformed one. validateAppSpec then reports it+ // by name ("key 'X' has an invalid key grammar", or "needs a stable key" for a non-string),+ // which the author can act on; replacing it with a slug here would either resurrect the+ // dangling-reference failure above or silently repair a typo the author needs to see. A key is+ // minted ONLY when the page carries no `key` property at all.+ let key = usableKey(p);+ if (!key) {+ const declared = Object.prototype.hasOwnProperty.call(p, 'key') && p.key !== undefined;+ if (declared) {+ key = p.key; // present but malformed — hand it to validation unchanged+ } else {+ key = slugify(p.name);+ let n = 1;+ while (used.has(key)) { n += 1; key = `${slugify(p.name)}-${n}`; }+ used.add(key);+ }+ }p.key = key;- nameToKey.set(p.name, key);+ // Only a usable key can stand in for this page in a reference. Registering a malformed one+ // would rewrite a legacy name-ref to `42` or `""` and bury the real error under a second one.+ if (typeof key === 'string' && key.trim()) nameToKey.set(p.name, key);if (!p.source && typeof p.codeFile === 'string') { p.source = { kind: 'tsx', codeFile: p.codeFile }; delete p.codeFile; }}// Pass 2: rewrite name-refs to keys exactly once. Because nameToKey is complete, forward refs// (a page referencing a later-declared page) resolve correctly without a repeated second pass.+ //+ // An exact AUTHORED-key match wins over a name match. Once authored keys survive migration+ // (pass 0), a reference can legitimately already BE a key — and a spec may contain a page whose+ // authored key equals a DIFFERENT page's name (key 'orders' on "All Orders", plus a page actually+ // named "orders"). Rewriting unconditionally would silently retarget that reference to the other+ // page and still validate, because the substituted value is itself a valid key.+ //+ // The test is `authoredKeys`, NOT every final key: a MINTED key is derived from a name, so it can+ // collide with a different page's name by construction (pages "All Orders" and "all-orders" mint+ // 'all-orders' and 'all-orders-2'). Treating a minted key as authoritative would leave a legacy+ // name-ref to the second page pointing at the first. A legacy spec has no authored keys at all,+ // so it keeps exactly its previous name-first behaviour.+ const rewrite = (ref) => (authoredKeys.has(ref) ? ref : (nameToKey.has(ref) ? nameToKey.get(ref) : ref));for (const p of arr(out.pages)) {if (!p || typeof p !== 'object') continue;- for (const nav of arr(p.navigatesTo)) { if (nav && nameToKey.has(nav.targetKey)) nav.targetKey = nameToKey.get(nav.targetKey); }+ for (const nav of arr(p.navigatesTo)) { if (nav && typeof nav.targetKey === 'string') nav.targetKey = rewrite(nav.targetKey); }}for (const a of arr(out.appShell && out.appShell.areas)) {if (!a || typeof a !== 'object') continue;for (const g of arr(a.groups)) {if (!g || typeof g !== 'object') continue;- for (const sa of arr(g.subAreas)) { if (sa && sa.page && nameToKey.has(sa.page)) sa.page = nameToKey.get(sa.page); }+ for (const sa of arr(g.subAreas)) { if (sa && typeof sa.page === 'string') sa.page = rewrite(sa.page); }}}return out;diff --git a/plugins/model-apps/scripts/lib/source-literals.js b/plugins/model-apps/scripts/lib/source-literals.jsindex 94c3af774..6fe8410a9 100644--- a/plugins/model-apps/scripts/lib/source-literals.js+++ b/plugins/model-apps/scripts/lib/source-literals.js@@ -282,6 +282,28 @@ function blankLiterals(code) {}if (mode === 'jsxTag') {+ // Comments come FIRST. A `//` or `/* */` comment between attributes is valid TSX, and a+ // generator naturally emits one to explain an attribute. Without this branch the attribute-+ // value case below sees an apostrophe in the comment prose ("Griffel's") and treats it as a+ // quote — and that scanner deliberately does NOT stop at a newline, because a JSX attribute+ // value may legitimately span lines, so it ran to EOF. The real `export default` was blanked+ // and every bracket after it miscounted, which is the false-positive direction this file's+ // header calls the worse one: a complete page refused as truncated. #542.+ //+ // `/` in a tag is otherwise only the start of `/>`, and `n` distinguishes all three cases.+ if (c === '/' && n === '/') {+ const end = src.indexOf('\n', i);+ blank(i, end === -1 ? src.length : end);+ i = end === -1 ? src.length : end;+ continue;+ }+ if (c === '/' && n === '*') {+ const end = src.indexOf('*/', i + 2);+ const stop = end === -1 ? src.length : end + 2;+ blank(i, stop);+ i = stop;+ continue;+ }if (c === '"' || c === "'") { // attribute valuelet j = i + 1;while (j < src.length && src[j] !== c) j += 1;@@ -289,6 +311,26 @@ function blankLiterals(code) {i = Math.min(j + 1, src.length);continue;}+ // A template literal inside a tag can only be part of an explicit TYPE ARGUMENT, e.g.+ // <Link<`https://${string}`> to={u} />+ // and its content is data, not code. Consuming it as one unit here is what keeps the `//`+ // in a template-literal *type* from being mistaken for the comment branch above — which+ // would blank to end of line and reject a valid module, and could also hide a genuinely+ // malformed expression that follows on the same line. Mirrors the `code`-mode scanner:+ // `${...}` interpolations are blanked with the rest rather than tracked.+ if (c === '`') {+ let j = i + 1;+ let d = 0;+ for (; j < src.length; j += 1) {+ if (src[j] === '\\') { j += 1; continue; }+ if (src[j] === '{' && src[j - 1] === '$') d += 1;+ else if (src[j] === '}' && d > 0) d -= 1;+ else if (src[j] === '`' && d === 0) break;+ }+ blank(i + 1, j);+ i = Math.min(j + 1, src.length);+ continue;+ }if (c === '{') { enterJsxExpr('jsxTag'); i += 1; continue; }if (c === '/' && n === '>') { // self-closing: no text run followsmode = jsxDepth > 0 ? 'jsxText' : 'code';diff --git a/plugins/model-apps/scripts/lib/spec-lint.js b/plugins/model-apps/scripts/lib/spec-lint.jsindex b459862fa..eb6c8821b 100644--- a/plugins/model-apps/scripts/lib/spec-lint.js+++ b/plugins/model-apps/scripts/lib/spec-lint.js@@ -9,9 +9,82 @@ const { resolveSurfaces, unresolvedSurfaceMessage } = require('./surface-resolveconst CHOICE_OPTION_WARN = 12;const SEQNUM_RE = /\{SEQNUM(:\d+)?\}/i;// FetchXML operators that take no <value> (so a filter may omit value/values).-const NO_VALUE_OPS = new Set(['null', 'not-null', 'eq-userid', 'ne-userid', 'eq-useroruserteams', 'eq-userteams',+//+// The list is the documented value-less ConditionOperator set, NOT a curated subset: an operator+// missing here makes the lint demand a value the operator must not carry and reject a correct spec+// (#546 — `eq-businessid` / `ne-businessid`, the business-unit equivalents of `eq-userid` /+// `ne-userid`, which are the natural way to express "rows owned by my business unit"). The reverse+// error matters too, so do not add a value-TAKING operator here: that would silently stop the lint+// catching a missing value and push the failure to the platform at build time.+//+// Every name below is copied verbatim from the documented operator table, and the test pins them+// against an INDEPENDENT literal list — iterating this set to test itself cannot catch a typo in it,+// and a typo reintroduces exactly the #546 false positive.+// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/fetchxml/reference/operators+const NO_VALUE_OPS = new Set(['null', 'not-null',+ // current-user / current-business-unit context+ 'eq-userid', 'ne-userid', 'eq-useroruserteams', 'eq-userteams', 'eq-useroruserhierarchy',+ 'eq-useroruserhierarchyandteams', 'eq-businessid', 'ne-businessid', 'eq-userlanguage',+ // relative date'today', 'yesterday', 'tomorrow', 'this-week', 'last-week', 'next-week', 'this-month', 'last-month', 'next-month',- 'this-year', 'last-year', 'next-year', 'this-fiscal-year', 'last-seven-days', 'next-seven-days']);+ 'this-year', 'last-year', 'next-year', 'last-seven-days', 'next-seven-days',+ // relative fiscal period+ 'this-fiscal-year', 'last-fiscal-year', 'next-fiscal-year',+ 'this-fiscal-period', 'last-fiscal-period', 'next-fiscal-period']);++// Every operator the condition table documents, value-less ones included. Transcribed in the doc+// table's own alphabetical order so it can be diffed against the source by eye.+//+// WHY this exists: without it, a typo'd operator fell through to the missing-value check and was+// reported as `needs a value` — advice that is not merely unhelpful but WRONG. The author adds a+// value, the lint goes green, and Dataverse rejects the operator at build time. That is the same+// shape as the #546 false positive, with an extra step. Mirrors how business-rule operators are+// already validated (see BUSINESS_RULE_OPERATORS in app-spec.js, which also offers a near match).+//+// An unknown operator is a WARNING, not an error, and that is the direct lesson of #546: an+// INCOMPLETE list here would reject a correct spec, which is worse than letting a rare unknown+// operator through to a build-time failure that at least names it. `--strict` still fails on it.+// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/fetchxml/reference/operators+const KNOWN_FILTER_OPS = new Set([+ 'above', 'begins-with', 'between', 'contain-values', 'ends-with', 'eq', 'eq-businessid',+ 'eq-or-above', 'eq-or-under', 'eq-userid', 'eq-userlanguage', 'eq-useroruserhierarchy',+ 'eq-useroruserhierarchyandteams', 'eq-useroruserteams', 'eq-userteams', 'ge', 'gt', 'in',+ 'in-fiscal-period', 'in-fiscal-period-and-year', 'in-fiscal-year',+ 'in-or-after-fiscal-period-and-year', 'in-or-before-fiscal-period-and-year', 'last-fiscal-period',+ 'last-fiscal-year', 'last-month', 'last-seven-days', 'last-week', 'last-x-days',+ 'last-x-fiscal-periods', 'last-x-fiscal-years', 'last-x-hours', 'last-x-months', 'last-x-weeks',+ 'last-x-years', 'last-year', 'le', 'like', 'lt', 'ne', 'ne-businessid', 'ne-userid', 'neq',+ 'next-fiscal-period', 'next-fiscal-year', 'next-month', 'next-seven-days', 'next-week',+ 'next-x-days', 'next-x-fiscal-periods', 'next-x-fiscal-years', 'next-x-hours', 'next-x-months',+ 'next-x-weeks', 'next-x-years', 'next-year', 'not-begin-with', 'not-between',+ 'not-contain-values', 'not-end-with', 'not-in', 'not-like', 'not-null', 'not-under', 'null',+ 'olderthan-x-days', 'olderthan-x-hours', 'olderthan-x-minutes', 'olderthan-x-months',+ 'olderthan-x-weeks', 'olderthan-x-years', 'on', 'on-or-after', 'on-or-before',+ 'this-fiscal-period', 'this-fiscal-year', 'this-month', 'this-week', 'this-year', 'today',+ 'tomorrow', 'under', 'yesterday',+]);++// Cheap near-match for the "did you mean" hint, in the same spirit as the business-rule operator+// check. Catches the two mistakes that actually happen: wrong case (`EQ-USERID`) and a single+// dropped/extra/substituted character (`eq-useroruserteam`, `eq-businesid`).+function nearestFilterOp(op) {+ const lower = String(op).toLowerCase();+ for (const known of KNOWN_FILTER_OPS) if (known === lower) return known;+ for (const known of KNOWN_FILTER_OPS) {+ if (Math.abs(known.length - lower.length) > 1) continue;+ // Walk both strings once, allowing a single edit. Full Levenshtein is not worth it here.+ let i = 0, j = 0, edits = 0;+ while (i < known.length && j < lower.length) {+ if (known[i] === lower[j]) { i++; j++; continue; }+ if (++edits > 1) break;+ if (known.length > lower.length) i++;+ else if (known.length < lower.length) j++;+ else { i++; j++; }+ }+ if (edits + (known.length - i) + (lower.length - j) <= 1) return known;+ }+ return null;+}function lintAppSpec(spec) {const errors = [];@@ -294,9 +367,47 @@ function lintAppSpec(spec) {for (const f of v.filters || []) {if (!f.attr) { E(`View '${v.name}' has a filter without an attr`); continue; }const op = f.op || 'eq';- if (op === 'in' || op === 'not-in') {+ if (!KNOWN_FILTER_OPS.has(op)) {+ // Reported INSTEAD of the missing-value check below, never alongside it: `needs a value` is+ // wrong advice for an operator that does not exist, and acting on it produces a spec that+ // lints clean and then fails at the platform.+ const near = nearestFilterOp(op);+ W(`View '${v.name}' filter on '${f.attr}' uses '${op}', which is not a documented FetchXML condition operator${near ? ` — did you mean '${near}'?` : ''}. Dataverse will reject it when the view is built.`);+ } else if (op === 'in' || op === 'not-in') {if (!(Array.isArray(f.values) && f.values.length)) E(`View '${v.name}' filter on '${f.attr}' uses ${op} but has no values[]`);- } else if (!NO_VALUE_OPS.has(op) && f.value === undefined) {+ } else if (NO_VALUE_OPS.has(op)) {+ // A value on a value-less operator is a WARNING, not an error, and the distinction was+ // settled by measurement rather than assumption. Probed live against Dataverse Web API:+ // eq-businessid value="00000000-0000-0000-0000-000000000000" -> HTTP 200, 1 row+ // eq-businessid (no value) -> HTTP 200, 1 row+ // this-year value="1999" -> HTTP 200, 1 row+ // this-year (no value) -> HTTP 200, 1 row+ // The platform neither rejects the condition nor honours the value — it IGNORES it. So+ // erroring would block specs that build and run correctly today, while staying silent+ // leaves a filter that does not do what its `value` says. The author almost always meant+ // a value-TAKING operator (`eq` against a specific business unit) — hence the advice.+ //+ // Note this deliberately differs from the business-rule operator check in app-spec.js,+ // which ERRORS on the same shape. That is a different engine: a business rule is compiled+ // client-side, where the stray value is not harmless.+ //+ // The operator set spans several unrelated semantics (`null`/`not-null` test presence,+ // `eq-userlanguage` matches the user's language, the relative-date ones match a period), so+ // the message deliberately says only that the value has no effect — asserting a particular+ // match semantics would be wrong for most of the set.+ //+ // `value` and `values` are called out separately because they are dropped at different+ // points, and a message that named the wrong one would send the author to the wrong place:+ // `value` is forwarded into the condition and discarded by Dataverse (sdk-build.js emits it+ // for any non-in/not-in operator), whereas `values` is only ever read by the in/not-in+ // branch, so it never reaches the platform at all.+ if (f.value !== undefined) {+ W(`View '${v.name}' filter on '${f.attr}' uses the value-less operator '${op}' but also carries a value — it is sent to Dataverse and ignored there, so it has no effect on what the filter matches. Drop the value, or use a value-taking operator (e.g. 'eq') if you meant to match a specific row.`);+ }+ if (f.values !== undefined) {+ W(`View '${v.name}' filter on '${f.attr}' uses the value-less operator '${op}' but also carries values[] — values[] is only read by the 'in'/'not-in' operators, so it is dropped when the view is built. Drop it, or use 'in' if you meant to match a list.`);+ }+ } else if (f.value === undefined) {E(`View '${v.name}' filter on '${f.attr}' (${op}) needs a value`);}}@@ -421,4 +532,14 @@ function dupWarn(names, kind, W) {}}-module.exports = { lintAppSpec };+// The operator sets are exported FROZEN — as arrays, not the live Sets. The module-level Set is+// shared by every in-process consumer through the require cache, so handing out the instance would+// let one caller's `.add()`/`.delete()` silently change lint behaviour for everything else.+// Exported so the regression test can compare them against an independent, doc-derived literal list+// in BOTH directions — a missing/typo'd entry reintroduces the #546 false positive, and an extra+// (value-taking) entry silently disables the missing-value check.+module.exports = {+ lintAppSpec,+ NO_VALUE_OPS: Object.freeze([...NO_VALUE_OPS]),+ KNOWN_FILTER_OPS: Object.freeze([...KNOWN_FILTER_OPS]),+};diff --git a/plugins/model-apps/scripts/lint-app-spec.js b/plugins/model-apps/scripts/lint-app-spec.jsnew file mode 100644index 000000000..2b306cd41--- /dev/null+++ b/plugins/model-apps/scripts/lint-app-spec.js@@ -0,0 +1,229 @@+#!/usr/bin/env node+'use strict';+// lint-app-spec: validate and lint an App Spec WITHOUT touching an environment.+//+// WHY this exists (#560): `validateAppSpec` (the hard schema/deploy gate) and `lintAppSpec` (the+// authoring guardrails) were library exports with no entry point, and `build-model-app.js` has no+// lint-only flag. A headless author — a CI job, or an agent authoring a spec outside the interactive+// skill flow — had to reach in with `node -e "require('./lib/spec-lint.js')..."`, which is both+// undiscoverable and easy to get wrong (it is the MIGRATED spec that must be validated, not the+// file as written; see below).+//+// This runs the gates a build runs on load, plus the authoring guardrails:+// 1. migrateAppSpec — upgrade a legacy spec to schemaVersion 2 (mints page keys, rewrites+// name-refs). Skipping it lints a shape the build never sees.+// 2. validateAppSpec — the hard gate. Its errors are what `--apply` refuses on.+// 3. lintAppSpec — advisory guardrails: errors AND warnings. NOTE: `build-model-app.js` does+// NOT run this; it migrates and validates only. The `lint:` findings here+// are therefore ADDITIONAL to what the builder reports, which is the point —+// the skill's plan gate is where they are meant to be caught.+//+// Exit codes: 0 when there are no errors from either step (warnings alone do not fail, so a CI job+// can gate on correctness without being blocked by advice), 1 otherwise. `--strict` also fails on+// warnings, for a pipeline that wants them treated as errors.+//+// `--profile` selects validateAppSpec's strictness and DEFAULTS TO `plan`, not `deploy`. The deploy+// profile requires every generative page to be IMPLEMENTED (`source.kind: 'tsx'` with a codeFile),+// which a spec legitimately lacks until generate-pages runs — and that is exactly when the+// authoring flow invokes this. `plan` relaxes only that; it does NOT relax any other rule (a+// persona job still requires `privileges[]` under every profile). Pass `--profile deploy` to gate+// a final, deployable spec.+//+// Usage:+// node lint-app-spec.js --spec @<app-folder>/app-spec.json+// [--profile design|plan|deploy|structural] [--strict] [--json]++const { parseArgs, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');+const { validateAppSpec, migrateAppSpec, VALIDATION_PROFILES } = require('./lib/app-spec.js');+const { lintAppSpec } = require('./lib/spec-lint.js');++const USAGE = 'Usage: node lint-app-spec.js --spec @<path-to-app-spec.json> [--profile design|plan|deploy|structural] [--strict] [--json]';++// Pure core: spec in, report out. Exported so tests can assert the contract without spawning a+// process or writing fixture files to disk.+//+// `profile` selects how strict `validateAppSpec` is. It matters more than it looks: the DEPLOY+// profile requires every generative page to be implemented (`source.kind: 'tsx'` with a codeFile),+// which is deliberately not true while pages are still intents. Defaulting to deploy made this CLI+// reject a perfectly normal work-in-progress spec at the two gates the authoring flow actually runs+// it at, so the default is `plan`, the same profile the builder's own dry run uses. `plan` relaxes+// ONLY that rule — a persona job still requires `privileges[]` under every profile. A caller+// checking a FINAL, deployable spec+// (a CI gate before `--apply`) should pass `--profile deploy` explicitly.+function lintSpec(rawSpec, opts) {+ // `undefined` means "not supplied" and takes the default. Anything else — including the EMPTY+ // STRING — is a supplied value and must face the allow-list. `|| 'plan'` folded `''` into the+ // default, so a CI wrapper whose `--profile=$PROFILE` expanded to empty silently ran the weaker+ // plan gate while believing it had requested `deploy`.+ const profile = opts && opts.profile !== undefined ? opts.profile : 'plan';+ if (!VALIDATION_PROFILES.includes(profile)) {+ const named = typeof profile === 'string' && profile.trim() ? `unknown profile '${profile}'` : `empty profile value`;+ // Tagged `schema:` like every other error from this function. authoring-flow.md tells the agent+ // to triage on that prefix ("fix the `schema:` ones first"), so an untagged error has no bucket.+ // A bad profile IS a rejection of the validate gate's own argument, so `schema:` is its home.+ return { ok: false, profile, errors: [`schema: ${named} (valid: ${VALIDATION_PROFILES.join(', ')})`], warnings: [] };+ }+ const spec = migrateAppSpec(rawSpec);++ // validateAppSpec is the gate `--apply` enforces, so its findings are reported FIRST and tagged+ // as such: an author who fixes lint advice while a schema error stands has fixed nothing.+ const validation = validateAppSpec(spec, { profile });+ const validationErrors = (validation && validation.errors) || [];+ // validateAppSpec also emits non-blocking advisories the build narrates (e.g. a Customer-column+ // description Dataverse will not store). Dropping them here would make this CLI quieter than the+ // build it stands in for, and would let `--strict` pass on a spec the build warns about.+ const validationWarnings = (validation && validation.warnings) || [];++ // A spec that fails the schema gate can put lintAppSpec in front of shapes it never expects+ // (a null entity, a string where a list belongs). The lint already guards its own collections,+ // but it is downstream advice either way — keep a crash from masking the real, already-known+ // schema errors. The crash is REPORTED, not swallowed, so a genuine lint defect still surfaces.+ let lint = { ok: true, errors: [], warnings: [] };+ try {+ lint = lintAppSpec(spec) || lint;+ } catch (err) {+ lint = { ok: false, errors: [`lint could not run on this spec: ${err.message}`], warnings: [] };+ }++ const errors = [+ ...validationErrors.map((e) => `schema: ${e}`),+ ...((lint.errors || []).map((e) => `lint: ${e}`)),+ ];+ const warnings = [+ ...validationWarnings.map((w) => `schema: ${w}`),+ ...((lint.warnings || []).map((w) => `lint: ${w}`)),+ ];++ return { ok: errors.length === 0, profile, errors, warnings, schemaVersion: spec && spec.schemaVersion };+}++function main() {+ const { positional, flags } = parseArgs(process.argv.slice(2));++ // Every usage error below must still be readable by the DOCUMENTED caller, which invokes this+ // with `--json` and parses stdout (authoring-flow.md, app-builder/SKILL.md). emitResult writes a+ // bare Error to stderr only, leaving stdout empty — and `JSON.parse('')` throws, so an agent+ // following the documented flow gets a crash instead of the usage message. Emit the same shape+ // the success path does when --json was asked for.+ const wantsJson = flags.json === true || flags.json === 'true';+ const usageError = (message) => {+ if (wantsJson) {+ process.stdout.write(JSON.stringify({ ok: false, profile: null, errors: [`usage: ${message}`], warnings: [] }) + '\n');+ process.stderr.write(message + '\n');+ process.exitCode = 1;+ return undefined;+ }+ return emitResult(false, new Error(message));+ };++ // `--help` is not "unknown" — it is a request this tool simply answers with its usage. Rejecting+ // it reads as though the tool is broken, and the sibling CLIs in this directory (capture-fixture,+ // generate-page-manifest) both honour it.+ if (flags.help === true || flags.h === true) {+ process.stdout.write(USAGE + '\n');+ process.exitCode = 0;+ return;+ }++ // Unknown flags are a USAGE ERROR, not something to ignore. parseArgs accepts any `--name`, so a+ // typo (`--profle deploy`) would otherwise be dropped and the command would run the DEFAULT plan+ // profile while exiting 0 — a CI job reporting success for a gate it never applied. This CLI ships+ // in this change, so no caller can be relying on a flag outside this set.+ //+ // Read from argv rather than Object.keys(flags): assigning to `flags['__proto__']` goes through+ // the inherited setter and never becomes an own property, so `--__proto__ deploy` would slip the+ // allow-list AND swallow the next token. Same hazard modelapps-hook-utils.js guards with+ // Object.create(null).+ const KNOWN_FLAGS = new Set(['spec', 'profile', 'strict', 'json', 'help', 'h']);+ const passedFlagNames = process.argv.slice(2)+ .filter((a) => a.startsWith('--'))+ .map((a) => a.slice(2).split('=')[0]);+ const unknown = [...new Set(passedFlagNames.filter((k) => !KNOWN_FLAGS.has(k)))];+ if (unknown.length > 0) {+ return usageError(`unknown flag(s): ${unknown.map((k) => '--' + k).join(', ')}\n${USAGE}`);+ }+ // A positional argument is equally suspect: `--spec` is the only way to name the file. But the+ // overwhelmingly likely cause on Windows is an UNQUOTED path containing spaces — the documented+ // flow passes an absolute path, and `C:\Users\x\OneDrive - Contoso\app-spec.json` splits into a+ // truncated `--spec` plus stray tokens. Naming what `--spec` actually parsed to points straight+ // at the cause; a bare "the spec is named with --spec" points away from it, because the caller+ // did exactly that.+ if (positional.length > 0) {+ const parsed = typeof flags.spec === 'string' ? ` --spec was parsed as '${flags.spec}'` : '';+ const hint = parsed+ ? `${parsed} — if the path contains spaces, quote it: --spec "@C:\\path with spaces\\app-spec.json"`+ : ' — the spec is named with --spec';+ return usageError(`unexpected argument(s): ${positional.join(', ')}${hint}\n${USAGE}`);+ }++ // parseArgs yields `true` for a bare `--flag` and a string for `--flag=value` / `--flag value`.+ // For a VALUE-taking flag, that bare `true` is a usage error and must be rejected rather than+ // coerced: a bare `--profile` silently falling back to the default would skip a `deploy` gate a+ // CI job believed it had requested, and a bare `--spec` would reach readJsonArg and surface as+ // "spec is not an object" — a gate report about a file the caller never named.+ const isOn = (v) => v === true || v === 'true';+ const specArg = flags.spec;+ if (specArg === undefined) return usageError(USAGE);+ if (typeof specArg !== 'string' || !specArg.trim()) return usageError(`--spec needs a path\n${USAGE}`);+ if (flags.profile !== undefined && (typeof flags.profile !== 'string' || !flags.profile.trim())) {+ // Covers both the bare `--profile` (boolean true) and `--profile=` / `--profile ''` (empty+ // string). Both are a caller who asked for a profile and did not supply one; neither may fall+ // through to the default.+ return usageError(`--profile needs one of: ${VALIDATION_PROFILES.join(', ')}\n${USAGE}`);+ }++ let rawSpec;+ try {+ rawSpec = readJsonArg(specArg.startsWith('@') ? specArg : '@' + specArg);+ } catch (err) {+ // A spec that is not readable/parseable is the single most common "why did nothing happen"+ // failure, so name the file and the parser's own message rather than a generic gate error.+ // Routed through usageError for the same reason as the flag checks: the documented caller reads+ // stdout as JSON, and an empty stdout throws in JSON.parse instead of reporting this message.+ return usageError(`could not read spec ${specArg}: ${err.message}`);+ }++ const report = lintSpec(rawSpec, { profile: flags.profile });+ const strict = isOn(flags.strict);+ const failed = !report.ok || (strict && report.warnings.length > 0);++ if (isOn(flags.json)) {+ // Deliberately NOT emitResult: its structured-failure branch reports+ // "Operation completed with N error(s)" off `payload.errors`, which for a warnings-only+ // `--strict` failure prints "0 error(s)" next to a non-zero exit — and the payload's own `ok`+ // must describe the COMMAND's outcome, not just whether errors were found.+ process.stdout.write(JSON.stringify({ ...report, ok: !failed }) + '\n');+ if (failed) {+ process.stderr.write(+ report.errors.length > 0+ ? `app spec has ${report.errors.length} error(s); see stdout JSON\n`+ : `app spec has ${report.warnings.length} warning(s) and --strict was set; see stdout JSON\n`+ );+ }+ // Set the code and RETURN rather than process.exit(). Node's stdout is asynchronous when it is a+ // TTY on Windows, and process.exit() tears the process down without draining it — so an+ // interactive Windows run of a large report could lose its tail. MEASURED: a 5 MB write over a+ // PIPE survives process.exit() intact on Windows, so a `--json | jq` CI consumer was never at+ // risk; this is the interactive case and the idiomatic pattern, not a fix for a reproduced bug.+ // The non-JSON usage-error paths still exit through emitResult's process.exit() — deliberately+ // out of scope here, since that is shared behaviour across every CLI in this directory.+ // https://nodejs.org/api/process.html#a-note-on-process-io+ process.exitCode = failed ? 1 : 0;+ return;+ }++ for (const e of report.errors) process.stderr.write(`ERROR ${e}\n`);+ for (const w of report.warnings) process.stderr.write(`WARN ${w}\n`);+ process.stdout.write(+ `${failed ? 'FAIL' : 'OK'} [profile: ${report.profile}] — ${report.errors.length} error(s), ${report.warnings.length} warning(s)` ++ `${strict && report.errors.length === 0 && report.warnings.length > 0 ? ' (failed by --strict)' : ''}\n`+ );+ // Same reason as the --json branch: the report goes out before the process is allowed to end.+ process.exitCode = failed ? 1 : 0;+}++if (require.main === module) {+ main();+}++module.exports = { lintSpec };diff --git a/plugins/model-apps/scripts/tests/app-spec-migrate.test.js b/plugins/model-apps/scripts/tests/app-spec-migrate.test.jsindex 4a6eeb505..f45724a94 100644--- a/plugins/model-apps/scripts/tests/app-spec-migrate.test.js+++ b/plugins/model-apps/scripts/tests/app-spec-migrate.test.js@@ -63,6 +63,118 @@ test('mints a fallback key for a page with a blank name', () => {assert.strictEqual(migrateAppSpec(legacy).pages[0].key, 'page');});+// #545 Case 1 regression. A spec may declare schemaVersion 2 on each PAGE (and carry hand-authored+// stable keys and key-based refs) while omitting the TOP-LEVEL schemaVersion. Migration then runs,+// and pass 1 used to mint `p.key = slugify(p.name)` UNCONDITIONALLY — overwriting the author's keys.+// The refs are keys, not names, so pass 2 left them pointing at the now-discarded keys, and+// validateAppSpec reported one "not a known page key" / "unknown page" error per page, none of+// which named the real cause. Adding the top-level schemaVersion "fixed" it only because that made+// migration a no-op. An authored key must survive migration.+test('#545: preserves hand-authored page keys when only the top-level schemaVersion is missing', () => {+ const authored = {+ solution: { uniqueName: 'c', publisherPrefix: 'c' }, app: { name: 'C' },+ entities: [{ schemaName: 'c_order', primaryAttribute: { schemaName: 'c_name' }, columns: [] }],+ pages: [+ // Keys deliberately DIFFER from slugify(name), which is what makes the clobber observable.+ { schemaVersion: 2, key: 'orders', name: 'All Open Orders', source: { kind: 'tsx', codeFile: 'orders.tsx' }, navigatesTo: [{ targetKey: 'order-card' }] },+ { schemaVersion: 2, key: 'order-card', name: 'Order Details View', source: { kind: 'tsx', codeFile: 'card.tsx' } },+ ],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Main', subAreas: [{ title: 'Orders', page: 'orders' }, { title: 'Card', page: 'order-card' }] }] }] },+ };+ const m = migrateAppSpec(authored);+ assert.strictEqual(m.schemaVersion, 2);+ assert.strictEqual(m.pages[0].key, 'orders', 'authored key survives migration (not re-slugged from the name)');+ assert.strictEqual(m.pages[1].key, 'order-card');+ assert.strictEqual(m.pages[0].navigatesTo[0].targetKey, 'order-card', 'key-based navigatesTo still resolves');+ assert.deepStrictEqual(m.appShell.areas[0].groups[0].subAreas.map((s) => s.page), ['orders', 'order-card']);+ const r = validateAppSpec(m);+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+});++// Mixed spec: some pages carry an authored key, others do not. Every authored key must be RESERVED+// before any key is minted, or a minted slug can collide with an authored key declared later and+// silently steal it.+test('#545: mints only for keyless pages, and never mints over a later authored key', () => {+ const authored = {+ solution: { uniqueName: 'c', publisherPrefix: 'c' }, app: { name: 'C' }, entities: [],+ pages: [+ { name: 'Orders', source: { kind: 'intent' } }, // keyless -> slug would be 'orders'+ { key: 'orders', name: 'Legacy Orders', source: { kind: 'intent' } }, // authored 'orders' declared LATER+ ],+ };+ const m = migrateAppSpec(authored);+ assert.strictEqual(m.pages[1].key, 'orders', 'the authored key wins');+ assert.strictEqual(m.pages[0].key, 'orders-2', 'the minted key yields to the reserved authored key');+});++// An authored key that violates the key grammar must NOT be silently replaced: validateAppSpec+// reports it by name, which is a message the author can act on. Silently re-slugging it would+// resurrect the same dangling-reference failure this fix exists to remove.+test('#545: a malformed authored key is preserved so validation can name it', () => {+ const authored = {+ solution: { uniqueName: 'c', publisherPrefix: 'c' }, app: { name: 'C' }, entities: [],+ pages: [{ key: 'Not A Slug', name: 'Orders', source: { kind: 'intent' } }],+ };+ const m = migrateAppSpec(authored);+ assert.strictEqual(m.pages[0].key, 'Not A Slug');+ const r = validateAppSpec(m);+ assert.strictEqual(r.ok, false);+ assert.ok(r.errors.some((e) => e.includes('Not A Slug') && e.includes('invalid key grammar')), JSON.stringify(r.errors));+});++// Regression contract for the #545 fix. Once authored keys survive migration, a reference can legitimately+// already BE a key — and a spec may hold a page whose authored key equals a DIFFERENT page's name.+// Rewriting name-first silently retargets the reference to the other page AND still validates,+// because the substituted value is itself a valid key. An exact key match must win.+test('#545: an authored key that equals another page\'s name is not retargeted by the name rewrite', () => {+ const authored = {+ solution: { uniqueName: 'c', publisherPrefix: 'c' }, app: { name: 'C' }, entities: [],+ pages: [+ { key: 'orders', name: 'All Orders', source: { kind: 'intent' }, navigatesTo: [{ targetKey: 'orders' }] },+ { key: 'report', name: 'orders', source: { kind: 'intent' } },+ ],+ appShell: { areas: [{ label: 'M', groups: [{ label: 'M', subAreas: [{ title: 'O', page: 'orders' }] }] }] },+ };+ const m = migrateAppSpec(authored);+ assert.strictEqual(m.pages[0].navigatesTo[0].targetKey, 'orders', "the key ref stays on the page that OWNS the key, not the page NAMED 'orders'");+ assert.strictEqual(m.appShell.areas[0].groups[0].subAreas[0].page, 'orders');+});++// Regression contract. The key-first rewrite must key off AUTHORED keys, not every final key. A MINTED+// key is derived from a name, so it collides with a different page's name by construction: pages+// "All Orders" and "all-orders" mint 'all-orders' and 'all-orders-2'. Treating a minted key as+// authoritative left a legacy name-ref to the SECOND page pointing at the first.+test('#545: a legacy name-ref is still resolved by name when the match is a MINTED key', () => {+ const legacy = {+ solution: { uniqueName: 'c', publisherPrefix: 'c' }, app: { name: 'C' }, entities: [],+ pages: [+ { name: 'All Orders', codeFile: 'a.tsx' },+ { name: 'all-orders', codeFile: 'b.tsx', navigatesTo: [{ targetKey: 'all-orders' }] },+ ],+ };+ const m = migrateAppSpec(legacy);+ assert.deepStrictEqual(m.pages.map((p) => p.key), ['all-orders', 'all-orders-2']);+ assert.strictEqual(m.pages[1].navigatesTo[0].targetKey, 'all-orders-2',+ 'the name-ref names the SECOND page; a minted key must not capture it');+});++// Regression contract. A key the author WROTE but got wrong must reach validation unchanged. Minting+// over it silently repairs a typo the author needs to see — and contradicts the preservation this+// pass documents. Only a page with no `key` property at all gets one minted.+test('#545: a present-but-malformed key is preserved verbatim for validation to name', () => {+ for (const key of [42, '', ' ', null]) {+ const s = { solution: { uniqueName: 'c', publisherPrefix: 'c' }, app: { name: 'C' }, entities: [], pages: [{ key, name: 'Orders', source: { kind: 'intent' } }] };+ const m = migrateAppSpec(s);+ assert.deepStrictEqual(m.pages[0].key, key, `key ${JSON.stringify(key)} must survive migration`);+ const r = validateAppSpec(m, { profile: 'plan' });+ assert.ok(r.errors.some((e) => /stable key|invalid key grammar/.test(e)),+ `validation must name the key problem for ${JSON.stringify(key)}: ${JSON.stringify(r.errors)}`);+ }+ // ...while a page with NO key property still gets one minted, as before.+ const s = { solution: { uniqueName: 'c', publisherPrefix: 'c' }, app: { name: 'C' }, entities: [], pages: [{ name: 'Orders', source: { kind: 'intent' } }] };+ assert.strictEqual(migrateAppSpec(s).pages[0].key, 'orders');+});+// IMPORTANT #2 regression: a navigatesTo name-ref whose target name collides with a minted key// for a DIFFERENT page must resolve to the correct (first) page and not be double-rewritten.//diff --git a/plugins/model-apps/scripts/tests/lint-app-spec.test.js b/plugins/model-apps/scripts/tests/lint-app-spec.test.jsnew file mode 100644index 000000000..bab0ce14d--- /dev/null+++ b/plugins/model-apps/scripts/tests/lint-app-spec.test.js@@ -0,0 +1,391 @@+// #560: lint-app-spec.js is the CLI surface for the two gates that previously had none.+// The contract that matters is that it runs the SAME three steps a deploying CLI runs on load+// (migrate -> validate -> lint) — linting the file as written instead of the migrated shape is+// exactly the mistake the `node -e` workaround invited.++const { test } = require('node:test');+const assert = require('node:assert');+const path = require('node:path');+const { execFileSync } = require('node:child_process');+const fs = require('node:fs');+const os = require('node:os');++const { lintSpec } = require('../lint-app-spec.js');++const CLI = path.join(__dirname, '..', 'lint-app-spec.js');++const good = () => ({+ solution: { uniqueName: 'c', publisherPrefix: 'c' },+ app: { name: 'C' },+ entities: [{ schemaName: 'c_order', displayName: 'Order', pluralName: 'Orders', primaryAttribute: { schemaName: 'c_name', displayName: 'Name' }, columns: [] }],+ forms: [], views: [], charts: [],+});++test('a clean spec reports ok with no errors', () => {+ const r = lintSpec(good());+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+ assert.deepStrictEqual(r.errors, []);+ assert.strictEqual(r.profile, 'plan', 'the default profile is plan, not deploy');+});++// Regression contract. validateAppSpec defaults to the DEPLOY profile, which requires every generative+// page to be implemented and every persona job to carry privileges. Both are deliberately absent+// while a spec is being authored — which is exactly when the documented gates run this CLI — so a+// deploy default rejected normal work-in-progress specs and would have broken the authoring flow.+test('the default profile accepts a work-in-progress spec that the deploy profile rejects', () => {+ const s = good();+ s.pages = [{ key: 'ov', name: 'Overview', purpose: 'overview', source: { kind: 'intent' } }];+ s.appShell = { areas: [{ label: 'M', groups: [{ label: 'M', subAreas: [{ title: 'Overview', page: 'ov' }] }] }] };++ const dflt = lintSpec(s);+ assert.strictEqual(dflt.ok, true, `an intent page must pass the default gate: ${JSON.stringify(dflt.errors)}`);++ const deploy = lintSpec(s, { profile: 'deploy' });+ assert.strictEqual(deploy.ok, false, 'deploy still requires the page to be implemented');+ assert.ok(deploy.errors.some((e) => /must be implemented/.test(e)), JSON.stringify(deploy.errors));+});++test('an unknown profile is rejected by name rather than silently falling back', () => {+ const r = lintSpec(good(), { profile: 'nope' });+ assert.strictEqual(r.ok, false);+ assert.ok(r.errors.some((e) => /unknown profile 'nope'/.test(e)), JSON.stringify(r.errors));+});++// Regression contract. `|| 'plan'` treated the EMPTY STRING as "not supplied". A supplied-but-empty+// profile is a caller who asked for a profile and gave none — most plausibly a CI wrapper whose+// `--profile=$PROFILE` expanded empty — and folding it into the default silently ran the weaker plan+// gate while the job believed it had requested `deploy`. Only `undefined` may take the default.+test('an EMPTY profile is rejected rather than silently defaulting to plan', () => {+ for (const profile of ['', ' ']) {+ const r = lintSpec(good(), { profile });+ assert.strictEqual(r.ok, false, `profile ${JSON.stringify(profile)} must not be accepted`);+ assert.ok(r.errors.some((e) => /empty profile value|unknown profile/.test(e)), JSON.stringify(r.errors));+ assert.notStrictEqual(r.profile, 'plan', 'must not report the default it did not run');+ }+ assert.strictEqual(lintSpec(good(), { profile: undefined }).profile, 'plan', 'omitted still takes the default');+ assert.strictEqual(lintSpec(good(), {}).profile, 'plan');+});++// Regression contract. validateAppSpec emits non-blocking advisories of its own, which the build narrates.+// Reporting only lint warnings made this CLI quieter than the build it stands in for.+test('warnings from BOTH gates are reported, each tagged with its source', () => {+ const s = good();+ // Two pre-existing (pageId-bearing) pages sharing a name is a validateAppSpec WARNING.+ s.pages = [+ { key: 'a', name: 'Overview', pageId: 'p1', source: { kind: 'tsx', codeFile: 'a.tsx' } },+ { key: 'b', name: 'overview', pageId: 'p2', source: { kind: 'tsx', codeFile: 'b.tsx' } },+ ];+ s.appShell = { areas: [{ label: 'M', groups: [{ label: 'M', subAreas: [{ title: 'A', page: 'a' }, { title: 'B', page: 'b' }] }] }] };+ const r = lintSpec(s);+ assert.ok(r.warnings.some((w) => w.startsWith('schema: ')), `expected a schema-tagged warning: ${JSON.stringify(r.warnings)}`);+});++test('schema (validateAppSpec) findings are reported and tagged "schema:"', () => {+ const s = good();+ delete s.solution;+ const r = lintSpec(s);+ assert.strictEqual(r.ok, false);+ assert.ok(r.errors.some((e) => e.startsWith('schema: ')), JSON.stringify(r.errors));+});++test('lint (lintAppSpec) findings are reported and tagged "lint:"', () => {+ const s = good();+ // A view filter with a value-taking operator and no value is a lint error, not a schema error.+ s.views = [{ entity: 'c_order', name: 'Mine', columns: ['c_name'], filters: [{ attr: 'c_name', op: 'eq' }] }];+ const r = lintSpec(s);+ assert.strictEqual(r.ok, false);+ assert.ok(r.errors.some((e) => e.startsWith('lint: ')), JSON.stringify(r.errors));+});++// The load-bearing behaviour: the spec is MIGRATED before either gate sees it. A legacy spec with+// name-based refs is valid only after migration, so linting the raw file would report false errors.+test('the spec is migrated before validation (a legacy spec is not reported as broken)', () => {+ const legacy = {+ ...good(),+ pages: [{ name: 'Sales Overview', codeFile: 'sales.tsx' }],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Main', subAreas: [{ title: 'Sales Overview', page: 'Sales Overview' }] }] }] },+ };+ const r = lintSpec(legacy);+ assert.strictEqual(r.schemaVersion, 2, 'migration ran');+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+});++test('warnings alone do not fail (so CI can gate on correctness, not advice)', () => {+ const s = good();+ // "Active <Plural>" collides with the stock default view — a documented WARNING.+ s.views = [{ entity: 'c_order', name: 'Active Orders', columns: ['c_name'], activeOnly: true }];+ const r = lintSpec(s);+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+ assert.ok(r.warnings.length > 0, 'expected the stock-default-view warning');+ assert.ok(r.warnings.every((w) => /^(schema|lint): /.test(w)), `every warning is source-tagged: ${JSON.stringify(r.warnings)}`);+});++function runCli(spec, extraArgs) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'lint-app-spec-'));+ const file = path.join(dir, 'app-spec.json');+ fs.writeFileSync(file, JSON.stringify(spec));+ try {+ const stdout = execFileSync(process.execPath, [CLI, '--spec', '@' + file, ...(extraArgs || [])], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+ return { code: 0, stdout };+ } catch (err) {+ return { code: err.status, stdout: String(err.stdout || ''), stderr: String(err.stderr || '') };+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+}++test('CLI exits 0 on a clean spec and 1 when a gate fails', () => {+ const ok = runCli(good());+ assert.strictEqual(ok.code, 0, ok.stdout + (ok.stderr || ''));+ assert.match(ok.stdout, /^OK \[profile: plan\] — 0 error\(s\)/m);++ const bad = good();+ delete bad.solution;+ const fail = runCli(bad);+ assert.strictEqual(fail.code, 1);+ assert.match(fail.stderr, /ERROR {2}schema: /);+});++test('CLI --profile deploy is available for gating a final, deployable spec', () => {+ const s = good();+ s.pages = [{ key: 'ov', name: 'Overview', purpose: 'overview', source: { kind: 'intent' } }];+ s.appShell = { areas: [{ label: 'M', groups: [{ label: 'M', subAreas: [{ title: 'Overview', page: 'ov' }] }] }] };+ assert.strictEqual(runCli(s).code, 0, 'passes the default plan gate');+ const deploy = runCli(s, ['--profile', 'deploy']);+ assert.strictEqual(deploy.code, 1);+ assert.match(deploy.stdout, /FAIL \[profile: deploy\]/);+});++// Regression contract. The JSON payload's `ok` must describe the COMMAND's outcome. A warnings-only+// --strict run exits 1, so emitting ok:true there would let a machine consumer read a failure as+// a success.+test('CLI --strict --json reports ok:false and exits 1 on warnings alone', () => {+ const s = good();+ s.views = [{ entity: 'c_order', name: 'Active Orders', columns: ['c_name'], activeOnly: true }];+ const out = runCli(s, ['--strict', '--json']);+ assert.strictEqual(out.code, 1);+ const payload = JSON.parse(out.stdout);+ assert.strictEqual(payload.ok, false, 'JSON status must match the exit code');+ assert.deepStrictEqual(payload.errors, []);+ assert.ok(payload.warnings.length > 0);+ assert.match(out.stderr, /--strict was set/);+ // The misleading "completed with 0 error(s)" summary must not appear for a warnings-only failure.+ assert.doesNotMatch(out.stderr, /completed with 0 error\(s\)/);+});++test('CLI --json on a clean spec reports ok:true and exits 0', () => {+ const out = runCli(good(), ['--json']);+ assert.strictEqual(out.code, 0);+ const payload = JSON.parse(out.stdout);+ assert.strictEqual(payload.ok, true);+ assert.strictEqual(payload.profile, 'plan');+});++test('CLI --strict turns warnings into a failure', () => {+ const s = good();+ s.views = [{ entity: 'c_order', name: 'Active Orders', columns: ['c_name'], activeOnly: true }];+ assert.strictEqual(runCli(s).code, 0, 'warnings alone pass without --strict');+ const strict = runCli(s, ['--strict']);+ assert.strictEqual(strict.code, 1);+ assert.match(strict.stdout, /failed by --strict/);+});++test('CLI reports an unreadable spec by name rather than a generic gate error', () => {+ let out;+ try {+ execFileSync(process.execPath, [CLI, '--spec', '@does-not-exist.json'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+ out = { code: 0 };+ } catch (err) {+ out = { code: err.status, stderr: String(err.stderr || '') };+ }+ assert.strictEqual(out.code, 1);+ assert.match(out.stderr, /could not read spec @does-not-exist\.json/);+});++test('CLI with no --spec prints usage', () => {+ let out;+ try {+ execFileSync(process.execPath, [CLI], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+ out = { code: 0 };+ } catch (err) {+ out = { code: err.status, stderr: String(err.stderr || '') };+ }+ assert.strictEqual(out.code, 1);+ assert.match(out.stderr, /Usage: node lint-app-spec\.js/);+});++// Regression contract. parseArgs turns a bare `--flag` into `true`. For a VALUE-taking flag that is a+// usage error, not a default: a bare `--profile` silently falling back to `plan` would skip a+// `deploy` gate a CI job believed it had requested, and a bare `--spec` would reach readJsonArg and+// report "spec is not an object" — a gate verdict about a file the caller never named.+test('CLI rejects a value-taking flag given with no value', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'lint-app-spec-'));+ const file = path.join(dir, 'app-spec.json');+ fs.writeFileSync(file, JSON.stringify(good()));+ try {+ for (const [args, expected] of [+ [[CLI, '--spec'], /--spec needs a path/],+ [[CLI, '--spec', '@' + file, '--profile'], /--profile needs one of: design, plan, deploy, structural/],+ ]) {+ let out;+ try {+ execFileSync(process.execPath, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+ out = { code: 0, stderr: '' };+ } catch (err) {+ out = { code: err.status, stderr: String(err.stderr || '') };+ }+ assert.strictEqual(out.code, 1, `expected a usage failure for ${args.slice(1).join(' ')}`);+ assert.match(out.stderr, expected);+ assert.doesNotMatch(out.stderr, /spec is not an object/, 'a usage error must not surface as a gate verdict');+ }+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++// Regression contract. parseArgs preserves `--profile=` as the EMPTY STRING, which passed the+// bare-flag guard (it is a string) and was then folded into the default by `|| 'plan'`. A CI wrapper+// whose `--profile=$PROFILE` expanded empty therefore ran the weaker plan gate and exited 0 while+// believing it had requested `deploy`.+test('CLI rejects an EMPTY value-taking flag instead of silently taking the default', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'lint-app-spec-'));+ const file = path.join(dir, 'app-spec.json');+ fs.writeFileSync(file, JSON.stringify(good()));+ try {+ for (const [args, expected] of [+ [[CLI, '--spec', '@' + file, '--profile='], /--profile needs one of: design, plan, deploy, structural/],+ [[CLI, '--spec', '@' + file, '--profile', ''], /--profile needs one of: design, plan, deploy, structural/],+ [[CLI, '--spec='], /--spec needs a path/],+ ]) {+ let out;+ try {+ execFileSync(process.execPath, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+ out = { code: 0, stdout: '', stderr: '' };+ } catch (err) {+ out = { code: err.status, stdout: String(err.stdout || ''), stderr: String(err.stderr || '') };+ }+ assert.strictEqual(out.code, 1, `expected a usage failure for ${args.slice(1).join(' ')}`);+ assert.match(out.stderr, expected);+ assert.doesNotMatch(out.stdout, /OK \[profile: plan\]/, 'must not run the default gate it was not asked for');+ }+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++// Regression contract. parseArgs accepts any `--name`, so a typo was silently dropped and the+// command ran the DEFAULT plan profile — a CI job reporting success for a gate it never applied.+test('CLI rejects an unknown flag rather than silently running the default gate', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'lint-app-spec-'));+ const file = path.join(dir, 'app-spec.json');+ fs.writeFileSync(file, JSON.stringify(good()));+ try {+ for (const [args, expected] of [+ [[CLI, '--spec', '@' + file, '--profle', 'deploy'], /unknown flag\(s\): --profle/],+ [[CLI, '--spec', '@' + file, '--strictt'], /unknown flag\(s\): --strictt/],+ [[CLI, '@' + file], /unexpected argument\(s\)/],+ ]) {+ let out;+ try {+ execFileSync(process.execPath, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+ out = { code: 0, stdout: '', stderr: '' };+ } catch (err) {+ out = { code: err.status, stdout: String(err.stdout || ''), stderr: String(err.stderr || '') };+ }+ assert.strictEqual(out.code, 1, `expected a usage failure for ${args.slice(1).join(' ')}`);+ assert.match(out.stderr, expected);+ assert.doesNotMatch(out.stdout, /OK \[profile: plan\]/, 'a typo must not report a passing gate');+ }+ // The complement: every KNOWN flag combination still runs. (No --strict here: the fixture emits+ // warnings, which --strict correctly turns into a non-zero exit — that is tested separately.)+ const ok = execFileSync(process.execPath, [CLI, '--spec', '@' + file, '--profile', 'plan', '--json'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+ assert.strictEqual(JSON.parse(ok).ok, true, ok);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++// Regression contract. The positional guard fired BEFORE --spec was inspected, so the most common+// Windows failure — an unquoted absolute path containing spaces, which the documented flow invites —+// lost its diagnostic. The old message named the truncated file; the new one must too, or it points+// the reader away from the cause by asserting they should have used --spec, which they did.+test('CLI names the truncated --spec value when an unquoted path with spaces splits', () => {+ let out;+ try {+ execFileSync(process.execPath, [CLI, '--spec', '@C:\\Users\\x\\OneDrive', '-', 'Contoso\\app-spec.json'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+ out = { code: 0, stderr: '' };+ } catch (err) {+ out = { code: err.status, stderr: String(err.stderr || '') };+ }+ assert.strictEqual(out.code, 1);+ assert.match(out.stderr, /--spec was parsed as '@C:\\Users\\x\\OneDrive'/);+ assert.match(out.stderr, /quote it/);+});++// Regression contract. The documented invocation is `--spec @<path> --json` and the caller parses+// stdout. A usage error that writes only to stderr leaves stdout empty, and JSON.parse('') throws —+// so an agent following the documented flow crashes instead of reporting the usage message.+test('CLI --json emits a parseable payload for usage errors too, never empty stdout', () => {+ for (const args of [+ [CLI, '--json', '--profle', 'deploy', '--spec', '@x.json'],+ [CLI, '--json', '--spec', '@does-not-exist.json'],+ [CLI, '--json'],+ ]) {+ let out;+ try {+ execFileSync(process.execPath, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+ out = { code: 0, stdout: '', stderr: '' };+ } catch (err) {+ out = { code: err.status, stdout: String(err.stdout || ''), stderr: String(err.stderr || '') };+ }+ assert.strictEqual(out.code, 1, args.join(' '));+ const payload = JSON.parse(out.stdout);+ assert.strictEqual(payload.ok, false);+ assert.ok(Array.isArray(payload.errors) && payload.errors.length > 0, out.stdout);+ assert.ok(payload.errors.every((e) => e.startsWith('usage: ')), `usage errors are tagged so an agent can bucket them: ${out.stdout}`);+ }+});++// Regression contract. --help is a request this tool can answer, not an unknown flag. The sibling+// CLIs in this directory honour it, and rejecting it reads as though the tool is broken.+test('CLI --help prints usage and exits 0', () => {+ const out = execFileSync(process.execPath, [CLI, '--help'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+ assert.match(out, /Usage: node lint-app-spec\.js/);+});++// Regression contract. authoring-flow.md tells the agent to triage on the schema:/lint: prefix,+// so an untagged error has no bucket. Nothing pinned the invariant on the errors side.+test('EVERY error is source-tagged, including a rejected profile', () => {+ const bad = lintSpec(good(), { profile: 'DEPLOY' });+ assert.strictEqual(bad.ok, false);+ assert.ok(bad.errors.every((e) => /^(schema|lint): /.test(e)), JSON.stringify(bad.errors));++ const s = good();+ delete s.solution;+ s.views = [{ entity: 'c_order', name: 'Mine', columns: ['c_name'], filters: [{ attr: 'c_name', op: 'eq' }] }];+ const r = lintSpec(s);+ assert.ok(r.errors.length > 1);+ assert.ok(r.errors.every((e) => /^(schema|lint): /.test(e)), JSON.stringify(r.errors));+});++// Regression contract. parseArgs accumulates into a plain `{}`, so assigning `flags['__proto__']`+// goes through the inherited setter and never becomes an own property: an allow-list built on+// Object.keys(flags) would miss `--__proto__` entirely AND silently swallow the token after it.+// The allow-list therefore reads the flag NAMES from argv, which cannot be fooled this way.+test('CLI rejects prototype-named flags that never become own properties', () => {+ for (const args of [+ [CLI, '--__proto__', 'deploy', '--spec', '@x.json'],+ [CLI, '--__proto__=deploy', '--spec', '@x.json'],+ [CLI, '--constructor', '--spec', '@x.json'],+ ]) {+ let out;+ try {+ execFileSync(process.execPath, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+ out = { code: 0, stderr: '' };+ } catch (err) {+ out = { code: err.status, stderr: String(err.stderr || '') };+ }+ assert.strictEqual(out.code, 1, `expected a usage failure for ${args.slice(1).join(' ')}`);+ assert.match(out.stderr, /unknown flag\(s\): --(__proto__|constructor)/);+ }+});diff --git a/plugins/model-apps/scripts/tests/source-literals.test.js b/plugins/model-apps/scripts/tests/source-literals.test.jsindex 1c97fd1d5..eaa335e7f 100644--- a/plugins/model-apps/scripts/tests/source-literals.test.js+++ b/plugins/model-apps/scripts/tests/source-literals.test.js@@ -110,6 +110,23 @@ test('JSX text is text, not code — the false-positive cases that block real us'JSX with an explicit type argument': 'export default function P(){ return <Table<Row> rows={r} />; }\n','fragment': 'export default function P(){ return <><span>a</span><span>b</span></>; }\n','comparison operators': 'const b = a < c && c > a;\nexport default function P(){ return <div/>; }\n',+ // #542. A `//` or `/* */` comment BETWEEN ATTRIBUTES in a JSX opening tag is valid TSX and a+ // natural thing for a generator to emit when explaining an attribute. `jsxTag` mode had no+ // comment handling at all, so an apostrophe inside one was read as an attribute-value quote,+ // which then ran to EOF (the attribute scanner does not stop at a newline, because a JSX+ // attribute value legitimately may span lines). That blanked the real `export default` and+ // miscounted every bracket after it, so promotion rejected a complete page as "truncated" —+ // and because promotion is transactional, one such page blocked the whole batch.+ 'in-tag line comment': 'export default function P(){ return <button\n type="button"\n // wins over the base border shorthand\n className={x}\n>hi</button>; }\n',+ 'in-tag line comment with an apostrophe': 'export default function P(){ return <button\n type="button"\n // wins over Griffel\'s atomic output\n className={x}\n>hi</button>; }\n',+ 'in-tag block comment with an apostrophe': 'export default function P(){ return <button\n type="button"\n /* Griffel\'s atomic output wins */\n className={x}\n>hi</button>; }\n',+ 'in-tag comment containing a quote and a bracket': 'export default function P(){ return <button\n // don\'t count this ( or this "\n className={x}\n>hi</button>; }\n',+ 'in-tag comment before a self-closing tag': 'export default function P(){ return <div><Icon\n // Griffel\'s output\n aria-hidden\n/></div>; }\n',+ // The other position a `//` can appear inside a tag WITHOUT being a comment: a template-literal+ // TYPE argument. Its content is data, so it must be consumed whole — otherwise the comment+ // branch above blanks to end of line and rejects a valid module.+ 'template-literal type argument containing `//`': 'export default function P(){ return <C<`https://${string}`> />; }\n',+ 'template-literal type argument containing `/*`': 'export default function P(){ return <C<`a/*b`> />; }\n',};for (const [name, code] of Object.entries(cases)) {assert.equal(hasDefaultExport(code), true, `default export missed: ${name}`);@@ -133,6 +150,11 @@ test('hasUnbalancedBrackets flags a truncated write but tolerates JSX and generiassert.equal(hasUnbalancedBrackets('const x: Array<Record<string, number>> = [];\nexport default () => <div a={1} />;\n'), false);// Brackets inside strings/comments must not count.assert.equal(hasUnbalancedBrackets('const s = "{{{"; // )))\nexport default () => null;\n'), false);+ // ...but blanking a comment must not become a way to HIDE a real defect. A template-literal type+ // argument in a tag is consumed as data, so a malformed expression after it on the same line is+ // still visible. (When the `//` inside the template was mistaken for a comment, the rest of the+ // line — including this `{(}` — was blanked and the file read as balanced.)+ assert.equal(hasUnbalancedBrackets('export default function P() {\n return <C<`https://${string}`> value={(} />;\n}\n'), true);});test('every committed .tsx the repo ships is accepted (false-positive corpus)', () => {diff --git a/plugins/model-apps/scripts/tests/spec-lint.test.js b/plugins/model-apps/scripts/tests/spec-lint.test.jsindex fba4fc488..edc737a4b 100644--- a/plugins/model-apps/scripts/tests/spec-lint.test.js+++ b/plugins/model-apps/scripts/tests/spec-lint.test.js@@ -1,7 +1,7 @@// plugins/model-apps/scripts/tests/spec-lint.test.jsconst { test } = require('node:test');const assert = require('node:assert');-const { lintAppSpec } = require('../lib/spec-lint.js');+const { lintAppSpec, NO_VALUE_OPS, KNOWN_FILTER_OPS } = require('../lib/spec-lint.js');const { migrateAppSpec } = require('../lib/app-spec.js');const base = () => ({@@ -35,6 +35,165 @@ test('malformed top-level collections return lint errors instead of throwing', (}});+// #546. `eq-businessid` / `ne-businessid` are value-less FetchXML condition operators — the+// business-unit equivalents of `eq-userid` / `ne-userid` — and are the natural way to express+// "rows owned by my business unit". They were missing from NO_VALUE_OPS, so the lint demanded a+// `value` the operator must not carry and rejected a correct spec.+// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/condition-operator+test('#546 view filters: value-less operators are accepted without a value', () => {+ for (const op of ['eq-businessid', 'ne-businessid', 'eq-userid', 'ne-userid', 'null', 'this-week']) {+ const s = base();+ s.views = [{ entity: 'new_ticket', name: 'Mine', columns: ['new_name'], filters: [{ attr: 'owningbusinessunit', op }] }];+ const r = lintAppSpec(s);+ assert.strictEqual(r.ok, true, `${op} must not require a value: ${JSON.stringify(r.errors)}`);+ }+});++// The complement: an operator that DOES take a value must still be caught when the value is+// omitted, or widening the set above would have turned the check into a rubber stamp.+test('#546 view filters: a value-taking operator with no value is still an error', () => {+ const s = base();+ s.views = [{ entity: 'new_ticket', name: 'Mine', columns: ['new_name'], filters: [{ attr: 'new_priority', op: 'eq' }] }];+ const r = lintAppSpec(s);+ assert.strictEqual(r.ok, false);+ assert.ok(r.errors.some((e) => /needs a value/.test(e)), JSON.stringify(r.errors));+});++// Regression contract: the #546 test above only exercised a handful of operators, and a test that+// ITERATES NO_VALUE_OPS to check NO_VALUE_OPS cannot catch a typo inside it — a misspelled entry+// would simply not be tested, and would reintroduce the same build-blocking false positive.+//+// This list is kept in the DOC TABLE'S OWN ALPHABETICAL ORDER, not the source module's editorial+// grouping, precisely so the transcription is verifiable against+// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/fetchxml/reference/operators+// rather than being a reflow of the thing it is meant to check. (A first pass at this test copied+// the source's grouping, which is not independent of the thing it checks at all.)+// Note the near-misses deliberately EXCLUDED because they take a value: last-x-days, next-x-days,+// in-fiscal-period, in-fiscal-year, olderthan-x-*, on, on-or-before, between.+const DOCUMENTED_NO_VALUE_OPS = [+ 'eq-businessid', 'eq-userid', 'eq-userlanguage', 'eq-useroruserhierarchy',+ 'eq-useroruserhierarchyandteams', 'eq-useroruserteams', 'eq-userteams',+ 'last-fiscal-period', 'last-fiscal-year', 'last-month', 'last-seven-days', 'last-week',+ 'last-year', 'ne-businessid', 'ne-userid', 'next-fiscal-period', 'next-fiscal-year',+ 'next-month', 'next-seven-days', 'next-week', 'next-year', 'not-null', 'null',+ 'this-fiscal-period', 'this-fiscal-year', 'this-month', 'this-week', 'this-year',+ 'today', 'tomorrow', 'yesterday',+];++test('#546 every documented value-less operator is accepted without a value', () => {+ for (const op of DOCUMENTED_NO_VALUE_OPS) {+ const s = base();+ s.views = [{ entity: 'new_ticket', name: 'Mine', columns: ['new_name'], filters: [{ attr: 'owningbusinessunit', op }] }];+ const r = lintAppSpec(s);+ assert.strictEqual(r.ok, true, `'${op}' must not require a value: ${JSON.stringify(r.errors)}`);+ assert.ok(!r.warnings.some((w) => /not a documented FetchXML/.test(w)), `'${op}' must be in the known-operator set too: ${JSON.stringify(r.warnings)}`);+ }+});++// Both directions. A MISSING/typo'd entry reintroduces #546; an EXTRA entry is worse — adding a+// value-TAKING operator here silently disables the missing-value check for it and pushes the+// failure to the platform at build time.+test('#546 NO_VALUE_OPS matches the documented operator list exactly, in both directions', () => {+ assert.deepStrictEqual([...NO_VALUE_OPS].sort(), [...DOCUMENTED_NO_VALUE_OPS].sort());+});++test('the value-less set is a subset of the known-operator set (no entry can be unreachable)', () => {+ const known = new Set(KNOWN_FILTER_OPS);+ for (const op of NO_VALUE_OPS) assert.ok(known.has(op), `'${op}' is value-less but not a known operator`);+});++// The exported sets are shared through the require cache, so handing out the live Set would let one+// consumer's mutation change lint behaviour process-wide.+test('the exported operator sets are frozen copies, not the live Sets', () => {+ assert.ok(Object.isFrozen(NO_VALUE_OPS) && Object.isFrozen(KNOWN_FILTER_OPS));+ assert.throws(() => { NO_VALUE_OPS.push('eq'); });+});++// The SEVERITY here was settled by measurement, not assumption. The obvious reading is that a+// value on a value-less operator is rejected by the platform. Probed live against the Dataverse+// Web API:+// eq-businessid value="00000000-0000-0000-0000-000000000000" -> HTTP 200, 1 row (same as no value)+// this-year value="1999" -> HTTP 200, 1 row (same as no value)+// The platform neither rejects the condition nor honours the value: it IGNORES it. An error would+// therefore block specs that build and run correctly today, so this is a warning — but a silent+// accept would leave a filter that does not do what its `value` plainly says it does.+test('a value on a value-less operator WARNS (the platform ignores it) and does not fail the lint', () => {+ const s = base();+ s.views = [{ entity: 'new_ticket', name: 'Mine', columns: ['new_name'], filters: [{ attr: 'owningbusinessunit', op: 'eq-businessid', value: '00000000-0000-0000-0000-000000000000' }] }];+ const r = lintAppSpec(s);+ assert.strictEqual(r.ok, true, `must not be an error: ${JSON.stringify(r.errors)}`);+ assert.ok(+ r.warnings.some((w) => /value-less operator 'eq-businessid'/.test(w) && /sent to Dataverse and ignored there/.test(w)),+ JSON.stringify(r.warnings)+ );+});++// Regression contract. `value` and `values` are dropped at DIFFERENT points, so one message for+// both sent the author to the wrong place: sdk-build.js forwards `value` into the condition (the+// platform then ignores it), but reads `values` ONLY in the in/not-in branch — so on a value-less+// operator it never reaches Dataverse at all.+test('values[] on a value-less operator warns about the BUILD dropping it, not Dataverse', () => {+ const s = base();+ s.views = [{ entity: 'new_ticket', name: 'Mine', columns: ['new_name'], filters: [{ attr: 'createdon', op: 'this-year', values: ['1999'] }] }];+ const r = lintAppSpec(s);+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+ const w = r.warnings.find((x) => /value-less operator 'this-year'/.test(x));+ assert.ok(w, JSON.stringify(r.warnings));+ assert.match(w, /only read by the 'in'\/'not-in' operators/);+ assert.doesNotMatch(w, /sent to Dataverse/, 'values[] never reaches the platform — saying so would misdirect the author');+});++// Regression contract. Without a known-operator set, a typo'd operator fell through to the+// missing-value check and was reported as `needs a value` — advice that is WRONG. Acting on it+// produces a spec that lints clean and is then rejected by Dataverse at build time. This is the+// same shape as the #546 false positive with an extra step.+test('an operator outside the documented set warns with a near match instead of "needs a value"', () => {+ for (const [op, expected] of [+ ['eq-businesid', 'eq-businessid'],+ ['eq-userteam', 'eq-userteams'],+ ['EQ-USERID', 'eq-userid'],+ ]) {+ const s = base();+ s.views = [{ entity: 'new_ticket', name: 'Mine', columns: ['new_name'], filters: [{ attr: 'ownerid', op }] }];+ const r = lintAppSpec(s);+ assert.ok(+ !r.errors.some((e) => /needs a value/.test(e)),+ `'${op}' must not be reported as needing a value it cannot take: ${JSON.stringify(r.errors)}`+ );+ assert.ok(+ r.warnings.some((w) => new RegExp(`uses '${op}'`).test(w) && w.includes(`did you mean '${expected}'`)),+ `'${op}' should suggest '${expected}': ${JSON.stringify(r.warnings)}`+ );+ }+});++test('an unrecognisable operator still warns, without inventing a near match', () => {+ const s = base();+ s.views = [{ entity: 'new_ticket', name: 'Mine', columns: ['new_name'], filters: [{ attr: 'ownerid', op: 'totally-made-up' }] }];+ const r = lintAppSpec(s);+ const w = r.warnings.find((x) => /totally-made-up/.test(x));+ assert.ok(w, JSON.stringify(r.warnings));+ assert.doesNotMatch(w, /did you mean/);+});++// The complement: a legitimate value-TAKING operator must still reach the missing-value error, or+// the new allow-list would have turned that check into a rubber stamp.+test('a known value-taking operator with no value is still an error, not an unknown-operator warning', () => {+ const s = base();+ s.views = [{ entity: 'new_ticket', name: 'Mine', columns: ['new_name'], filters: [{ attr: 'createdon', op: 'last-x-days' }] }];+ const r = lintAppSpec(s);+ assert.strictEqual(r.ok, false);+ assert.ok(r.errors.some((e) => /needs a value/.test(e)), JSON.stringify(r.errors));+ assert.ok(!r.warnings.some((w) => /not a documented FetchXML/.test(w)), JSON.stringify(r.warnings));+});++test('a value-less operator WITHOUT a value produces no warning (the advice is not noise)', () => {+ const s = base();+ s.views = [{ entity: 'new_ticket', name: 'Mine', columns: ['new_name'], filters: [{ attr: 'owningbusinessunit', op: 'eq-businessid' }] }];+ const r = lintAppSpec(s);+ assert.ok(!r.warnings.some((w) => /value-less operator/.test(w)), JSON.stringify(r.warnings));+});+test('a view named like the stock default ("Active <Plural>") WARNS about the merge-onto-default collision', () => {const s = base();s.views = [{ entity: 'new_ticket', name: 'Active Tickets', columns: ['new_name', 'new_priority'], activeOnly: true }];diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex f357d6ad5..111c3e9e6 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -202,10 +202,11 @@ every prompt yourself via `AskUserQuestion`. In short:right" (see the CRITICAL note above).** The user must be able to SEE each form, the sitemap, andthe page intents they are approving. For a single form only: `node "${PLUGIN_ROOT}/scripts/preview-form.js" --spec @<working-dir>/app-spec.json`.- **Don't pre-create tables/columns** — the build does it idempotently.-5. **Guardrail lint (hard gate)** — run the **full** `spec-lint.js` on the complete spec; **errors block**, warnings teach. If it blocks (or warns), **paste the findings into your chat reply** — tool output is collapsed and invisible to the user (see the CRITICAL note above), so the user can't fix what they can't see:+5. **Guardrail lint (hard gate)** — run the **full** lint on the complete spec; **errors block**, warnings teach. If it blocks (or warns), **paste the findings into your chat reply** — tool output is collapsed and invisible to the user (see the CRITICAL note above), so the user can't fix what they can't see:```bash- node -e "const{lintAppSpec}=require('${PLUGIN_ROOT}/scripts/lib/spec-lint.js');const s=require('<working-dir>/app-spec.json');const r=lintAppSpec(s);console.log(JSON.stringify(r,null,2));process.exit(r.ok?0:1)"+ node "${PLUGIN_ROOT}/scripts/lint-app-spec.js" --spec @<working-dir>/app-spec.json --json```+ This runs migration and `validateAppSpec` — the gates the build itself runs on load — plus the `lintAppSpec` authoring guardrails, which the builder does **not** run. It exits non-zero on errors. It validates under the `plan` profile (which allows not-yet-generated intent pages), matching Step 6's dry run.6. **Plan-mode approval (the single build approval)** — present the plan **including the builddry-run's phase-grouped plan** (run `build-model-app.js` without `--apply`, using the `plan`profile that allows intent pages) inside `EnterPlanMode`, then `ExitPlanMode` to get the user'sdiff --git a/scripts/tests/validate-hooks-manifests.test.js b/scripts/tests/validate-hooks-manifests.test.jsnew file mode 100644index 000000000..2f420bf22--- /dev/null+++ b/scripts/tests/validate-hooks-manifests.test.js@@ -0,0 +1,67 @@+// Guards the guard. validate-hooks-manifests.js exists to stop a plugin shipping a hooks.json+// key the host does not recognise, because the only symptom is a warning line in somebody+// else's terminal at every session start — invisible in review, and caught by no other test.+// The cases that matter most are therefore the ones asserting it does NOT stay silent.++const test = require('node:test');+const assert = require('node:assert');+const fs = require('node:fs');+const path = require('node:path');++const { checkManifest, findHookManifests, ALLOWED_TOP_LEVEL_KEYS } = require('../validate-hooks-manifests.js');++test('a manifest with only "hooks" passes', () => {+ assert.deepEqual(checkManifest({ hooks: {} }, 'x/hooks.json'), []);+});++test('a manifest with "hooks" and the recognised "description" passes', () => {+ assert.deepEqual(checkManifest({ description: 'what these do', hooks: {} }, 'x/hooks.json'), []);+});++test('the "_comment" key that caused #555/#558 is rejected, and the message says where prose goes', () => {+ const problems = checkManifest({ _comment: 'prose', hooks: {} }, 'plugins/p/hooks/hooks.json');+ assert.equal(problems.length, 1);+ assert.match(problems[0], /unknown top-level key "_comment"/);+ assert.match(problems[0], /hooks\/README\.md/);+ // The message must quote the host's own wording so a reader can connect it to the+ // warning they actually saw in their terminal.+ assert.match(problems[0], /unknown key "_comment" ignored/);+});++test('any other unrecognised key is rejected too (the rule is an allow-list, not a _comment blocklist)', () => {+ for (const key of ['comment', '//', 'notes', 'x-docs', 'readme']) {+ const problems = checkManifest({ [key]: 'prose', hooks: {} }, 'x/hooks.json');+ assert.equal(problems.length, 1, `${key} should be rejected`);+ assert.match(problems[0], new RegExp(`unknown top-level key "${key.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')}"`));+ }+});++test('a manifest missing "hooks" is rejected', () => {+ const problems = checkManifest({ description: 'only prose' }, 'x/hooks.json');+ assert.equal(problems.length, 1);+ assert.match(problems[0], /missing the required "hooks" key/);+});++test('a non-object manifest is rejected without throwing', () => {+ for (const value of [null, [], 'string', 42]) {+ const problems = checkManifest(value, 'x/hooks.json');+ assert.equal(problems.length, 1, JSON.stringify(value));+ assert.match(problems[0], /expected a JSON object/);+ }+});++// The real repository must satisfy the rule. This is what actually fails a PR that+// reintroduces the key, so it is asserted against the committed files rather than fixtures.+test('every committed plugin hooks.json passes', () => {+ const files = findHookManifests();+ assert.ok(files.length >= 3, `expected to find plugin hooks manifests, found ${files.length}`);+ for (const filePath of files) {+ const manifest = JSON.parse(fs.readFileSync(filePath, 'utf8'));+ const rel = path.relative(path.resolve(__dirname, '..', '..'), filePath);+ assert.deepEqual(checkManifest(manifest, rel), [], rel);+ }+});++test('the allow-list stays tight — widening it silently re-creates the bug', () => {+ assert.deepEqual([...ALLOWED_TOP_LEVEL_KEYS].sort(), ['description', 'hooks']);+});diff --git a/scripts/validate-hooks-manifests.js b/scripts/validate-hooks-manifests.jsnew file mode 100644index 000000000..b6cefa47c--- /dev/null+++ b/scripts/validate-hooks-manifests.js@@ -0,0 +1,124 @@+#!/usr/bin/env node++/**+ * Validates that every plugin's `hooks/hooks.json` carries only keys the host's+ * hook loader recognises.+ *+ * WHY: Claude Code validates `hooks.json` against a CLOSED schema and prints a+ * warning for any key it does not know:+ *+ * model-apps: hooks.json: unknown key "_comment" ignored+ *+ * That line appears at EVERY session start, for every user of the plugin, and+ * reads as a plugin misconfiguration. The hooks themselves still work — the key+ * really is ignored — so nothing fails, no test catches it, and the noise+ * survives indefinitely. Two of the eight plugins shipped a `_comment` key+ * holding documentation prose (model-apps, mobile-apps); see issues #555 / #558.+ *+ * The prose is worth keeping, so it moved to `plugins/<plugin>/hooks/README.md`,+ * which has no schema at all. This check exists because a JSON file is exactly+ * where the next contributor will reach for a comment: JSON has no comment+ * syntax, `_comment` is the usual workaround, and the cost of getting it wrong+ * is invisible in review and only shows up in somebody else's terminal.+ *+ * Allowed top-level keys:+ * - `hooks` (required) the event -> matcher -> command tree the loader reads.+ * - `description` (optional) a recognised, ignored-by-design documentation field.+ * Anything else fails, naming the file, the key, and where the prose should go.+ *+ * Scope: repo-wide over `plugins/<plugin>/hooks/hooks.json`. Unlike the+ * model-apps-scoped environment scan, there is no pre-existing violation+ * elsewhere to grandfather — canvas-apps already uses `description` and+ * power-pages ships `hooks` alone — so every plugin can be held to this today.+ */++const fs = require('fs');+const path = require('path');++const ROOT = path.resolve(__dirname, '..');+const PLUGINS_DIR = path.join(ROOT, 'plugins');++// `hooks` is what the loader actually executes; `description` is a documented,+// deliberately-ignored field several plugin ecosystems accept. Keep this list+// tight: the whole point is that an unrecognised key is a user-visible warning,+// so widening it without checking the host's schema re-creates the bug.+const ALLOWED_TOP_LEVEL_KEYS = new Set(['hooks', 'description']);++function toPosix(relativePath) {+ return relativePath.replace(/\\/g, '/');+}++// Returns the list of problems with ONE parsed manifest. Pure and exported so the+// test can exercise the rule without writing files to disk.+function checkManifest(manifest, relPath) {+ const problems = [];++ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {+ problems.push(`${relPath}: expected a JSON object at the top level`);+ return problems;+ }++ for (const key of Object.keys(manifest)) {+ if (ALLOWED_TOP_LEVEL_KEYS.has(key)) continue;+ problems.push(+ `${relPath}: unknown top-level key "${key}". The host prints ` ++ `'hooks.json: unknown key "${key}" ignored' at every session start. ` ++ `Move prose to plugins/<plugin>/hooks/README.md.`+ );+ }++ if (!Object.prototype.hasOwnProperty.call(manifest, 'hooks')) {+ problems.push(`${relPath}: missing the required "hooks" key`);+ }++ return problems;+}++// Probe the canonical path per plugin rather than walking the tree: a hooks+// manifest is only loaded from plugins/<plugin>/hooks/hooks.json, so a file of+// that name anywhere else is not a manifest and must not be held to this schema.+function findHookManifests() {+ if (!fs.existsSync(PLUGINS_DIR)) return [];+ return fs+ .readdirSync(PLUGINS_DIR, { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .map((entry) => path.join(PLUGINS_DIR, entry.name, 'hooks', 'hooks.json'))+ .filter((filePath) => fs.existsSync(filePath));+}++function main() {+ const errors = [];+ const files = findHookManifests();++ for (const filePath of files) {+ const relPath = toPosix(path.relative(ROOT, filePath));+ let manifest;+ try {+ manifest = JSON.parse(fs.readFileSync(filePath, 'utf8'));+ } catch (err) {+ // A manifest that does not parse cannot load any hook at all, so this is a+ // shippable defect in its own right — fail rather than skip.+ errors.push(`${relPath}: could not parse JSON (${err.message})`);+ continue;+ }+ errors.push(...checkManifest(manifest, relPath));+ }++ if (errors.length > 0) {+ console.log('Plugin hooks.json validation failed:');+ for (const error of errors) console.log(`- ${error}`);+ console.log(+ `\nAllowed top-level keys: ${[...ALLOWED_TOP_LEVEL_KEYS].join(', ')}. ` ++ 'JSON has no comment syntax — document the hooks in hooks/README.md instead.'+ );+ process.exit(1);+ }++ console.log(`All ${files.length} plugin hooks.json manifest(s) use only recognised top-level keys.`);+}++if (require.main === module) {+ main();+}++module.exports = { checkManifest, findHookManifests, ALLOWED_TOP_LEVEL_KEYS };