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: genpage provenance, output and filename gates, and the transpile claim (#620)
Akshay Maloo943401d773b2
diff --git a/evals/model-apps/genpage/EVAL_GUIDE.md b/evals/model-apps/genpage/EVAL_GUIDE.mdindex edec07818..2cf4d4ee2 100644--- a/evals/model-apps/genpage/EVAL_GUIDE.md+++ b/evals/model-apps/genpage/EVAL_GUIDE.md@@ -355,7 +355,7 @@ For ad-hoc verification or assertions the Layer 2 runner currently skips, grep t| `Xrm.Navigation.navigateTo` | If navigation is used, must appear (literal or via `xrm?.Navigation?.navigateTo` alias) || Unsized icons | `grep -E '\w+(16\|20\|24\|28\|32)(Regular\|Filled)\b'` should return nothing || try-catch on dataApi | Each `await dataApi\.` must be inside a try block |-| No placeholders | `grep -E '(TODO\|FIXME\|\.\.\..*$)'` should not match in function bodies |+| No placeholders | `node plugins/model-apps/scripts/genpage-worker-output.js --file <page>.tsx` — its elision check is the Layer 2 rule. A bare `grep -E '(TODO\|FIXME\|\.\.\.)'` over-matches spreads, `'TODO'` status values and "Loading…" || FormattedValue for lookups | Any `_xxx_value` in a select must be paired with a FormattedValue access || `createTableColumn` import | If `<DataGrid>` is used, must import `createTableColumn` |diff --git a/evals/model-apps/genpage/fixtures/1-account-card-gallery/genpage-plan.md b/evals/model-apps/genpage/fixtures/1-account-card-gallery/genpage-plan.mdindex c155d99a9..68e7ed444 100644--- a/evals/model-apps/genpage/fixtures/1-account-card-gallery/genpage-plan.md+++ b/evals/model-apps/genpage/fixtures/1-account-card-gallery/genpage-plan.md@@ -41,6 +41,9 @@ accountNo connector bindings.+## Custom API Bindings+No custom API bindings.+## Design Preferences- Card grid layout, responsive auto-fill columnsdiff --git a/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/genpage-plan.md b/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/genpage-plan.mdindex 734011137..7b847a822 100644--- a/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/genpage-plan.md+++ b/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/genpage-plan.md@@ -43,6 +43,9 @@ contact, appointmentNo connector bindings.+## Custom API Bindings+No custom API bindings.+## Design Preferences- Cross-page navigation uses Xrm.Navigation.navigateTo with `pageId: "PAGEREF_<filename>"` placeholders that the orchestrator resolves in Phase 6.5diff --git a/evals/model-apps/genpage/fixtures/13-contact-localization/genpage-plan.md b/evals/model-apps/genpage/fixtures/13-contact-localization/genpage-plan.mdindex cfbf47a1d..11dd6506a 100644--- a/evals/model-apps/genpage/fixtures/13-contact-localization/genpage-plan.md+++ b/evals/model-apps/genpage/fixtures/13-contact-localization/genpage-plan.md@@ -50,6 +50,9 @@ No connector bindings.- dir attribute set from locale.isRtl- Logical CSS properties (marginInlineStart/End, paddingInlineStart/End)+## Custom API Bindings+No custom API bindings.+## Design Preferences- DataGrid with sortable, resizable columnsdiff --git a/evals/model-apps/genpage/fixtures/17-weather-mock-data/genpage-plan.md b/evals/model-apps/genpage/fixtures/17-weather-mock-data/genpage-plan.mdindex a1ceefb89..7bbc288f8 100644--- a/evals/model-apps/genpage/fixtures/17-weather-mock-data/genpage-plan.md+++ b/evals/model-apps/genpage/fixtures/17-weather-mock-data/genpage-plan.md@@ -39,6 +39,9 @@ No entity creation required — all entities already exist.No connector bindings.+## Custom API Bindings+No custom API bindings.+## Design Preferences- Inline mock weather data (maker chose mock data — no connector binding requested)diff --git a/evals/model-apps/genpage/fixtures/18-sharepoint-connectors/genpage-plan.md b/evals/model-apps/genpage/fixtures/18-sharepoint-connectors/genpage-plan.mdindex f7b4f18d4..cbd5a58eb 100644--- a/evals/model-apps/genpage/fixtures/18-sharepoint-connectors/genpage-plan.md+++ b/evals/model-apps/genpage/fixtures/18-sharepoint-connectors/genpage-plan.md@@ -41,6 +41,9 @@ No entity creation required — all entities already exist.|--------------|--------------|---------|----------------|---------------------|------------|--------|------------|----------|| new_uxtest_sharepoint | /providers/Microsoft.PowerApps/apis/shared_sharepointonline | https://contoso.sharepoint.com/sites/team | 5709dd6f-c73e-4079-ad23-2334e45e0e13 | Documents | | ID (number), Title (string), Author (string), FileType ({Value:string}), Created (string), Modified (string) | | |+## Custom API Bindings+No custom API bindings.+## Design Preferences- Clean card list layout for document browsingdiff --git a/evals/model-apps/genpage/fixtures/2-mock-dashboard/genpage-plan.md b/evals/model-apps/genpage/fixtures/2-mock-dashboard/genpage-plan.mdindex dfd2ceab7..657084a90 100644--- a/evals/model-apps/genpage/fixtures/2-mock-dashboard/genpage-plan.md+++ b/evals/model-apps/genpage/fixtures/2-mock-dashboard/genpage-plan.md@@ -41,6 +41,9 @@ No entity creation required — all entities already exist.No connector bindings.+## Custom API Bindings+No custom API bindings.+## Design Preferences- Modern dark theme look (use Fluent UI V9 dark tokens)diff --git a/evals/model-apps/genpage/fixtures/4-case-wizard/genpage-plan.md b/evals/model-apps/genpage/fixtures/4-case-wizard/genpage-plan.mdindex 69c8365d8..24bea6155 100644--- a/evals/model-apps/genpage/fixtures/4-case-wizard/genpage-plan.md+++ b/evals/model-apps/genpage/fixtures/4-case-wizard/genpage-plan.md@@ -41,6 +41,9 @@ incident, contactNo connector bindings.+## Custom API Bindings+No custom API bindings.+## Design Preferences- 3 steps: customer info → case details → reviewdiff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/genpage-plan.md b/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/genpage-plan.mdindex 1cda500ff..ac7322f72 100644--- a/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/genpage-plan.md+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/genpage-plan.md@@ -83,6 +83,9 @@ None.No connector bindings.+## Custom API Bindings+No custom API bindings.+## Design Preferences- DataGrid layout, sortable, resizable columnsdiff --git a/evals/model-apps/genpage/fixtures/README.md b/evals/model-apps/genpage/fixtures/README.mdindex fad6df835..21ee34821 100644--- a/evals/model-apps/genpage/fixtures/README.md+++ b/evals/model-apps/genpage/fixtures/README.md@@ -78,7 +78,7 @@ regeneration:## Current stateThis directory ships with 10 fixtures — 6 synthetic (hand-built, v2.2-compliant)-and 4 real captures (3 from claude-sonnet-4-6 sessions under the v2.2 plugin):+and 4 real captures (3 from sessions under the v2.2 plugin):| Fixture | Eval | Source | State | Shape covered ||---------|-----:|--------|-------|---------------|@@ -89,9 +89,9 @@ and 4 real captures (3 from claude-sonnet-4-6 sessions under the v2.2 plugin):| `5-kanban-task-board/` | 5 | Real capture (2026-05-21, pre-v2.2-spec) | mostly green | Native HTML5 DnD on `task` entity — Layer 2 fully green; Layer 1 pre-spec workflow-log gaps || `7-job-candidates-new-entities/` | 7 | Synthetic | green | New entities + lookup + choice column + sample data + solution selection || `11-recruitment-multi-page/` | 11 | Synthetic | green | Multi-page (3 pages), parallel page-builder dispatch, PAGEREF cross-nav, Phase 6.5 resolution |-| `11-recruitment-pages-real/` | 11 | Real capture (2026-05-21, v2.2-spec) | **green** | Same shape as synthetic — first real capture validated under tightened spec |+| `11-recruitment-pages-real/` | 11 | Real capture (2026-05-21, v2.2-spec) | red (Custom API section only) | Same shape as synthetic — first real capture validated under tightened spec; predates the enforced `## Custom API Bindings` section (see below) || `13-contact-localization/` | 13 | Synthetic | green | Localization (en-US / ar-SA / fr-FR), RTL, logical CSS properties |-| `15-support-tickets-real/` | 15 | Real capture (2026-05-26, v2.2-spec) | **green** | New entity + choice columns + sample data + check-auth retry flow |+| `15-support-tickets-real/` | 15 | Real capture (2026-05-26, v2.2-spec) | red (Custom API section only) | New entity + choice columns + sample data + check-auth retry flow; predates the enforced `## Custom API Bindings` section (see below) |**Synthetic fixtures** are hand-built to be v2.2-compliant — they exercisethe relevant code paths and serve as green-path regression tests for the@@ -99,8 +99,10 @@ runners. All Layer 1 + Layer 2 assertions pass or skip.**Real captures** validate the runners against actual `/genpage` output:-- The two **green real captures** (eval 11, eval 15) were captured after the- v2.2 planner-spec tightening landed. Both layers exit 0 against them.+- The two real captures for eval 11 and eval 15 were captured after the+ v2.2 planner-spec tightening landed, and both layers exited 0 against+ them until the `## Custom API Bindings` section was enforced; that one+ Layer 1 check is now their only failure.- The two **red real captures** (eval 2, eval 5) were captured before thespec tightening propagated to the agent's session. They have knownworkflow-log compactness gaps documented in their fixture READMEs; they@@ -108,4 +110,18 @@ runners. All Layer 1 + Layer 2 assertions pass or skip.The mix gives a green-path regression test (synthetic) + a drift-detectionexample (red real captures) + proof-of-life that the v2.2 spec produces-green output (green real captures).+passing output (the eval 11 and 15 captures, which pass everything except+the later-enforced Custom API section).++**Captured plans predate `## Custom API Bindings` enforcement.**+`references/plan-schema.md` has always required that section, but the+Layer 1 validator only started enforcing it with [#585], after every+fixture here was made. The synthetic and authored plans gained the exact+no-bindings sentinel (`No custom API bindings.`, before+`## Design Preferences`) — none of those pages calls a Custom API. The four+**real captures were deliberately not edited**: a capture is evidence of+what the planner produced, and rewriting it to match today's schema would+falsify it (the same rule the upload-transport assertions follow). Each now+also fails that one Layer 1 check; re-capturing clears it.++[#585]: https://github.com/microsoft/power-platform-skills/issues/585diff --git a/evals/model-apps/genpage/lib/assertions-layer-1.js b/evals/model-apps/genpage/lib/assertions-layer-1.jsindex 21e31fcf8..ebee6178a 100644--- a/evals/model-apps/genpage/lib/assertions-layer-1.js+++ b/evals/model-apps/genpage/lib/assertions-layer-1.js@@ -13,6 +13,9 @@'use strict';+const path = require('node:path');+const { pageFileProblems } = require('../../../../plugins/model-apps/scripts/lib/page-file-targets.js');+function fail(reason) { return { status: 'fail', reason }; }function pass() { return { status: 'pass', reason: '' }; }@@ -145,6 +148,7 @@ const REQUIRED_PLAN_SECTIONS = ['Entity Creation Required','Existing Entities','Connector Bindings',+ 'Custom API Bindings','Design Preferences','Relevant Samples','Per-Page Specifications',@@ -230,6 +234,27 @@ function parseMarkdownRows(sectionText, requiredColumns) {return rows;}+function workingDirectoryOf(plan) {+ const section = planSection(plan, 'Working Directory');+ return section ? section.split(/\r?\n/)[0].trim() : '';+}++function validatePageFileTargets(pageRows, workingDir, errors) {+ // The rule is the plugin's own (page-file-targets.js), so this validator, /app-builder's plan+ // projection and /genpage's pre-dispatch gate cannot disagree about a page filename.+ const files = pageRows.map((row) => String(row.file || '').trim());+ const byFile = new Map(pageRows.map((row) => [String(row.file || '').trim(), row]));+ const problems = pageFileProblems(files, { workingDir: workingDir ? path.resolve(workingDir) : process.cwd() });+ for (const problem of problems) {+ const row = byFile.get(problem.file) || {};+ if (problem.code === 'collision') {+ errors.push(schemaError('duplicate-page-file', `page files ${problem.message}`, { section: 'Pages', page: row.page, file: problem.file }));+ } else {+ errors.push(schemaError('invalid-page-file', `page "${row.page}": ${problem.message}`, { section: 'Pages', page: row.page, file: problem.file }));+ }+ }+}+function parsePerPageBlocks(sectionText) {const lines = sectionText.split(/\r?\n/);const blocks = new Map();@@ -318,10 +343,14 @@ function validateGenpagePlanSchema(plan) {const observed = sections.map((section) => section.title).filter((title) => REQUIRED_PLAN_SECTIONS.includes(title) || OPTIONAL_PLAN_SECTIONS.has(title));+ // Solution Packaging is optional and sits between Custom API Bindings and Design Preferences, as in+ // references/plan-schema.md. Split at that point by NAME: an index goes stale the moment a required+ // section is added before it — which is exactly how Custom API Bindings ended up expected after it.+ const packagingAt = REQUIRED_PLAN_SECTIONS.indexOf('Design Preferences');const expected = [- ...REQUIRED_PLAN_SECTIONS.slice(0, 8),+ ...REQUIRED_PLAN_SECTIONS.slice(0, packagingAt),...(observed.includes('Solution Packaging') ? ['Solution Packaging'] : []),- ...REQUIRED_PLAN_SECTIONS.slice(8),+ ...REQUIRED_PLAN_SECTIONS.slice(packagingAt),];const comparable = observed.filter((title) => expected.includes(title));if (comparable.join('\n') !== expected.filter((title) => comparable.includes(title)).join('\n')) {@@ -336,6 +365,7 @@ function validateGenpagePlanSchema(plan) {if (pagesSection && pageRows.length === 0) {errors.push(schemaError('missing-pages-table', '## Pages must contain a table with Page, File, Purpose, and Entities columns', { section: 'Pages' }));}+ if (pageRows.length) validatePageFileTargets(pageRows, workingDirectoryOf(plan), errors);const entitySection = byTitle.get('Entity Creation Required');if (entitySection) validateEntityCreationSection(entitySection.content, errors);@@ -348,23 +378,20 @@ function validateGenpagePlanSchema(plan) {}}- // `## Custom API Bindings` is spec'd as always-present: plan-schema.md:212 gives it the same- // "Exact literal ... when empty" sentinel rule as `## Connector Bindings` at :211, and :213- // reserves "Opt-in" for `## Solution Packaging` alone — which is why OPTIONAL_PLAN_SECTIONS- // contains only that one section. (The "opt-in, unlike the always-present ## Connector Bindings"- // sentence at :158-160 sits inside the Solution Packaging block and describes IT, not this- // section.) In practice though, 0 of the 12 fixture plans emit `## Custom API Bindings` and- // REQUIRED_PLAN_SECTIONS omits it, so requiring it here would fail every existing plan. This- // check is therefore conditional until the fixtures catch up with the spec — a deliberate- // accommodation of a spec-vs-reality divergence, not a statement that the section is optional.- // Without it the Custom API half had no enforcement at all: the sentinel was stated but never- // checked, so a prompt regression leaking a `----- BEGIN/END ... -----` delimiter into this- // section scored green, while the identical regression in the connector half fails loudly.const customApiSection = byTitle.get('Custom API Bindings');if (customApiSection) {const body = customApiSection.content.trim();- if (body !== 'No custom API bindings.' && !findMarkdownTable(body, ['Name', 'Kind', 'Bound Entity'])) {+ const rows = parseMarkdownRows(body, ['Name', 'Kind', 'Bound Entity', 'Display Name', 'Parameters (name: kind)']);+ if (body !== 'No custom API bindings.' && rows.length === 0) {errors.push(schemaError('missing-customapi-table', '## Custom API Bindings must be the exact no-bindings sentinel or the Custom API binding table', { section: 'Custom API Bindings' }));+ } else {+ for (const row of rows) {+ const kind = row.kind || '';+ if (!row.name || !/^(Action|Function)$/i.test(kind) || !row['bound entity'] || !row['display name']) {+ errors.push(schemaError('missing-customapi-table', '## Custom API Bindings rows must include Name, Kind (Action or Function), Bound Entity, Display Name, and Parameters (name: kind)', { section: 'Custom API Bindings' }));+ break;+ }+ }}}@@ -993,7 +1020,7 @@ PHASE_EXPECTATIONS.set(({ fixture }) => {const log = fixture.entityCreationLog || fixture.workflowLog;if (!log) return fail('no entity-creation-log.md or workflow-log.md');-+// Check legacy flow: old-script calls must have --solutionconst legacyMatches = allMatches(/(create-table\.js|add-column\.js|create-relationship\.js)([^\n]*)/g, log);const offenders = [];@@ -1001,7 +1028,7 @@ PHASE_EXPECTATIONS.set(if (!/--solution\b/.test(m[2])) offenders.push(m[1]);}if (offenders.length > 0) return fail(`${offenders.length} call(s) missing --solution: ${offenders.slice(0,3).join(', ')}`);-+// Check new flow: provision-entities.js must have Solution: declared in plan or log// Check for provision-entities.js in both workflowLog and entityCreationLogconst usesNewFlow = /\bprovision-entities\.js\b/.test(fixture.workflowLog || '') || /\bprovision-entities\.js\b/.test(fixture.entityCreationLog || '');@@ -1013,10 +1040,10 @@ PHASE_EXPECTATIONS.set(const hasSolution = (planEnv && solutionPattern.test(planEnv)) || (logEnv && solutionPattern.test(logEnv));if (!hasSolution) return fail('provision-entities.js used but no Solution: declaration in ## Environment');}-+// Skip if no entity provisioning detectedif (legacyMatches.length === 0 && !usesNewFlow) return skip('no entity provisioning detected');-+return pass();});diff --git a/evals/model-apps/genpage/lib/assertions-layer-2.js b/evals/model-apps/genpage/lib/assertions-layer-2.jsindex a721827cf..eddabdab9 100644--- a/evals/model-apps/genpage/lib/assertions-layer-2.js+++ b/evals/model-apps/genpage/lib/assertions-layer-2.js@@ -20,7 +20,7 @@ const fs = require('node:fs');// re-implemented: it is a pure lexer over TSX text, not part of the thing this harness judges, and// two divergent copies of a tokenizer is exactly how a false-green assertion creeps back in. Evals// never ship, so reaching into the plugin directory here is in-repo only.-const { blankLiterals } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');+const { blankLiterals, findElisionMarker } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');let _verifiedIcons = null;function getVerifiedIcons() {@@ -240,14 +240,11 @@ ASSERTIONS.set(ASSERTIONS.set('Generated .tsx does NOT include any `TODO`, `FIXME`, ellipsis placeholders, or incomplete function bodies',({ files }) => {- const offender = files.find((f) => {- if (/\b(TODO|FIXME)\b/.test(f.content)) return true;- if (/\/\/\s*\.\.\./.test(f.content)) return true;- if (/\/\*\s*\.\.\.\s*\*\//.test(f.content)) return true;- if (/^\s*\.\.\.\s*(\/\/.*)?$/m.test(f.content)) return true;- return false;- });- return offender ? fail(`${offender.name}: contains TODO/FIXME or ellipsis placeholder`) : pass();+ // The same rule the plugin's worker-output gate applies (findElisionMarker), so an eval and the+ // runtime cannot disagree about one file. It looks in comments and bare lines only: "Loading…" in+ // a label is UI copy, not an elided function body.+ const offender = files.find((f) => findElisionMarker(f.content));+ return offender ? fail(`${offender.name}: contains ${findElisionMarker(offender.content)}`) : pass();});diff --git a/evals/model-apps/genpage/tests/assertions-layer-1.test.js b/evals/model-apps/genpage/tests/assertions-layer-1.test.jsindex 4b396cb66..a2554c4a4 100644--- a/evals/model-apps/genpage/tests/assertions-layer-1.test.js+++ b/evals/model-apps/genpage/tests/assertions-layer-1.test.js@@ -1,6 +1,9 @@'use strict';const { test } = require('node:test');const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');const {WORKFLOW_ASSERTIONS,@@ -62,6 +65,9 @@ account## Connector BindingsNo connector bindings.+## Custom API Bindings+No custom API bindings.+## Design Preferences- Styling: Clean- Features: Search@@ -667,31 +673,115 @@ for (const prose of [});}-// Omitting the section must stay valid — this guards against the obvious wrong fix of adding it to-// REQUIRED_PLAN_SECTIONS. plan-schema.md:212 does spec the section as always-present, but 0 of the-// 12 fixture plans emit it, so requiring it would fail 12/12 rather than catch a real defect.-test('a plan without a Custom API Bindings section is still valid', () => {+test('validateGenpagePlanSchema: missing Custom API Bindings section fails closed', () => {+ const plan = validPlan().replace(/\n## Custom API Bindings\nNo custom API bindings\.\n/, '\n');+ const errors = validateGenpagePlanSchema(plan);+ assert.ok(+ errors.some((error) => error.code === 'missing-section' && error.section === 'Custom API Bindings'),+ `expected missing Custom API Bindings section, got ${JSON.stringify(errors)}`+ );+});++test('Custom API Bindings section accepts the exact sentinel', () => {const errors = validateGenpagePlanSchema(validPlan());assert.equal(errors.filter((e) => e.code === 'missing-customapi-table').length, 0);});-test('an opt-in Custom API Bindings section accepts the exact sentinel', () => {- const plan = `${validPlan()}\n\n## Custom API Bindings\nNo custom API bindings.\n`;- const errors = validateGenpagePlanSchema(plan);- assert.equal(errors.filter((e) => e.code === 'missing-customapi-table').length, 0);+// references/plan-schema.md orders Connector Bindings → Custom API Bindings → Solution Packaging →+// Design Preferences. The order check split the required list at a fixed index, so adding Custom API+// Bindings to it made a schema-conformant plan WITH Solution Packaging fail as out of order.+test('a plan with Solution Packaging in plan-schema.md order passes the order check, and the reverse fails', () => {+ const packaging = '## Solution Packaging\n- Solution: ContosoApp\n\n';+ const conformant = validPlan().replace('## Design Preferences', `${packaging}## Design Preferences`);+ assert.deepEqual(validateGenpagePlanSchema(conformant).filter((e) => e.code === 'section-order'), []);+ const swapped = validPlan()+ .replace('## Custom API Bindings\nNo custom API bindings.\n\n', '')+ .replace('## Design Preferences', `${packaging}## Custom API Bindings\nNo custom API bindings.\n\n## Design Preferences`);+ assert.ok(validateGenpagePlanSchema(swapped).some((e) => e.code === 'section-order'), 'Solution Packaging before Custom API Bindings is out of order');});// The Custom API mirror of the connector delimiter leak. If the planner prompt regresses and the// planner copies the `----- BEGIN/END CUSTOM API BINDINGS -----` framing into the plan, the body// is no longer the exact sentinel and must be rejected — previously nothing checked this half.test('a leaked prompt delimiter in Custom API Bindings is rejected', () => {- const plan = `${validPlan()}\n\n## Custom API Bindings\n----- BEGIN CUSTOM API BINDINGS -----\nNo custom API bindings.\n----- END CUSTOM API BINDINGS -----\n`;+ const plan = validPlan().replace(+ '## Custom API Bindings\nNo custom API bindings.',+ '## Custom API Bindings\n----- BEGIN CUSTOM API BINDINGS -----\nNo custom API bindings.\n----- END CUSTOM API BINDINGS -----'+ );const errors = validateGenpagePlanSchema(plan);assert.equal(errors.filter((e) => e.code === 'missing-customapi-table').length, 1);});test('a populated Custom API Bindings table is accepted', () => {- const plan = `${validPlan()}\n\n## Custom API Bindings\n| Name | Kind | Bound Entity | Display Name | Parameters (name: kind) |\n|------|------|--------------|--------------|-------------------------|\n| new_ApproveOrder | Action | salesorder | Approve Order | Comment: String |\n`;+ const plan = validPlan().replace(+ '## Custom API Bindings\nNo custom API bindings.',+ '## Custom API Bindings\n| Name | Kind | Bound Entity | Display Name | Parameters (name: kind) |\n|------|------|--------------|--------------|-------------------------|\n| new_ApproveOrder | Action | salesorder | Approve Order | Comment: String |'+ );const errors = validateGenpagePlanSchema(plan);assert.equal(errors.filter((e) => e.code === 'missing-customapi-table').length, 0);});++test('a Custom API Bindings table missing required schema columns is rejected', () => {+ const plan = validPlan().replace(+ '## Custom API Bindings\nNo custom API bindings.',+ '## Custom API Bindings\n| Name | Kind | Bound Entity |\n|------|------|--------------|\n| new_ApproveOrder | Action | salesorder |'+ );+ const errors = validateGenpagePlanSchema(plan);+ assert.equal(errors.filter((e) => e.code === 'missing-customapi-table').length, 1);+});++test('validateGenpagePlanSchema: page file paths must stay inside the working directory', () => {+ for (const [file, codePattern] of [+ ['..\\outside.tsx', /separator|traversal|escape|absolute/i],+ ['../outside.tsx', /traversal|escape|outside/i],+ ['C:\\temp\\outside.tsx', /absolute|escape/i],+ ]) {+ const plan = validPlan().replace('account-overview.tsx', file);+ const errors = validateGenpagePlanSchema(plan);+ assert.ok(+ errors.some((error) => error.code === 'invalid-page-file' && codePattern.test(error.message)),+ `expected invalid-page-file for ${file}, got ${JSON.stringify(errors)}`+ );+ }+});++test('validateGenpagePlanSchema: page file parent realpath must stay inside the working directory', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-plan-root-'));+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-plan-outside-'));+ const link = path.join(root, 'linked');+ t.after(() => {+ fs.rmSync(link, { recursive: true, force: true });+ fs.rmSync(root, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ });+ try {+ fs.symlinkSync(outside, link, 'junction');+ } catch (error) {+ t.skip(`cannot create directory link on this host: ${error.message}`);+ return;+ }++ const plan = validPlan()+ .replace('D:\\work\\account-page', root)+ .replace('account-overview.tsx', 'linked/page.tsx');+ const errors = validateGenpagePlanSchema(plan);+ assert.ok(+ errors.some((error) => error.code === 'invalid-page-file' && /outside|realpath|working directory/i.test(error.message)),+ `expected invalid-page-file for symlink parent escape, got ${JSON.stringify(errors)}`+ );+});++test('validateGenpagePlanSchema: page files cannot collide by normalized case-insensitive identity', () => {+ const plan = validPlan().replace(+ '| Account Overview | account-overview.tsx | Show account highlights | account |',+ '| Account Overview | Page.tsx | Show account highlights | account |\n| Account Details | page.tsx | Show account details | account |'+ ).replace(+ '### Account Overview',+ '### Account Overview\n- **File:** Page.tsx\n- **Purpose:** Show account highlights\n- **Entities:** account\n- **Needs caching:** true\n- **Key Features:** Search and summary cards\n- **Components:** Card, Button\n- **Layout:** Responsive grid\n- **Data Binding:** queryTable("account")\n- **Interactions:** Search box filters cards\n\n### Account Details'+ );+ const errors = validateGenpagePlanSchema(plan);+ assert.ok(+ errors.some((error) => error.code === 'duplicate-page-file' && /Page\.tsx|page\.tsx/i.test(error.message)),+ `expected duplicate-page-file, got ${JSON.stringify(errors)}`+ );+});diff --git a/evals/model-apps/genpage/tests/assertions-layer-2.test.js b/evals/model-apps/genpage/tests/assertions-layer-2.test.jsindex bc2668626..0e35e2f5c 100644--- a/evals/model-apps/genpage/tests/assertions-layer-2.test.js+++ b/evals/model-apps/genpage/tests/assertions-layer-2.test.js@@ -235,6 +235,34 @@ test('no TODO: pass when spreads exist (...props is fine)', () => {assert.equal(result.status, 'pass');});+test('no TODO: fail on executable template elision and bare-line multiline spread', () => {+ const check = ASSERTIONS.get('Generated .tsx does NOT include any `TODO`, `FIXME`, ellipsis placeholders, or incomplete function bodies');+ const spread = ['const rows = [1, 2];', 'const copy = [', ' ...', ' rows', '];'].join('\n');+ const template = [+ 'const GeneratedComponent = () => {',+ ' const title = `${(() => {',+ ' ...',+ ' })()}`;',+ ' return null;',+ '};',+ ].join('\n');+ // Documented limit: a line holding only `...` fails closed as a placeholder. Generators should+ // write multiline spread as `...rows` on one line.+ assert.equal(check({ files: [f('spread.tsx', spread)], eval: evalStub() }).status, 'fail');+ const blockElision = ['export default function GeneratedComponent() {', ' ...', ' renderRows();', ' return null;', '}'].join('\n');+ assert.equal(check({ files: [f('template.tsx', template)], eval: evalStub() }).status, 'fail');+ assert.equal(check({ files: [f('block.tsx', blockElision)], eval: evalStub() }).status, 'fail');+});++// The eval and the runtime worker-output gate share one rule (findElisionMarker): elision counts only+// in a comment or a bare line, so the same words as UI copy never fail a page.+test('no TODO: UI copy with an ellipsis or the word TODO passes; an elision comment fails', () => {+ const check = ASSERTIONS.get('Generated .tsx does NOT include any `TODO`, `FIXME`, ellipsis placeholders, or incomplete function bodies');+ const copy = `const s = ['TODO', 'DONE'];\nconst el = <Spinner label="Loading…">Search documents...</Spinner>;`;+ assert.equal(check({ files: [f('a.tsx', copy)], eval: evalStub() }).status, 'pass');+ assert.equal(check({ files: [f('a.tsx', `${copy}\n// ... rest of the component`)], eval: evalStub() }).status, 'fail');+});+// ---------- assertion: DataGrid needs createTableColumn + sizing ----------test('DataGrid: skip when no DataGrid usage', () => {diff --git a/evals/model-apps/genpage/tests/run-layer-1.test.js b/evals/model-apps/genpage/tests/run-layer-1.test.jsindex ddcf3d366..0bfea472e 100644--- a/evals/model-apps/genpage/tests/run-layer-1.test.js+++ b/evals/model-apps/genpage/tests/run-layer-1.test.js@@ -72,6 +72,8 @@ No entity creation required — all entities already exist.None## Connector BindingsNo connector bindings.+## Custom API Bindings+No custom API bindings.## Design Preferences- Styling: clean- Features: mock dashboarddiff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.mdindex c8dd690b2..2a5d09232 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -660,6 +660,9 @@ scripts/smoke-eval.js ← scripted live smoke eval (build → assert → teardown)generate-page-manifest.js ← Phase 0.5: writes working-dir package.json + genpage.d.tsgenpage-upload.js ← /genpage: deploy one page via the shared wrapper (prompt passed BY FILE, never on a command line)+ genpage-plan-provenance.js ← /genpage: quarantine a stale plan before the planner writes, then verify the written plan targets the pages the approval named+ check-page-files.js ← /genpage: pre-dispatch gate — the page file names of the plan's one ## Pages table are safe write targets (lib/page-file-targets.js)+ genpage-worker-output.js ← /genpage: accept a parallel worker's page only if complete (default export, balanced, no elided code)capture-fixture.js ← Copies /genpage working dir into an eval fixture and runs both runnerslib/entity-provision.js ← Shared entity-provisioning core (solution + data-model + sample-data)@@ -673,6 +676,7 @@ scripts/op-diff.js ← destructive-op diff + --allow-destructive / --non-interactive gatingartifact-intent.js ← pure App Spec → canonical SDK intent compiler (new form topology; no SDK calls)page-plan.js ← pure App Spec → plan-document projection used by write-page-plan.js+ page-file-targets.js ← the one page-filename rule (absolute/backslash/traversal/.tsx only/links/case collision, incl. with files already there), shared with check-page-files.js and the evalssource-literals.js ← TSX lexer (code/comment/string/template/regex/JSX) — see "Known limits" belowsdk-teardown.js ← app-builder teardown engine (planTeardown is pure)sdk-http-client.js ← az-token HttpClient for the vendored SDK@@ -862,7 +866,27 @@ All three flags currently ship **OFF**, each waiting on cross-repo dependencies:**`scripts/lib/source-literals.js` — known limits.** It is a hand-rolled TSX lexer, not aparser: the plugin ships dependency-free, so there is no TypeScript to call. It trackscode / line comment / block comment / string / template / regex / JSX tag / JSX text, and-backs the `promote-intent-pages.js` structural gate plus the eval's effect scoper.+backs the `promote-intent-pages.js` structural gate plus the eval's effect scoper. It also+backs the navigation oracle (`pageref-resolver.js`), which finds each call AND parses its object+in the lexer's mask — executable code inside a template's `${…}` is visible, template text and+string bodies are not — and reads each value from the source at the same offsets, so one lexer+drives both. It also backs the worker-output gate+(`genpage-worker-output.js`), and `findElisionMarker` — the one "was code elided?" rule the+worker gate and the Layer 2 eval share (a `FIXME` comment, a `TODO` that opens a comment or takes+a colon, a comment opening with `...`, "omitted for brevity", or a bare `...` line; the same words+as UI copy — "Loading…", a `'TODO'` status value — are not elision). A template's `${…}` body is+code and is read by the same lexer (`lexInto`), JSX and comments included, never by a lighter+scanner. Whether a `/` or `<` starts a regex or JSX is judged by the code before it: never by a+comment's last word; a keyword read back as a property name (`counts.new / total`) or a postfix+`!` / `++` ends an operand; and a `)` ends one too, unless it closes an `if` / `for` / `while`+head, after which a statement starts. Each of those rules was once broken, and each break refused+a complete page as truncated or hid a navigation call. `hasDefaultExport` also needs the export+itself to be complete (a function or class reaches its body; a bare name is one the module+declares or imports, not a token that merely appears — the `as` of `import * as React` is not a+binding), because a write cut inside its export line balances; any complete `export default` will+do, for overloads. And `endsMidStatement` catches the cuts that leave every bracket balanced: the+lexer reports when a file stops inside a string, template, comment or JSX element, and a file+may not end on a token that needs more (`a +`, `React.`, `=>`). Both gates run all three checks.Judge changes to it by **both** error directions, and weight them correctly:- a false **accept** promotes prose as a page, and promotion is sticky — the page is then@@ -874,7 +898,10 @@ Judge changes to it by **both** error directions, and weight them correctly:committed `.tsx` in `samples/` and `evals/model-apps/genpage/fixtures/` (enumerated via`git ls-files`, so it does not race the transient fixture dirs `capture-fixture.test.js`creates). Two lexer bugs were invisible to hand-written cases and caught only by that-corpus — keep it, and add to it rather than around it.+corpus — keep it, and add to it rather than around it. The worker-output gate+(`genpage-worker-output.test.js`) and the icon hook (`validate-icon-imports.test.js`, samples+only) run the same kind of corpus: every committed page must pass them, because a false reject+there throws away a good page or blocks a pattern the page builder was told to copy.Residual limits, accepted deliberately:- **`<` disambiguation is structural, not semantic.** A generic arrow is recognised by itsdiff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex 6f9229cf1..d022d0c05 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -197,6 +197,95 @@ downloads that round-trip Choice columns.keep 60 s), and a conditional write that gets no answer is reported rather than re-sent: it maystill commit, and a re-send could only be refused as a false version conflict. Activating abusiness process flow on a newly created table can take longer than the old 60 s.+- **`/genpage` runs only the plan you approved** ([#585]). An edit plan is read as an edit, by its file name,+ and the approval preview by its own Current State block and the written plan by its own File Being Edited+ section, so a Pages table or an edit section quoted from the page's prompt cannot make an edit of another+ page pass. A plan left over from an earlier run is+ quarantined before the planner writes, and the new file must build exactly the pages the approved+ plan named — so a planner that failed to write, or wrote a different plan, halts instead of running it.+ A link at the plan path, its approval sidecar or the quarantine folder (a dangling one included), or a+ hard link at either file, is refused rather than written through, and an overlong or conflicting page+ id is refused, not truncated to a valid-looking one. An edit's target is the page the preview's own+ File line names, so neither a path quoted from the page's prompt nor another file in its folder+ (`page.tsx.bak`) can stand in for it.+- **A truncated page is caught before deploy** ([#585]). Every page — each parallel worker's, and one+ written inline — is checked for a complete default export, balanced brackets and elided code+ (`// TODO`, `// ...`, "omitted for brevity"). A write cut off where every bracket still balances+ fails too: inside its own export line (`export default function Page(props)` with no body),+ inside JSX, a string or a comment, or right after an operator — in `/app-builder`'s page promotion+ as well. A failing worker page is rebuilt inline, and an inline page that still fails halts.+ "Loading…" in a label is UI copy, not elision.+- **A missing `## Custom API Bindings` section halts instead of meaning "none"** ([#585]). Only the+ exact `No custom API bindings.` sentinel says a page has none, so a broken plan can no longer drop+ an approved binding. A plan made while `custom-api` was on halts too once the flag is off, instead+ of generating Custom API calls that deploy with no bindings.+- **Solution packaging checks every connection reference before changing anything** ([#585]). A+ missing reference used to fail after the app and pages had already been added to the solution.+- **Connections without both ids are no longer offered for binding** ([#585]). A listing where no row+ has a connection and a connector id is an error, not "no connections" — in every table layout PAC+ prints, including a connection row that matches none of its columns.+- **Right-to-left layout follows PAC's RTL column** ([#585]), not a list of six Arabic and Hebrew+ LCIDs — Persian, Urdu, other Arabic regions and the rest now render right to left.+- **Re-running the manifest generator with a new feature no longer reports success over a stale+ `package.json`** ([#585]). A missing package fails with the fix, and `/genpage` halts there for you+ to merge it or rerun with `--force`; a version you changed is kept and reported as `versionDrift`. A+ manifest saved with a UTF-8 byte-order mark (Windows PowerShell's default) is read as usual.+- **The code-generation rules list exactly the packages the page installs** ([#585]), and a test+ fails when they drift from the dependency map. Three libraries the rules offered but the package+ never installed are gone from the list.+- **Icons are verified however they are imported** ([#585]). A namespace, default, `require` or+ dynamic `import()` of `@fluentui/react-icons` is blocked — in any quote style, anywhere on a line,+ combined with a named import, or with a trailing comma or import options — since only named+ imports can be checked.+ A shipped sample that used two unverified sized icons is fixed, and every sample must now pass.+- **Navigation checks read code, not prose** ([#588]). A `navigateTo` in help text no longer counts+ as a link, and one inside a template's `${…}` is no longer invisible to the portability check. An+ emoji in a comment or a template, or a regex holding `/*`, `//` or a backtick+ (`u.replace(/\/*$/, "")`), no longer hides every call after it — which had left a placeholder link+ unresolved in the deployed page while verification passed.+- **A complete page is no longer rejected as truncated** ([#585]). `/app-builder`'s page promotion+ read these as unbalanced brackets and refused a finished page: braces in a nested template's text,+ a comment right before JSX or a regex, and a `/` after a property named like a keyword+ (`counts.new / total`), a non-null assertion (`closed! / total`) or `i++`, a division after a type+ cast (`total as NonNullable<number> / count`, its type arguments nested or across lines, and the+ name they belong to one part of a union, an intersection or a conditional type's false branch), and a+ file that ends in a member export such as `export default pages.Home` or a self-closing element+ with a callback prop. Two shapes the text alone cannot tell from a cut-off page are refused on+ purpose, and the page rules tell workers to avoid them: a line holding only `...` is always a+ placeholder, even where TypeScript would read a spread of the next line, and a file whose last+ statement ends in type arguments (`export default Page<string>`, a `type` alias) needs its `;`.+ The same checks back `/genpage`'s new gate.+- **A page's display name reaches the upload by file** ([#588]). `genpage-upload.js` takes `--name-file`, and+ `/genpage` writes the name to a file as it does the prompt: substituted into `--name "<name>"`, a shell expanded+ `$(…)` in it before the script ran, and `Revenue $100` arrived as `Revenue `.+- **`/genpage` single-quotes every value it fills into a command.** A working directory with a space in its+ path became two arguments, and a `$` in an app or solution name was expanded; the skill now states the rule+ once, every command template follows it, and a test fails when one drifts back.+- **The maker's text never passes through a shell, and the upload's input files never through a link.**+ `/genpage` writes the prompt, agent-message and page-name files with its file tool, not a shell command — even a+ single-quoted here-string ends at a line that begins with `'@`, and the rest of that line runs — after checking+ that none of those names is a link. `genpage-upload.js` refuses any of its input files (those three,+ `--connectors`, `--actions`) that is a link, a hard link or a folder, since a write through one rewrites the file+ it points to.+- **Page file names are checked before any worker writes** ([#588]). Absolute and drive-relative paths,+ `..`, backslash aliases, a character a shell would expand or split on (a space, `$`, a backtick, `;` —+ names use letters, digits, `.`, `-` and `_`), a name Windows cannot store (`CON.tsx`, a `:` — an NTFS alternate stream — or+ a trailing dot), a name that is not a `.tsx` page (`package.json`), a page path that is itself a link+ or not a regular file, a folder that links outside the working directory or cannot be read, and+ names that collide ignoring case (`Page.tsx` / `page.tsx`, with each other or with a file or folder+ already there) halt the build, as does a new page that is an already-built one reached through a link+ or junction, or a working directory that is a link or not a folder at all. A plan with a second Pages+ table naming files — one quoted in the requirements, fenced, quoted or not, and each table counted on its own,+ however many share a heading — halts too, instead of only the+ first being checked. So does a Pages section with any other table row beside its File table (a+ delimiter row repeated under a page row had made that row a header, and its page vanished from+ both checks) or a table with two File columns; a row written without its outer pipes is read like+ any other. `/app-builder` writes its page plan only as a plain file in the working+ directory, never through a link, hard link or folder at its path (`write-page-plan.js` no longer takes+ `--out`). The same rule covers the+ pages `/app-builder` generates — which now+ runs the disk checks too, before its workers — and the evals. A worker's page that is a folder or+ cannot be read fails its check instead of crashing it.- **An `already-exists` halt names the step that clears it.** A plain re-run keeps the workspace copythat was never recorded as pushed and halts again; the message now says to delete `.maker-workspace`first.diff --git a/plugins/model-apps/agents/genpage-page-builder.md b/plugins/model-apps/agents/genpage-page-builder.mdindex ced16c251..4f8a48372 100644--- a/plugins/model-apps/agents/genpage-page-builder.md+++ b/plugins/model-apps/agents/genpage-page-builder.md@@ -137,12 +137,14 @@ import has been Grep-validated against the verified list.## Step 2.6 — Runtime-only Griffel validation-`pac model genpage transpile` type-checks the page but does not execute-`makeStyles`; unsupported Griffel shorthands can therefore compile and then log-runtime errors in the browser. Before returning, Grep the generated `.tsx` with-the regex `['"]?borderWidth['"]?\s*:` so unquoted, quoted, and spaced property-syntax are all caught. Replace every match with the four explicit longhands:-`borderTopWidth`, `borderRightWidth`, `borderBottomWidth`, and+`pac model genpage transpile` only transpiles the page: it does not type-check it+(a type error, or a reference to a column that does not exist, still transpiles+and writes JavaScript), and it does not execute `makeStyles`. A clean transpile is+therefore no proof that the page is type-safe, and unsupported Griffel shorthands+can compile and then log runtime errors in the browser. Before returning, Grep the+generated `.tsx` with the regex `['"]?borderWidth['"]?\s*:` so unquoted, quoted,+and spaced property syntax are all caught. Replace every match with the four+explicit longhands: `borderTopWidth`, `borderRightWidth`, `borderBottomWidth`, and`borderLeftWidth`. Do not return a file that still matches the regex.## Step 3 — Read References and Samples@@ -177,10 +179,13 @@ Custom-API-backed and also read:${PLUGIN_ROOT}/references/custom-api.md```-If the `## Custom API Bindings` section is the literal `No custom API bindings.`, is-empty, is missing entirely, or contains no binding row, the page has **no Custom APIs** —-do not read custom-api.md and do not emit any `executeAction` / `executeFunction` /-`listBoundActions` code.+If the `## Custom API Bindings` section is exactly `No custom API bindings.`, the page has+**no Custom APIs** — do not read custom-api.md and do not emit any `executeAction` /+`executeFunction` / `listBoundActions` code. That sentinel is the only way a plan says+"none". If the section is empty, missing entirely, or neither the sentinel nor a binding+table, **stop and report it instead of writing the page**: the orchestrator halts on such a+plan before dispatch, so reaching you means the plan is broken, and treating it as "no+Custom APIs" would silently drop an approved binding.Only when your dispatch says **`Telemetry: enabled`** *and* the maker's own requestasks to measure, track, monitor, or diagnose something do you instrument the page and@@ -304,6 +309,8 @@ export default GeneratedComponent;- TimePicker from `@fluentui/react-timepicker-compat`- **Single-file architecture** — all components, utilities, styles in one `.tsx` file- **No external libraries** — only React, Fluent UI V9, approved Fluent icons, D3.js for charts+ (see `references/supported-dependencies.md`; `scripts/lib/supported-dependencies.js`+ is the source of truth for the generated package names, versions, and feature gates)- **makeStyles with tokens** — no inline styles for static values```typescriptconst useStyles = makeStyles({diff --git a/plugins/model-apps/agents/genpage-planner.md b/plugins/model-apps/agents/genpage-planner.mdindex e29df9387..d5ad73816 100644--- a/plugins/model-apps/agents/genpage-planner.md+++ b/plugins/model-apps/agents/genpage-planner.md@@ -170,7 +170,16 @@ pac model list-languagesNote the output. If multiple languages are configured (or any non-English language),localization will be included in the generated code. Include the detected languages-when reporting the environment to the user.+when reporting the environment to the user. Record each language's **LCID, Code and RTL**+columns exactly as PAC prints them, for example:++```+LCID Language Code RTL+1025 Arabic (Saudi Arabia) ar-SA Yes+```++The page builder takes text direction from that RTL value, never from a list of LCIDs it+remembers (`references/localization.md` → *RTL Layout Support*).### Continue Requirements Gathering@@ -492,7 +501,8 @@ plan mode does not reach the user from a subagent.- [solution unique name and prefix — always shown, "Default / new" for code-only flows]### Localization-- [list detected languages, or "English only — no localization needed"]+- [each detected language as `<LCID> <Code> — RTL: Yes|No` from `pac model list-languages`+ (e.g. `1025 ar-SA — RTL: Yes`), or "English only — no localization needed"]### Design- [styling preferences, features, accessibility notes from requirements]@@ -519,7 +529,9 @@ ${PLUGIN_ROOT}/references/plan-schema.md```Read that file before writing the plan. Every required section must be present with-the exact heading. Page filenames in the `## Pages` table must be unique.+the exact heading. Page filenames in the `## Pages` table must be unique, and use only letters,+digits, `-`, `_` and `.` — kebab-case such as `project-overview.tsx`, never a space or a shell+character: the dispatch gate refuses any other name, and the build halts.### CRITICAL — Prefix discipline in `## Entity Creation Required`diff --git a/plugins/model-apps/hooks/README.md b/plugins/model-apps/hooks/README.mdindex 30f16bd63..b7b17c04e 100644--- a/plugins/model-apps/hooks/README.md+++ b/plugins/model-apps/hooks/README.md@@ -20,7 +20,7 @@ back.| 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`. |+| `Write\|Edit\|MultiEdit` | `validate-icon-imports.js` | On every code write, validates `@fluentui/react-icons` imports against `references/verified-icons.txt`. Only named imports can be checked, so a namespace (`import * as`), default, `require(...)` or dynamic `import(...)` of the icon module is blocked too — where it is code; quoted in a string, a template or a comment it is not. Every committed `samples/*.tsx` must pass it (a test enforces this). |## UserPromptSubmitdiff --git a/plugins/model-apps/hooks/validate-icon-imports.js b/plugins/model-apps/hooks/validate-icon-imports.jsindex 73c71a6d4..eb32c9093 100644--- a/plugins/model-apps/hooks/validate-icon-imports.js+++ b/plugins/model-apps/hooks/validate-icon-imports.js@@ -30,6 +30,7 @@const fs = require('fs');const path = require('path');+const { blankNonCodePreservingTemplateExpressions, commentRanges } = require('../scripts/lib/source-literals.js');const PLUGIN_ROOT = path.resolve(__dirname, '..');const VERIFIED_ICONS_PATH = path.join(PLUGIN_ROOT, 'references', 'verified-icons.txt');@@ -141,17 +142,28 @@ function extractIconImports(content) {// starting with `//…` so it fails the identifier test and is silently skipped,// and (b) a `}` inside a `//` comment prematurely ends the `[^}]+` capture and// the whole import fails to match — both fail OPEN (a bad icon slips through).- // The `(?<!:)` lookbehind on the line-comment strip preserves `https://` URLs.- const code = content- .replace(/\/\*[\s\S]*?\*\//g, ' ')- .replace(/(?<!:)\/\/[^\n]*/g, '');+ //+ // And only an `import` in CODE counts, as in extractUnsupportedIconImports: an import line quoted in a+ // help template or a string is data, and blocking a write over it broke that contract. So the match runs+ // on a copy with every comment the lexer finds blanked to spaces — offsets kept, so the code mask lines up+ // (and a `//` inside a string is no comment) — and a match whose `import` is not code is skipped. Should+ // the lexer throw, the older comment-stripped match runs instead, which treats every such line as real.+ let codeMask = null;+ let code = null;+ try {+ codeMask = blankNonCodePreservingTemplateExpressions(content);+ code = blankComments(content);+ } catch { codeMask = null; }+ // The `(?<!:)` lookbehind on the fallback's line-comment strip preserves `https://` URLs.+ if (!codeMask) code = stripCommentsForImports(content);const escapedModule = ICON_MODULE.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');const re = new RegExp(- "^[ \\t]*import\\s+(?:type\\s+)?\\{([^}]+)\\}\\s*from\\s*['\"]" + escapedModule + "['\"]",- 'gm'+ "(?<![\\w$.])import\\s+(?:type\\s+)?(?:[A-Za-z_$][\\w$]*\\s*,\\s*)?\\{([^}]+)\\}\\s*from\\s*['\"]" + escapedModule + "['\"]",+ 'g');let m;while ((m = re.exec(code)) !== null) {+ if (codeMask && !codeMask.startsWith('import', code.indexOf('import', m.index))) continue;for (const raw of m[1].split(',')) {const spec = raw.trim();if (!spec) continue;@@ -163,6 +175,92 @@ function extractIconImports(content) {return names;}+function stripCommentsForImports(content) {+ return content+ .replace(/\/\*[\s\S]*?\*\//g, ' ')+ .replace(/(?<!:)\/\/[^\n]*/g, '');+}++// `content` with each comment the lexer finds turned into spaces, newlines kept, so every offset is+// unchanged. Unlike stripCommentsForImports, a `//` inside a string or JSX text is left alone.+function blankComments(content) {+ const out = content.split('');+ for (const { start, end } of commentRanges(content)) {+ for (let k = start; k < end; k += 1) if (out[k] !== '\n') out[k] = ' ';+ }+ return out.join('');+}++/**+ * Detect @fluentui/react-icons import shapes this hook cannot verify safely.+ *+ * Raw forms that bypass named-specifier validation:+ * import * as Icons from "@fluentui/react-icons";+ * import Icons from "@fluentui/react-icons";+ * const Icons = require("@fluentui/react-icons");+ *+ * Rejecting them is intentionally safer than parsing every namespace member access in TSX:+ * the verified-icons.txt source of truth lists named exports, and named imports make the exact+ * export names visible at the import boundary where this dependency-free hook can validate them.+ */+function extractUnsupportedIconImports(content) {+ const escapedModule = ICON_MODULE.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const unsupported = [];+ // The require and dynamic-import forms are matched ANYWHERE in the code, not only as a declaration:+ // React.createElement(require("@fluentui/react-icons").TotallyMadeUpIconRegular)+ // const Icons = await import("@fluentui/react-icons");+ // both reach an icon by member access, which no named-specifier check ever sees.+ const patterns = [+ // Static imports need code-token boundaries, not line starts: generated files often put+ // `import React ...; import * as Icons ...` on one line. Combined clauses are unsupported too+ // (`import DefaultIcon, * as Icons ...`, `import DefaultIcon, { AddRegular } ...`) because the+ // default/namespace binding can still reach unchecked member names even when named imports exist.+ { kind: 'namespace import', keyword: 'import', re: new RegExp("(?<![\\w$.])import\\s+(?:[A-Za-z_$][\\w$]*\\s*,\\s*)?\\*\\s+as\\s+[A-Za-z_$][\\w$]*\\s+from\\s*['\"]" + escapedModule + "['\"]", 'g') },+ { kind: 'default import', keyword: 'import', re: new RegExp("(?<![\\w$.])import\\s+[A-Za-z_$][\\w$]*(?:\\s*,\\s*(?:\\{[^}]*\\}|\\*\\s+as\\s+[A-Za-z_$][\\w$]*))?\\s+from\\s*['\"]" + escapedModule + "['\"]", 'g') },+ // Loader forms are blocked only when the FIRST argument is the complete module string. A derived+ // expression such as `require("@fluentui/react-icons".replace("icons", "components"))` loads a+ // different module and must not be blocked; trailing commas/options still load the icon namespace.+ { kind: 'CommonJS require', keyword: 'require', re: new RegExp("\\brequire\\s*\\(\\s*['\"`]" + escapedModule + "['\"`]\\s*(?:[,)])", 'g') },+ { kind: 'dynamic import()', keyword: 'import', re: new RegExp("\\bimport\\s*\\(\\s*['\"`]" + escapedModule + "['\"`]\\s*(?:[,)])", 'g') },+ ];+ // Only a keyword in CODE is an import. The plugin's TSX lexer blanks comments, strings, template+ // text and JSX text but keeps code inside `${…}`, so an import merely quoted in a help string, a+ // template or a comment does not block a write. The patterns run on a copy with every comment+ // turned into spaces of the same length: a comment BETWEEN an import's tokens —+ // import * as /* every icon */ Icons from "@fluentui/react-icons";+ // import Icons // all of them+ // from "@fluentui/react-icons";+ // — must not break the match, and the offsets must still line up with the code mask. Should the+ // lexer ever throw, fall back to the older comment-stripped match: a write wrongly blocked is+ // better than an unverified icon let through.+ let codeMask = null;+ let haystack = null;+ try {+ codeMask = blankNonCodePreservingTemplateExpressions(content);+ haystack = blankComments(content);+ } catch { codeMask = null; }+ if (!codeMask) haystack = stripCommentsForImports(content);+ for (const { kind, keyword, re } of patterns) {+ for (const m of haystack.matchAll(re)) {+ const at = haystack.indexOf(keyword, m.index);+ if (!codeMask || codeMask.startsWith(keyword, at)) { unsupported.push(kind); break; }+ }+ }+ return unsupported;+}++function buildUnsupportedImportMessage(relPath, unsupported) {+ const unique = [...new Set(unsupported)];+ return [+ `[model-apps] The write was blocked: ${ICON_MODULE} must use named imports so each icon export can be checked against references/verified-icons.txt.`,+ '',+ `For the agent: BLOCKED — unsupported ${ICON_MODULE} import form(s) in ${relPath}:`,+ ...unique.map((kind) => ` - ${kind}`),+ '',+ 'Rewrite the import as named unsized exports, for example `import { AddRegular } from "@fluentui/react-icons";`, then verify every imported name exists verbatim in references/verified-icons.txt.',+ ].join('\n');+}+function buildBlockMessage(relPath, invalid) {const lines = [];// User-facing summary — short, no jargon. States what happened (a block); the@@ -217,6 +315,13 @@ process.stdin.on('end', () => {// Only validate genpage-generated pages (see SCOPING note above).if (!isGenpageFile(content, absPath)) process.exit(0);+ const relPath = path.relative(cwd, absPath) || absPath;+ const unsupported = extractUnsupportedIconImports(content);+ if (unsupported.length > 0) {+ process.stderr.write(buildUnsupportedImportMessage(relPath, unsupported) + '\n');+ process.exit(2);+ }+const imported = extractIconImports(content);if (imported.length === 0) process.exit(0);@@ -233,7 +338,6 @@ process.stdin.on('end', () => {}if (invalid.length === 0) process.exit(0);- const relPath = path.relative(cwd, absPath) || absPath;process.stderr.write(buildBlockMessage(relPath, invalid) + '\n');process.exit(2);});diff --git a/plugins/model-apps/references/localization.md b/plugins/model-apps/references/localization.mdindex d4af80346..208c681ca 100644--- a/plugins/model-apps/references/localization.md+++ b/plugins/model-apps/references/localization.md@@ -30,8 +30,11 @@ const language = React.useMemo(() => {const uiLanguageId = (typeof Xrm !== "undefined" &&Xrm.Utility?.getGlobalContext()?.userSettings?.languageId) || 1033;const langMap: Record<number, { code: string; name: string; isRtl: boolean }> = {- // Populate entries from pac model list-languages output, mapped to LCID info.- // Example: 1033: { code: "en-US", name: "English", isRtl: false },+ // One entry per language `pac model list-languages` reports, copied from its columns:+ // LCID Language Code RTL+ // 1033 English (United States) en-US No+ // becomes 1033: { code: "en-US", name: "English (United States)", isRtl: false }.+ // `isRtl` comes from the RTL column (see RTL Layout Support) — never from memory.};return langMap[uiLanguageId] || { code: "en-US", name: "English", isRtl: false };}, []);@@ -67,7 +70,28 @@ Usage: `<Text>{translate("title")}</Text>` — never `<Text>Dashboard</Text>`.### RTL Layout Support-Detect RTL from the language LCID. Arabic (1025, 2049, 3073, 4097, 5121) and Hebrew (1037) are RTL.+Take each language's direction from the **RTL** column of `pac model list-languages` (carried into the+plan's `## Environment` → `Languages` line as a `— RTL` mark) — never from a hand-written list of LCIDs. The platform derives that column+from culture data, and a list always misses some: Windows culture data marks more than 40 right-to-left+cultures — every Arabic region, Persian and Dari, Urdu, Pashto, Sindhi, Uyghur, Divehi, Syriac, Central+Kurdish, Hebrew and Yiddish among them — and a language a list forgot renders left-to-right.++If a PAC build prints no RTL column, compute the flag from the language's **Code** instead. Direction is a+property of the script a language is written in, and `Intl.Locale#maximize()` fills in the likely script+from CLDR (`fa` → `fa-Arab-IR`, `ur-PK` → `ur-Arab-PK`, `dv-MV` → `dv-Thaa-MV`):++```typescript+// ISO 15924 scripts written right-to-left.+const RTL_SCRIPTS = new Set(["Arab", "Hebr", "Syrc", "Thaa", "Nkoo", "Adlm", "Rohg", "Mand", "Samr"]);+const isRtlLocale = (code: string): boolean => {+ try {+ // `Intl.Locale` is typed only from the ES2020 lib, so the cast keeps an older `lib` setting compiling.+ return RTL_SCRIPTS.has(new (Intl as any).Locale(code).maximize().script ?? "");+ } catch {+ return false; // not a valid BCP-47 tag+ }+};+```- Wrap the root element with the `dir` attribute: `<div dir={language.isRtl ? "rtl" : "ltr"}>`.- Use **logical CSS properties** instead of physical ones:diff --git a/plugins/model-apps/references/plan-schema.md b/plugins/model-apps/references/plan-schema.mdindex 15d1c125e..94a163922 100644--- a/plugins/model-apps/references/plan-schema.md+++ b/plugins/model-apps/references/plan-schema.md@@ -38,7 +38,9 @@ same relative position so downstream parsers can find them predictably:- App: [app name] ([app-id]) OR "create new: [name]"- Mode: app-builder ← **only** when the plan was projected from an App Spec by`scripts/write-page-plan.js`; omitted for a planner-authored (standalone `/genpage`) plan-- Languages: [detected languages with LCIDs, or "English (1033) only"]+- Languages: [each detected language with its LCID and code, marked `— RTL` when the RTL column of+ `pac model list-languages` says Yes — e.g. "English (1033, en-US); Arabic (Saudi Arabia) (1025,+ ar-SA) — RTL" — or "English (1033) only". The page builder takes text direction from that mark.]- Solution: [solution unique name — ALWAYS present, default fallback is "Default"]- Publisher Prefix: [prefix tied to the solution's publisher — ALWAYS present, default fallback is "new"]@@ -205,7 +207,7 @@ connector bindings." sentinel).]| `## Working Directory` | All downstream agents | Absolute path, forward slashes on Windows || `## Plugin Root` | Page-builder (to Read references/samples) | Absolute path || `## Environment` | Orchestrator | URL, app decision, languages |-| `## Pages` | Orchestrator (page list for Phase 5 dispatch) | File names must be unique |+| `## Pages` | Orchestrator (page list for Phase 5 dispatch) | File names must be unique, and use only letters, digits, `.`, `-` and `_` (kebab-case, e.g. `project-overview.tsx`). Exactly one Pages table with a File column: `check-page-files.js` refuses a plan with a second, one quoted in `## User Requirements` included || `## Entity Creation Required` | Entity-builder | Exact literal "No entity creation required..." when empty, else per-entity subsections || `## Existing Entities` | Orchestrator (for `pac model genpage generate-types --data-sources`) | Comma-separated logical names || `## Connector Bindings` | Planner, page-builder, orchestrator deploy | Exact literal "No connector bindings." when empty; logical names must match Dataverse connectionreferences; tabular bindings must include discovered optional `Fields`; REST/action bindings must include discovered `Parameters` and `Response` |diff --git a/plugins/model-apps/references/rules.md b/plugins/model-apps/references/rules.mdindex 7bb83203b..3310aa11c 100644--- a/plugins/model-apps/references/rules.md+++ b/plugins/model-apps/references/rules.md@@ -25,25 +25,43 @@ Comprehensive rules for generating generative page code. Read this file during c17. **No full-viewport modal scrims; prefer non-modal or in-page panels**: A default `<Dialog>` is `modalType="modal"` — it draws a `position: fixed` backdrop and traps focus across the whole window, which in the designer blankets the agent panel and locks the user out (they can't even ask the agent to remove it). Default dialogs to `modalType="non-modal"` **and** pass `mountNode`, or use an in-page absolutely-positioned panel. The page root must establish a containing block (`position: relative` + `contain: layout`) so even a fixed-position overlay is clipped to the page. Never size overlays to the viewport. See **Special Patterns > Dialogs and Overlays**.18. **Never nest a `<Dialog>` inside another `<Dialog>`**: Stacked modal scrims and nested focus traps make dialogs impossible to dismiss reliably. Render sibling dialogs as separate top-level surfaces switched by state, never one `<Dialog>` as a child of another's JSX.19. **All hooks above every early return — no conditional hook calls**: Detail/record pages crash with **minified React error #310** ("rendered more/fewer hooks than the previous render") on the *first* open of a record, then work on the second click. Cause: a hook — usually a `useMemo` deriving chart points or display rows from loaded data — sits *below* a loading/empty early return (`if (data.loading) return <Spinner/>`). On the first render data is still loading, the component early-returns and never reaches that `useMemo` (fewer hooks); when data arrives it renders past the return and calls the extra hook → the hook count differs between renders → #310. The "works the second time" intermittency (the cached render skips the loading branch) is the signature of this bug. **Fix:** place every `useMemo`/`useState`/`useEffect`/`useCallback` **above all early returns**, and make derived memos tolerate not-yet-loaded data (read from an always-initialized value, e.g. `data.rows ?? []`). Early returns are fine — they just must come *after* the last hook call. This is the React rules of hooks: never call a hook below a conditional `return`.+20. **Never put `...` alone on a line**: Write the spread/rest token and its operand together (`...rows`, not `...` followed by `rows` on the next line).+21. **End final type-argument statements with `;`**: If the file's last statement ends in a type argument list (`Page<string>`, `Array<Row>`), terminate it with a semicolon.---## Supported Libraries-Only these libraries are available. Do NOT use any other library.--```-"react": "^17.0.2"-"uuid": "^9.0.1"-"@fluentui/react-icons": "^2.0.292"-"@fluentui/react-calendar-compat": "^0.2.2"-"@fluentui/react-components": "^9.46.4"-"@fluentui/react-datepicker-compat": "^0.5.0"-"@fluentui/react-timepicker-compat": "^0.3.0"-"@fluentui/react-theme": "^9.1.24"-"d3": "^7.9.0"+Only the generated `package.json` dependencies below are available. Do NOT use+any other library. `scripts/lib/supported-dependencies.js` is the source of+truth for names, versions, and feature gates; this example is validated against+that module by `scripts/tests/supported-dependencies-docs.test.js`.++```json+{+ "dependencies": {+ "react": "17.0.2",+ "react-dom": "17.0.2",+ "@fluentui/react-components": "^9.54.0",+ "@fluentui/react-icons": "2.0.326",+ "d3": "^7.8.5",+ "@fluentui/react-datepicker-compat": "^0.4.50",+ "@fluentui/react-timepicker-compat": "^0.2.40"+ },+ "devDependencies": {+ "typescript": "^5.4.0",+ "@types/react": "^17.0.80",+ "@types/react-dom": "^17.0.25",+ "@types/d3": "^7.4.3"+ }+}```+Feature-gated packages are installed only when the generator receives the+matching flag: `charts` adds `d3` and `@types/d3`, `datepicker` adds+`@fluentui/react-datepicker-compat`, and `timepicker` adds+`@fluentui/react-timepicker-compat`.+**CRITICAL**: DatePicker must be imported from `@fluentui/react-datepicker-compat` and TimePicker from `@fluentui/react-timepicker-compat` (NOT from `@fluentui/react-components`)---@@ -605,7 +623,7 @@ required patterns and the binding contract.### Custom API DataAPI (optional — only when the plan has Custom API Bindings)-When the plan's `## Custom API Bindings` is non-empty, the page may invoke Dataverse+When the plan's `## Custom API Bindings` contains a binding table, the page may invoke Dataverse**Custom APIs** (server-side plug-in logic) on the signed-in user's own token. A CustomAPI of kind **Action** (may mutate) is called with `dataApi.executeAction`; a **Function**(read-only) with `dataApi.executeFunction`; `dataApi.listBoundActions` enumerates thediff --git a/plugins/model-apps/references/supported-dependencies.md b/plugins/model-apps/references/supported-dependencies.mdindex ac43c6b10..ad3ca69b1 100644--- a/plugins/model-apps/references/supported-dependencies.md+++ b/plugins/model-apps/references/supported-dependencies.md@@ -7,10 +7,10 @@ populate the `package.json` written into each working dir during Phase 0.5.This makes the working dir installable (`npm install`) so VSCode IntelliSense,type-checking, and "go to definition" work after generation.-**Source of truth:** This doc tracks-`scripts/lib/supported-dependencies.js`. When the upstream genux runtime team-publishes an authoritative version list, update that file — this doc and the-generator both read from there.+**Source of truth:** `scripts/lib/supported-dependencies.js`. When the upstream+genux runtime team publishes an authoritative version list, update that file —+this doc, `references/rules.md`, and the generator are validated against it by+`scripts/tests/supported-dependencies-docs.test.js`.## Confidence levels@@ -65,6 +65,6 @@ When upstream confirms versions or a runtime upgrade lands:1. Edit `scripts/lib/supported-dependencies.js` — change the `version` field and (if applicable) flip `confidence` from `compatible` to `pinned`.2. Re-run `node --test plugins/model-apps/scripts/tests/generate-page-manifest.test.js` — the tests assert the generated manifest's dependency map, feature-flag handling, and `--force` behavior.-3. Update this doc to reflect the new versions (the table is hand-maintained from the JS module — a small sync script could automate it later).+3. Update this doc and `references/rules.md` to reflect the new versions; `scripts/tests/supported-dependencies-docs.test.js` fails if they drift from the JS module.4. Bump the plugin minor or patch version in `.plugin/plugin.json`.5. CHANGELOG entry under the appropriate version section.diff --git a/plugins/model-apps/references/troubleshooting.md b/plugins/model-apps/references/troubleshooting.mdindex 5d5728ca8..da73bc988 100644--- a/plugins/model-apps/references/troubleshooting.md+++ b/plugins/model-apps/references/troubleshooting.md@@ -46,7 +46,11 @@ This plugin creates **pages within existing** model-driven apps — it cannot cr## Page Upload Fails- Verify app-id: run `pac model list` to get the correct GUID-- Ensure `--name` is provided for new pages+- Ensure the page's display name is provided for new pages — written to a file and passed with `--name-file`, so a shell never reads it+- A page display name with a straight double quote (`"`) is stored with a backslash before each one (`\"Q3\"`). The name reaches pac intact, and the extra backslash is added inside pac. Until pac is fixed, use typographic quotes (`“Q3”`) in page names+- `--prompt-file …/prompt.txt is a symbolic link or junction, not a file written in place` (or `is a hard link`,+ for any input file): something other than the skill left a link at that name, and writing it may have changed+ the file it points to. Check that file, delete the link, and re-run; the skill then writes a plain file there- Check `.tsx` file exists and has no syntax errors- Verify `--data-sources` matches entities used in code- Ensure schema was generated for entity-based pagesdiff --git a/plugins/model-apps/samples/6-comprehensive-form.tsx b/plugins/model-apps/samples/6-comprehensive-form.tsxindex 40ca63bec..c9c4f8e7b 100644--- a/plugins/model-apps/samples/6-comprehensive-form.tsx+++ b/plugins/model-apps/samples/6-comprehensive-form.tsx@@ -2,7 +2,7 @@ import React, { useEffect, useState, useCallback, useRef } from 'react';import { Checkbox, Combobox, Field, Input, makeStyles, Option, Radio, RadioGroup, Slider, SpinButton, Switch, Textarea, tokens, Button, Text, Caption1, Subtitle1, Body1, MessageBar, useId as useFluentId, mergeClasses } from "@fluentui/react-components";import { DatePicker } from "@fluentui/react-datepicker-compat";import { TimePicker } from "@fluentui/react-timepicker-compat";-import { CheckmarkCircle20Filled, ErrorCircle20Filled } from "@fluentui/react-icons";+import { CheckmarkCircleFilled, ErrorCircleFilled } from "@fluentui/react-icons";const useStyles = makeStyles({container: { display: "flex", flexDirection: "column", gap: tokens.spacingVerticalXL, padding: tokens.spacingHorizontalM, maxWidth: "800px", margin: "0 auto", width: "100%", boxSizing: "border-box", height: '100%', overflowY: 'auto', "@media (max-width: 768px)": { padding: tokens.spacingHorizontalS, gap: tokens.spacingVerticalL }, "@media (max-width: 480px)": { padding: tokens.spacingHorizontalXS } },@@ -88,7 +88,7 @@ const GeneratedComponent: React.FC = () => {<Subtitle1 as="h1" block>User Information Form</Subtitle1><Body1 style={{ color: tokens.colorNeutralForeground2, marginTop: tokens.spacingVerticalXS }} block>Please fill out all required fields. Fields marked with * are mandatory.</Body1></header>- {submitMessage && <div className={styles.messageContainer}><MessageBar intent={submitMessage.type === "success" ? "success" : "error"} icon={submitMessage.type === "success" ? <CheckmarkCircle20Filled /> : <ErrorCircle20Filled />}>{submitMessage.content}</MessageBar></div>}+ {submitMessage && <div className={styles.messageContainer}><MessageBar intent={submitMessage.type === "success" ? "success" : "error"} icon={submitMessage.type === "success" ? <CheckmarkCircleFilled /> : <ErrorCircleFilled />}>{submitMessage.content}</MessageBar></div>}<form onSubmit={(e) => { e.preventDefault(); handleSubmit(); }} noValidate aria-label="User information form"><FormSection title="Basic Information" description="Tell us about yourself" titleId={basicInfoTitleId} descriptionId={basicInfoDescId}><div className={mergeClasses(styles.formGrid, styles.twoColumnGrid)}>diff --git a/plugins/model-apps/scripts/add-page-to-solution.js b/plugins/model-apps/scripts/add-page-to-solution.jsindex f0ef9bedc..67ca48b2b 100644--- a/plugins/model-apps/scripts/add-page-to-solution.js+++ b/plugins/model-apps/scripts/add-page-to-solution.js@@ -74,6 +74,21 @@ async function resolveEntityComponentType(envUrl, logicalName) {return componentType;}+async function resolveConnectionReferences(envUrl, refs) {+ const resolved = [];+ for (const logicalName of refs) {+ const query =+ `connectionreferences?$filter=connectionreferencelogicalname eq '${escapeODataString(logicalName)}'` ++ '&$select=connectionreferenceid&$top=1';+ const lookup = await dataverseRequest(envUrl, 'GET', query);+ ensureOk(lookup, `Lookup connection reference ${logicalName}`);+ const id = lookup.data?.value?.[0]?.connectionreferenceid;+ if (!id) throw new Error(`Connection reference '${logicalName}' not found in env`);+ resolved.push({ logicalName, id });+ }+ return resolved;+}+async function main() {const argv = process.argv.slice(2);const { positional, flags } = parseArgs(argv);@@ -122,6 +137,9 @@ async function main() {const connectionReferenceComponentType = refs.length? await resolveEntityComponentType(envUrl, CONNECTION_REFERENCE_LOGICAL_NAME): null;+ const resolvedConnectionRefs = refs.length+ ? await resolveConnectionReferences(envUrl, refs)+ : [];// The appmodule (type 80) with AddRequiredComponents=true pulls the sitemap and// appmodulecomponent, but NOT the GenPage — the page is added explicitly below.@@ -138,15 +156,7 @@ async function main() {const refsToAdd = connectionRefsToAdd(refs, connectorsOn);const skippedConnectionRefs = connectorsOn ? [] : refs;- for (const logicalName of refsToAdd) {- const query =- `connectionreferences?$filter=connectionreferencelogicalname eq '${escapeODataString(logicalName)}'` +- '&$select=connectionreferenceid&$top=1';- const lookup = await dataverseRequest(envUrl, 'GET', query);- ensureOk(lookup, `Lookup connection reference ${logicalName}`);- const id = lookup.data?.value?.[0]?.connectionreferenceid;- if (!id) throw new Error(`Connection reference '${logicalName}' not found in env`);-+ for (const { logicalName, id } of resolvedConnectionRefs.filter((ref) => refsToAdd.includes(ref.logicalName))) {await addComponent(envUrl, solutionUniqueName, id, connectionReferenceComponentType, false);added.push({ type: 'connectionreference', logicalName, id });}@@ -172,4 +182,5 @@ module.exports = {UXAGENTPROJECT_LOGICAL_NAME,CONNECTION_REFERENCE_LOGICAL_NAME,resolveEntityComponentType,+ resolveConnectionReferences,};diff --git a/plugins/model-apps/scripts/check-page-files.js b/plugins/model-apps/scripts/check-page-files.jsnew file mode 100644index 000000000..d84249c43--- /dev/null+++ b/plugins/model-apps/scripts/check-page-files.js@@ -0,0 +1,64 @@+#!/usr/bin/env node+'use strict';+// Pre-dispatch gate for /genpage: are the page files a plan names safe to hand to parallel workers?+//+// The rule itself lives in lib/page-file-targets.js (shared with /app-builder and the evals). This+// wrapper exists so the orchestrator — an AI following SKILL.md — gets a yes/no answer it cannot talk+// itself past: a traversal, an absolute path or two case-colliding names are easy to spot by eye, but+// a directory junction that points outside the working directory is not.+//+// Usage:+// node check-page-files.js --plan <working-dir>/genpage-plan.md [--working-dir <dir>]+// The working directory defaults to the plan file's own directory, which is where /genpage writes it.+//+// Output (one JSON line) and exit code:+// 0 {"ok":true,"workingDir":…,"files":[…],"problems":[]}+// 3 {"ok":false,…,"problems":[{"file","code","message"}]} — halt and re-plan+// 1 usage error, or the plan has no readable ## Pages table, or more than one with a File column++const fs = require('node:fs');+const path = require('node:path');+const { pageFileProblems, pagesTables } = require('./lib/page-file-targets.js');++function checkPageFiles({ planPath, workingDir }) {+ if (!planPath) return { exit: 1, result: { ok: false, error: '--plan is required' } };+ const abs = path.resolve(planPath);+ let plan;+ try {+ plan = fs.readFileSync(abs, 'utf8');+ } catch (e) {+ return { exit: 1, result: { ok: false, error: `--plan could not be read: ${e.message}` } };+ }+ const { tables, unreadable } = pagesTables(plan);+ if (unreadable) {+ return { exit: 1, result: { ok: false, error: `${abs} has table rows in a Pages section that are not its File table's rows (rows ahead of its header, a second delimiter row, a table with no File column beside it, or two File columns), so which files they name cannot be read — re-plan with the one table` } };+ }+ // Refused, not read by the first: a Pages table quoted in the requirements (fenced or not) decided the+ // files checked here while the workers wrote the real table's (lib/page-file-targets.js).+ if (tables.length > 1) {+ return { exit: 1, result: { ok: false, error: `${abs} has ${tables.length} Pages tables with a File column, so which one the pages come from is ambiguous (a table quoted in the requirements counts too) — re-plan with exactly one` } };+ }+ const files = tables.length ? tables[0] : null;+ if (!files) return { exit: 1, result: { ok: false, error: `${abs} has no ## Pages table with a File column` } };+ if (!files.length) return { exit: 1, result: { ok: false, error: `${abs} lists no pages` } };+ const root = path.resolve(workingDir || path.dirname(abs));+ const problems = pageFileProblems(files, { workingDir: root });+ return { exit: problems.length ? 3 : 0, result: { ok: problems.length === 0, workingDir: root, files, problems } };+}++function parseArgv(argv) {+ const out = {};+ for (let i = 0; i < argv.length; i += 1) {+ if (argv[i] === '--plan') { out.planPath = argv[i + 1]; i += 1; }+ else if (argv[i] === '--working-dir') { out.workingDir = argv[i + 1]; i += 1; }+ }+ return out;+}++if (require.main === module) {+ const { exit, result } = checkPageFiles(parseArgv(process.argv.slice(2)));+ process.stdout.write(JSON.stringify(result) + '\n');+ process.exit(exit);+}++module.exports = { checkPageFiles };diff --git a/plugins/model-apps/scripts/generate-page-manifest.js b/plugins/model-apps/scripts/generate-page-manifest.jsindex 630be131f..70e120be1 100644--- a/plugins/model-apps/scripts/generate-page-manifest.js+++ b/plugins/model-apps/scripts/generate-page-manifest.js@@ -13,8 +13,11 @@// here.//// Run by the /genpage orchestrator in Phase 0.5 (after working-dir creation).-// Idempotent by default — skips files that already exist. Pass --force to-// overwrite.+// Keeps existing files by default, but an existing package.json must already list+// every package the requested features need — otherwise the run fails (exit 2) and+// names them, rather than report success over a manifest `npm install` cannot use.+// A package present at a different version is kept and reported as `versionDrift`.+// Pass --force to overwrite.//// Usage:// node generate-page-manifest.js <working-dir> <page-slug> [--features <list>] [--force]@@ -31,7 +34,7 @@// Exit codes:// 0 success// 1 invalid arguments-// 2 I/O error+// 2 I/O error, or an existing package.json that lacks a required package or cannot be verifiedconst fs = require('node:fs');const path = require('node:path');@@ -100,6 +103,78 @@ function buildPackageJson(slug, features) {};}+// What an existing package.json lacks for the requested page, split by severity. A package ABSENT from+// both dependency sections breaks `npm install` for the page's imports, so the command must not report+// success. A package present at a DIFFERENT version is left alone: pinning or bumping a version is a+// legitimate edit, and failing on it would make every rerun fail unless `--force` discarded that edit.+// It is still reported (`drift`), so a pin left behind by an older plugin release is visible.+function comparePackageDependencies(pkg, expectedDependencies, expectedDevDependencies) {+ const section = (key) => (pkg && pkg[key] && typeof pkg[key] === 'object' && !Array.isArray(pkg[key]) ? pkg[key] : {});+ // Either section installs the package, so either satisfies it — but only with a version npm can use. A key+ // whose value is null, an object or an empty string installs nothing, so it counts as missing (not as a+ // version that drifted), and it never hides a usable entry for the same package in the other section.+ const usable = (v) => typeof v === 'string' && v.trim() !== '';+ const installed = {};+ for (const key of ['devDependencies', 'dependencies']) {+ for (const [name, version] of Object.entries(section(key))) if (usable(version)) installed[name] = version;+ }+ const missing = [];+ const drift = [];+ const check = (group, expected) => {+ for (const [name, version] of Object.entries(expected)) {+ if (!Object.prototype.hasOwnProperty.call(installed, name)) missing.push(`${group}.${name}=${version}`);+ else if (installed[name] !== version) drift.push(`${name} ${installed[name]} (generated pages expect ${version})`);+ }+ };+ check('dependencies', expectedDependencies);+ check('devDependencies', expectedDevDependencies);+ return { missing, drift };+}++function validateExistingPackageJson(filePath, expectedPkg) {+ let st = null;+ try {+ st = fs.lstatSync(filePath);+ } catch (err) {+ if (err.code === 'ENOENT') return null;+ const e = new Error(`existing package.json could not be inspected (${err.code || err.message})`);+ e.code = 'STALE_MANIFEST';+ throw e;+ }+ if (!st.isFile()) {+ // Not read through, and `--force` is no way out either: writeIfAllowed refuses a non-regular leaf.+ const kind = st.isSymbolicLink() ? 'symbolic link' : st.isDirectory() ? 'directory' : 'special file';+ const e = new Error(`existing package.json is a ${kind}, so its dependencies cannot be verified and it is never written through; replace it with a regular file and rerun`);+ e.code = 'STALE_MANIFEST';+ throw e;+ }++ let existing;+ try {+ // One leading UTF-8 byte-order mark is dropped: Windows PowerShell's `Set-Content -Encoding UTF8` writes+ // one, npm reads such a manifest fine, and JSON.parse refuses it — so a valid package.json halted every+ // rerun. The file itself is left as it is.+ existing = JSON.parse(fs.readFileSync(filePath, 'utf8').replace(/^\uFEFF/, ''));+ } catch (err) {+ const e = new Error(`existing package.json could not be parsed, so its dependencies cannot be verified (${err.message}); fix it or rerun with --force`);+ e.code = 'STALE_MANIFEST';+ throw e;+ }++ const { missing, drift } = comparePackageDependencies(existing, expectedPkg.dependencies, expectedPkg.devDependencies);+ if (missing.length > 0) {+ // Reruns without --force preserve user edits, so reporting success here would leave VS Code and+ // `npm install` with a package that cannot satisfy the feature imports the command just accepted.+ const e = new Error(+ `existing package.json is missing requested generated-page dependencies: ${missing.join(', ')}. ` ++ 'Rerun with --force to regenerate it, or merge these dependencies by hand and rerun.'+ );+ e.code = 'STALE_MANIFEST';+ throw e;+ }+ return { drift };+}+// Static ambient declarations for the genux runtime. Same content for every// working dir — no parameterization.function buildAmbientDeclarations() {@@ -409,7 +484,9 @@ function main() {try {const pkg = buildPackageJson(slug, args.features);const pkgPath = path.join(workingDir, 'package.json');+ const existing = args.force ? null : validateExistingPackageJson(pkgPath, pkg);pkgResult = writeIfAllowed(pkgPath, JSON.stringify(pkg, null, 2) + '\n', args.force, approvedRoot);+ if (existing && existing.drift.length && pkgResult && pkgResult.wrote === false) pkgResult.versionDrift = existing.drift;const dtsPath = path.join(workingDir, 'genpage.d.ts');dtsResult = writeIfAllowed(dtsPath, buildAmbientDeclarations(), args.force, approvedRoot);@@ -436,6 +513,8 @@ module.exports = {parseArgs,buildPackageJson,buildAmbientDeclarations,+ comparePackageDependencies,+ validateExistingPackageJson,// Exported for the output-confinement tests: `--force` must overwrite the file this tool owns,// never whatever a symlink at that name points at.writeIfAllowed,diff --git a/plugins/model-apps/scripts/genpage-plan-provenance.js b/plugins/model-apps/scripts/genpage-plan-provenance.jsnew file mode 100644index 000000000..4fb2936f2--- /dev/null+++ b/plugins/model-apps/scripts/genpage-plan-provenance.js@@ -0,0 +1,328 @@+#!/usr/bin/env node+'use strict';+// Deterministic provenance gate for planner-authored markdown.+//+// WHY this is a script: the orchestrator is an AI workflow and `genpage-plan.md` /+// `genpage-edit-plan.md` may already exist from an earlier run. Checking "file exists" after a+// planner invocation accepts stale approved content if the planner failed to write this time. The+// contract is two-part:+// 1. `prepare` quarantines the old authoritative file BEFORE the planner is re-invoked, so the file+// existing afterwards means this invocation wrote it.+// 2. `verify` proves the written file targets exactly what the approved plan named.+//+// Why not a hash of the whole approved body: the planner hands back a PREVIEW for approval and then+// writes a DIFFERENT document. The preview is+// ## Genpage Plan / ### Pages (N total) / ### Data Strategy … (full prefixed names)+// and the written plan is+// # Genpage Plan / ## User Requirements / … / ## Pages / … / ## Per-Page Specifications (suffixes)+// (agents/genpage-planner.md Steps 5 and 6; the edit planner likewise, Steps 3 and 4). No two such+// documents hash equal, so a hash gate halted every approved run. What both documents DO state is+// what the run will touch — the page files of a create, the page id of an edit — and that is what is+// compared: a stale plan from an earlier run, or one the planner re-derived, targets other pages.++const crypto = require('node:crypto');+const fs = require('node:fs');+const path = require('node:path');+const { pagesTables } = require('./lib/page-file-targets.js');++function sha256(text) {+ return crypto.createHash('sha256').update(String(text), 'utf8').digest('hex');+}++// What a plan document targets.+// create: the Pages table's File column — `## Pages` in the written plan, `### Pages (N total)`+// in the preview.+// edit: the page id — `- **Page ID:** <guid>` in the written edit plan, and+// `- **File:** <guid>/page.tsx` in the preview's `### Current State`.+// Returns { kind, targets } or null when the document names neither.+//+// Both GUID patterns are bounded by `[\w-]` on the side that could run on, exactly as the upload+// parser bounds pac's `Page ID:` (lib/genpage-cli.js parsePageId): an overlong `<guid>deadbeef` was+// truncated to its first 36 characters and certified.+//+// The written edit plan states the id ONCE, structurally, in `## File Being Edited`+// (agents/genpage-edit-planner.md), and only that section is read: the plan also copies the page's+// earlier prompts in full (`## Original Page Context`), and a label quoted there — "(**Page ID:** …)",+// "Show the **Page ID:** in the footer" — blocked every later edit of that page. Within the section every+// label must hold the same well-formed id: a malformed one makes the plan name NOTHING and is never+// rescued by an id found elsewhere, since the edit worker reads that very label.+//+// The approval PREVIEW has no such section. It names its page in its own `- **File:** <guid>/page.tsx`+// line under `### Current State` and quotes the first ~100 characters of the page's prompt a few lines+// later (`- **Original prompt:** …`), so a label read anywhere came out of that quote and decided the+// approved target — the same page halting on every edit, since its first prompt never changes. So a+// preview is read by the File line in its Current State block ALONE: a block whose File line is missing+// or names another file is a broken preview, and reading on found a label or a path quoted from the+// prompt, which approved another page. Only a document with neither section nor block is read by a File+// line anywhere, then by a label that BEGINS a line (under the same rule), and then by any+// `<guid>/page.tsx` path.+const GUID = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';+const LABELLED_ID = new RegExp(`^\`?\\{?(${GUID})\\}?\`?(?![\\w-])`);+function labelledPageIds(text, { lineStart = false } = {}) {+ const label = lineStart ? /^[ \t]*(?:[-*+][ \t]+)?\*\*Page ID:\*\*[ \t]*([^\r\n]*)/gm : /\*\*Page ID:\*\*[ \t]*([^\r\n]*)/g;+ return [...text.matchAll(label)].map((m) => {+ const id = LABELLED_ID.exec(m[1].trim());+ return id ? id[1].toLowerCase() : null;+ });+}+// A path names `page.tsx` only when the name ENDS there: `page\.tsx\b` also took `<guid>/page.tsx.bak`, a+// different file, and since an edit's provenance compares only the GUID, an approval naming it certified a+// written plan for the real page. What goes on naming a file is a letter or digit in any script, one of+// `_ - ~ + # $ @ % & =`, an opening bracket, or a path separator (`page.tsx/old.tsx` is a file in a FOLDER+// of that name) — or a `.` or `:` before one of those (`page.tsx.bak`, the NTFS stream `page.tsx:alt`).+// Anything else ends it: a blank, the end, sentence punctuation, a quote, a dash or a closing mark in any+// script (`”`, `»`, `<br>`). The rule says what CONTINUES a name, not what ends one, because a path the+// fallback cannot end is skipped and the next one in the document wins — which may be a path quoted in the+// page's own prompt.+const NAME_GOES_ON = String.raw`[\p{L}\p{N}_\-~+#$@%&=(\[{/\\]`;+const PAGE_END = `(?!${NAME_GOES_ON}|[.:]+${NAME_GOES_ON})`;+// The File line reads the same way; a note after the path (` (edit)`) is not part of it. The page folder may+// come after a path (`D:\work\edit\<guid>\page.tsx`, `./<guid>/page.tsx`), which a planner writing the+// plan's absolute path beside it can easily carry over: only the GUID is compared, so it changes nothing.+const FILE_LINE = new RegExp(`^[ \\t]*[-*+][ \\t]+\\*\\*File:\\*\\*[ \\t]*\`?(?:[^\\r\\n\`]*[\\\\/])?(${GUID})[\\\\/]page\\.tsx${PAGE_END}`, 'imu');+// The preview's own block, or null when there is none. Its File line is read there only: the preview also+// quotes the page's prompt, and a `- **File:** <other>/page.tsx` bullet in that quote, placed ahead of the+// block, decided the target.+function currentStateBlock(src) {+ const state = /^###[ \t]+Current State[ \t]*$/im.exec(src);+ if (!state) return null;+ const rest = src.slice(state.index + state[0].length);+ const next = /^#{1,3}[ \t]+\S/m.exec(rest);+ return next ? rest.slice(0, next.index) : rest;+}+// `kind` is what the flow says the document is ('create' | 'edit' — see planKindOf), or null to read it from+// the document itself. With a kind, only that kind's target is read. `doc` says which of the two documents+// this is — the approval 'preview' or the 'written' plan — and each is then read by its own authoritative+// part alone; null reads either way, as before.+function planTargets(text, { kind = null, doc = null } = {}) {+ const src = String(text || '');+ if (kind !== 'edit') {+ // A Pages table decides "create" first when the kind is not known: an edit plan has none of its own,+ // while a create plan's per-page `- **File:**` lines could hold a `<guid>/page.tsx` path and be misread+ // as an edit target. Each file is compared in the page-file rule's own spelling, `.` segments dropped:+ // `./overview.tsx` in the preview and `overview.tsx` in the written plan name the same page.+ // Read by the page-file gate's own rule, `## Pages` in the written plan and `### Pages (N total)` in the+ // preview alike. More than one table with a File column names nothing — a Pages table quoted in the+ // requirements used to stand in for the real one (lib/page-file-targets.js pagesSections).+ const { tables, unreadable } = pagesTables(src);+ if (unreadable || tables.length > 1) return null;+ const files = tables[0];+ if (files && files.length) return { kind: 'create', targets: files.map((f) => path.posix.normalize(f.trim())).sort() };+ // A create plan is read by its Pages table alone: without one it names nothing, never a page id its text+ // happens to hold.+ if (kind === 'create') return null;+ }+ // The edit target is the page's GUID: the written plan's `- **Page ID:** <guid>`, or else the GUID+ // folder directly before `page.tsx`, which both the preview's `- **File:** <guid>/page.tsx` and the+ // written plan's `- **Absolute path:** <working-dir>/<guid>/page.tsx` carry.+ //+ // The approval preview names its page in its own Current State block, and nowhere else: its prompt snippet+ // may quote anything — a `## File Being Edited` section included, which, read first, named another page.+ if (doc === 'preview') {+ const state = currentStateBlock(src);+ const file = state === null ? null : FILE_LINE.exec(state);+ return file ? { kind: 'edit', targets: [file[1].toLowerCase()] } : null;+ }+ const section = /^##[ \t]+File Being Edited[ \t]*$/im.exec(src);+ // The written plan names its page in its `## File Being Edited` section, and nowhere else.+ if (doc === 'written' && !section) return null;+ let scope = src;+ if (section) {+ const rest = src.slice(section.index + section[0].length);+ const next = /^#{1,2}[ \t]+\S/m.exec(rest);+ const body = next ? rest.slice(0, next.index) : rest;+ const labels = labelledPageIds(body);+ if (labels.length) return labels.every((id) => id && id === labels[0]) ? { kind: 'edit', targets: [labels[0]] } : null;+ if (doc === 'written') scope = body;+ } else {+ const state = currentStateBlock(src);+ const file = FILE_LINE.exec(state === null ? src : state);+ if (file) return { kind: 'edit', targets: [file[1].toLowerCase()] };+ if (state !== null) return null;+ const [first] = labelledPageIds(src, { lineStart: true });+ if (first !== undefined) return first ? { kind: 'edit', targets: [first] } : null;+ }+ const folder = scope.match(new RegExp(`(?<![\\w-])(${GUID})[\\\\/]page\\.tsx${PAGE_END}`, 'u'));+ if (folder) return { kind: 'edit', targets: [folder[1].toLowerCase()] };+ return null;+}++// What is AT `p` — lstat, not existsSync. existsSync follows a link and answers false for a DANGLING+// one, so a planted link at the plan path read as "no plan here" and stayed in place for the planner+// to write through. null when there is nothing there at all.+function entryAt(p) {+ try { return fs.lstatSync(p); } catch (e) { if (e && e.code === 'ENOENT') return null; throw e; }+}++function uniquePath(basePath) {+ if (!entryAt(basePath)) return basePath;+ const parsed = path.parse(basePath);+ for (let i = 1; i < 1000; i += 1) {+ const candidate = path.join(parsed.dir, `${parsed.name}-${i}${parsed.ext}`);+ if (!entryAt(candidate)) return candidate;+ }+ throw new Error(`could not allocate quarantine path for ${basePath}`);+}++// Both paths this touches are refused when they are links (dangling ones included) or not the kind of+// entry they should be. The planner writes THROUGH a link at the plan path, putting the approved plan+// wherever it points; and mkdir({ recursive }) plus rename both follow a link at `.genpage-provenance`,+// which moved the stale plan outside the working directory. The workflow never creates either link, so+// refusing costs a legitimate run nothing. Every failure is an `ok:false` result, never a throw.+function preparePlanProvenance({ planPath }) {+ if (!planPath) return { ok: false, error: '--plan is required' };+ const absPlanPath = path.resolve(planPath);+ const refuse = (error) => ({ ok: false, action: 'prepare', planPath: absPlanPath, error });+ try {+ // The working directory ITSELF must not be a link — the rule the page-file gate and the manifest+ // generator apply to the same directory. With the plan absent this returned ok at once, and the planner+ // then wrote the plan, and the orchestrator its approval sidecar, wherever a link planted there points.+ // A linked ANCESTOR is still followed, a normal setup (macOS temp dirs sit under a symlinked /var).+ const workingDir = path.dirname(absPlanPath);+ const dir = entryAt(workingDir);+ if (dir && dir.isSymbolicLink()) {+ return refuse(`${workingDir} is a symbolic link or junction — pass the directory it points to as the working directory`);+ }+ // The approval sidecar the skill has the orchestrator write next to the plan+ // (`.approved-genpage-plan.md`, `.approved-genpage-edit-plan.md`) is written IN PLACE after this+ // runs, so a link there — or a hard link, whose other name the write would rewrite — puts the approved+ // body wherever it points. Refused here, before anything is written, like a link at the plan path.+ const sidecarPath = path.join(path.dirname(absPlanPath), `.approved-${path.basename(absPlanPath)}`);+ const sidecar = entryAt(sidecarPath);+ if (sidecar && (!sidecar.isFile() || sidecar.nlink > 1)) {+ return refuse(`${sidecarPath} is not a plain file (a link, junction, hard link or folder) — remove it and re-run; the approved plan would be written through it`);+ }+ const plan = entryAt(absPlanPath);+ if (!plan) return { ok: true, action: 'prepare', planPath: absPlanPath, quarantinedPath: null };+ if (plan.isSymbolicLink()) return refuse(`${absPlanPath} is a symbolic link or junction — remove it and re-run; the planner would write the plan through it`);+ if (!plan.isFile()) return refuse(`${absPlanPath} is not a regular file — remove it and re-run`);+ // A HARD link is a plain file to lstat, yet quarantining it only renames this name: the plan stays+ // reachable through its other names, outside the working directory included — the sidecar rule, here.+ if (plan.nlink > 1) return refuse(`${absPlanPath} is a hard link (${plan.nlink} names for one file) — remove it and re-run`);+ const quarantineDir = path.join(path.dirname(absPlanPath), '.genpage-provenance');+ const quarantine = entryAt(quarantineDir);+ // lstat never reports a link as a directory, so this refuses a link, a junction and a file alike.+ if (quarantine && !quarantine.isDirectory()) {+ return refuse(`${quarantineDir} is not a plain directory (a link, junction or file) — remove it and re-run`);+ }+ if (!quarantine) fs.mkdirSync(quarantineDir);+ const stale = fs.readFileSync(absPlanPath, 'utf8');+ const staleHash = sha256(stale);+ const parsed = path.parse(absPlanPath);+ const quarantinedPath = uniquePath(path.join(quarantineDir, `${parsed.name}.stale-${staleHash.slice(0, 12)}${parsed.ext || '.md'}`));+ fs.renameSync(absPlanPath, quarantinedPath);+ return { ok: true, action: 'prepare', planPath: absPlanPath, quarantinedPath, staleHash };+ } catch (e) {+ return refuse(`could not quarantine the earlier plan: ${e.message}`);+ }+}++// Which kind of plan a path holds is the flow's choice, not the document's: /genpage writes a create plan to+// `genpage-plan.md` and an edit plan to `genpage-edit-plan.md` (skills/genpage/SKILL.md and edit-flow.md), and+// neither the planner nor the maker's text names the file. The document cannot say it reliably: an edit plan+// quotes the page's earlier prompts, and a Pages table quoted there — in the preview's prompt snippet and the+// written plan's `## Original Page Context` alike — read both as the same create, so an edit of ANOTHER page+// was certified. null for any other name, which is then read from the document as before.+function planKindOf(planPath) {+ const name = path.basename(String(planPath || '')).toLowerCase();+ if (name === 'genpage-edit-plan.md') return 'edit';+ if (name === 'genpage-plan.md') return 'create';+ return null;+}++function verifyPlanProvenance({ planPath, approvedPlan }) {+ if (!planPath) return { ok: false, error: '--plan is required' };+ if (approvedPlan == null) return { ok: false, error: '--approved is required' };+ const absPlanPath = path.resolve(planPath);+ const kind = planKindOf(absPlanPath);+ const approved = planTargets(approvedPlan, { kind, doc: 'preview' });+ if (!approved) {+ return {+ ok: false,+ action: 'verify',+ planPath: absPlanPath,+ error: 'the approved plan body names no pages — save the plan body the planner returned for approval (its Pages table, or the Current State file of an edit) as the --approved file',+ };+ }+ // The file this certifies must be the one written in place: a link would have it vouch for a+ // document that lives somewhere else.+ let entry;+ try { entry = entryAt(absPlanPath); } catch (e) {+ return { ok: false, action: 'verify', planPath: absPlanPath, approvedTargets: approved.targets, error: `could not inspect ${absPlanPath}: ${e.message}` };+ }+ if (!entry) {+ return { ok: false, action: 'verify', planPath: absPlanPath, approvedTargets: approved.targets, error: `planner did not write ${absPlanPath}` };+ }+ // lstat reports a link as a link, never as a file, so this refuses links and folders alike — and a hard+ // link, whose other names the planner's write would have rewritten too.+ if (!entry.isFile() || entry.nlink > 1) {+ return { ok: false, action: 'verify', planPath: absPlanPath, approvedTargets: approved.targets, error: `${absPlanPath} is not a plain file (a link, junction, hard link or folder) — the plan must be written in place` };+ }+ let written;+ try { written = fs.readFileSync(absPlanPath, 'utf8'); } catch (e) {+ return { ok: false, action: 'verify', planPath: absPlanPath, approvedTargets: approved.targets, error: `could not read ${absPlanPath}: ${e.message}` };+ }+ // Recorded, not compared: an audit line for workflow-log.md naming the exact file that was verified.+ const writtenHash = sha256(written);+ const actual = planTargets(written, { kind, doc: 'written' });+ const same = actual && actual.kind === approved.kind+ && actual.targets.length === approved.targets.length+ && actual.targets.every((t, i) => t === approved.targets[i]);+ if (!same) {+ return {+ ok: false,+ action: 'verify',+ planPath: absPlanPath,+ approvedTargets: approved.targets,+ writtenTargets: actual ? actual.targets : [],+ writtenHash,+ error: `the written plan targets ${actual ? actual.targets.join(', ') || 'nothing' : 'no pages'}, but the approved plan named ${approved.targets.join(', ')}`,+ };+ }+ return { ok: true, action: 'verify', planPath: absPlanPath, kind: approved.kind, targets: approved.targets, writtenHash };+}++function parseArgv(argv) {+ const out = { command: argv[0] || '' };+ for (let i = 1; i < argv.length; i += 1) {+ const key = argv[i];+ if (!key.startsWith('--')) continue;+ out[key.slice(2)] = argv[i + 1];+ i += 1;+ }+ return out;+}++// The approved body comes from a file the orchestrator wrote. It must be that file, written in place — a+// link would have the gate compare against whatever it points at.+function readApproved(value) {+ if (!(value && value.startsWith('@'))) return value;+ const file = path.resolve(value.slice(1));+ if (!fs.lstatSync(file).isFile()) throw new Error(`${file} is not a regular file (a link, junction or folder) — the approved plan must be written in place`);+ return fs.readFileSync(file, 'utf8');+}++function main() {+ const args = parseArgv(process.argv.slice(2));+ let result;+ if (args.command === 'prepare') {+ result = preparePlanProvenance({ planPath: args.plan });+ } else if (args.command === 'verify') {+ let approvedPlan;+ try {+ approvedPlan = readApproved(args.approved);+ result = verifyPlanProvenance({ planPath: args.plan, approvedPlan });+ } catch (e) {+ result = { ok: false, action: 'verify', error: `could not read the approved plan: ${e.message}` };+ }+ } else {+ result = { ok: false, error: 'Usage: node genpage-plan-provenance.js prepare --plan <path> OR verify --plan <path> --approved @<approved-plan-file>' };+ }++ process.stdout.write(JSON.stringify(result) + '\n');+ process.exit(result.ok ? 0 : (args.command === 'prepare' || args.command === 'verify' ? 3 : 1));+}++if (require.main === module) main();++module.exports = { preparePlanProvenance, verifyPlanProvenance, planTargets, sha256 };diff --git a/plugins/model-apps/scripts/genpage-upload.js b/plugins/model-apps/scripts/genpage-upload.jsindex 16ef121aa..d1a24ad5d 100644--- a/plugins/model-apps/scripts/genpage-upload.js+++ b/plugins/model-apps/scripts/genpage-upload.js@@ -33,7 +33,7 @@ const os = require('node:os');const { parseArgs, validateFlags, emitResult } = require('./lib/dataverse-auth.js');const { makeGenpageCli, suppliedButBlank } = require('./lib/genpage-cli.js');-const KNOWN = ['env', 'app-id', 'code-file', 'compiled-code-file', 'page-id', 'name',+const KNOWN = ['env', 'app-id', 'code-file', 'compiled-code-file', 'page-id', 'name', 'name-file','data-sources', 'clear-data-sources', 'prompt', 'prompt-file', 'agent-message', 'agent-message-file','model', 'connectors', 'actions', 'add-to-sitemap'];// Bare switches; every other flag carries a value.@@ -41,10 +41,32 @@ const SWITCHES = ['add-to-sitemap', 'clear-data-sources'];const NEED_VALUE = KNOWN.filter((f) => !SWITCHES.includes(f));const USAGE = 'Usage: node scripts/genpage-upload.js --env <orgUrl> --app-id <guid> --code-file <path> '- + '--prompt-file <path> --agent-message-file <path> [--page-id <guid>] [--name <text>] '+ + '--prompt-file <path> --agent-message-file <path> [--page-id <guid>] [--name-file <path> | --name <text>] '+ '[--data-sources <csv>] [--clear-data-sources] [--compiled-code-file <path>] [--model <id>] '+ '[--connectors <path>] [--actions <path>] [--add-to-sitemap]';+// The skill writes these inputs — the prompt, agent-message and page-name files, connectors.json, actions.json —+// into the working directory just before the upload, and a write through a link left at one of those names (a+// symbolic link, a junction, or a hard link whose other name lives elsewhere) rewrites the file it points to,+// outside the working directory included. The skill checks each name before it writes (SKILL.md Phase 6); this is+// the check that holds when that step was skipped: the upload stops, and says the linked file may have been+// changed. Returns null for a plain file, and for a path that is not there (the read or pac reports that).+//+// Scope: both checks close a link left in the folder BEFORE the run, such as one shipped in a cloned repository. A+// process racing the skill to plant one between its check and its write is out of their reach. Such a process+// already holds the user's rights over the whole working directory (its pages, plan and manifest), and no check+// inside the skill can stop it.+function notPlainFile(abs) {+ let st;+ try { st = fs.lstatSync(abs); } catch (e) {+ return e && e.code === 'ENOENT' ? null : `${abs} could not be inspected (${(e && e.code) || e})`;+ }+ if (st.isFile() && st.nlink <= 1) return null;+ if (st.isSymbolicLink()) return `${abs} is a symbolic link or junction, not a file written in place — writing it may have changed the file it points to; check that file, remove the link and re-run`;+ if (st.isFile()) return `${abs} is a hard link (${st.nlink} names for one file), not a file written in place — writing it changed its other names too; check them, remove this one and re-run`;+ return `${abs} is not a plain file (a folder or a special file) — remove it and re-run`;+}+// Resolve one text input that may arrive inline or by file. Returns { ok, value } or { ok:false,// error }. Supplying BOTH is rejected rather than silently preferring one: the two would be// different text, and quietly picking either means deploying a prompt the caller did not intend.@@ -71,6 +93,8 @@ function resolveText(flags, inlineFlag, fileFlag, readFile) {// /app-builder wrapper path preserves a final newline, so stripping one here made the same text// deploy differently depending on which path carried it. A prompt that legitimately ends with a// newline (a downloaded transcript, a heredoc) keeps it.+ const linked = notPlainFile(path.resolve(file));+ if (linked) return { ok: false, error: `--${fileFlag} ${linked}` };try {return {ok: true,@@ -102,6 +126,13 @@ async function main(argv = process.argv.slice(2), deps = {}) {if (!prompt.ok) return emit(false, { error: prompt.error });const agentMessage = resolveText(flags, 'agent-message', 'agent-message-file', readFile);if (!agentMessage.ok) return emit(false, { error: agentMessage.error });+ // The page's display name travels by file too. It is the maker's text as well, and the skill substituted it+ // into `--name "<name>"`: PowerShell expanded `$(…)` in it before this script ran — a name could run a+ // command — and `Revenue $100` arrived as `Revenue `. By file it is never command text, and keeps every+ // character. Its trailing line break, which an editor adds, is not part of the name.+ const pageName = resolveText(flags, 'name', 'name-file', readFile);+ if (!pageName.ok) return emit(false, { error: pageName.error });+ if (typeof flags['name-file'] === 'string' && pageName.value !== undefined) pageName.value = pageName.value.replace(/(?:\r?\n)+$/, '');// An EMPTY prompt or agent-message is refused rather than defaulted. `upload()` substitutes// `Generative page <name>` for a blank prompt and `Authored by app-builder` for a blank agent@@ -112,6 +143,7 @@ async function main(argv = process.argv.slice(2), deps = {}) {for (const [label, inlineFlag, fileFlag, resolved] of [['prompt', 'prompt', 'prompt-file', prompt],['agent message', 'agent-message', 'agent-message-file', agentMessage],+ ['page name', 'name', 'name-file', pageName],]) {const given = typeof flags[inlineFlag] === 'string' || typeof flags[fileFlag] === 'string';if (given && suppliedButBlank(resolved.value === undefined ? '' : resolved.value)) {@@ -145,6 +177,12 @@ async function main(argv = process.argv.slice(2), deps = {}) {});}+ // pac reads these two itself; they are checked here for the same reason as the text files (notPlainFile).+ for (const flag of ['connectors', 'actions']) {+ const linked = typeof flags[flag] === 'string' && flags[flag] ? notPlainFile(path.resolve(flags[flag])) : null;+ if (linked) return emit(false, { error: `--${flag} ${linked}` });+ }+const cli = cliFactory(flags.env);// An UPDATE must have a target that EXISTS. pac treats an unknown `--page-id` as a CREATE and@@ -253,7 +291,7 @@ async function main(argv = process.argv.slice(2), deps = {}) {pageId: flags['page-id'] || undefined,codeFile: flags['code-file'],compiledCodeFile: flags['compiled-code-file'] || undefined,- name: flags.name || undefined,+ name: pageName.value || undefined,prompt: prompt.value,agentMessage: agentMessage.value,// Passed through as the CSV the caller typed; upload() normalizes array-or-string. When the@@ -296,4 +334,4 @@ if (require.main === module) {process.exit(1);});}-module.exports = { main, resolveText };+module.exports = { main, resolveText, notPlainFile };diff --git a/plugins/model-apps/scripts/genpage-worker-output.js b/plugins/model-apps/scripts/genpage-worker-output.jsnew file mode 100644index 000000000..18c33317d--- /dev/null+++ b/plugins/model-apps/scripts/genpage-worker-output.js@@ -0,0 +1,162 @@+#!/usr/bin/env node+'use strict';+// Validate page-builder worker output before the orchestrator accepts it.+//+// A partially written `.tsx` can still contain the token `export default`, so existence plus a token+// scan is not enough. This script reuses the dependency-free TSX lexer that already protects+// promote-intent-pages.js, giving the AI orchestration an executable yes/no gate before it decides+// whether to run the inline fallback.++const fs = require('node:fs');+const path = require('node:path');+const crypto = require('node:crypto');+const { blankLiterals, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets } = require('./lib/source-literals.js');++// A worker that returns without writing leaves whatever was at its path before, and a complete page an+// earlier attempt left there passes every content check: the stale page was deployed instead of taking+// the inline fallback. So the orchestrator STAMPS each target right before it dispatches the page+// (`--stamp`), and the check refuses a file exactly as it was stamped — same size, modification time and+// content. Any write moves the modification time, so a page rewritten with identical bytes still counts+// as written. The stamp is a sidecar beside the page, `.<name>.dispatch-stamp.json`; a check that finds the+// page changed consumes it, and one that finds it unchanged keeps it, so a retry is refused the same way. A+// check with no stamp checks the content alone.+const STAMP_SUFFIX = '.dispatch-stamp.json';+const stampPathFor = (abs) => path.join(path.dirname(abs), `.${path.basename(abs)}${STAMP_SUFFIX}`);+const sha256 = (buf) => crypto.createHash('sha256').update(buf).digest('hex');++function stampPageTarget({ filePath }) {+ if (!filePath) return { ok: false, action: 'stamp', problems: ['--file is required'] };+ const abs = path.resolve(filePath);+ const fail = (problem) => ({ ok: false, action: 'stamp', filePath: abs, problems: [problem] });+ try {+ // A page whose folder does not exist yet cannot be stale — nothing is there to be left behind — so there+ // is nothing to stamp, and the folder is not created for it: a page never written is caught without one.+ try { fs.lstatSync(path.dirname(abs)); } catch (e) {+ if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return { ok: true, action: 'stamp', filePath: abs, existed: false };+ throw e;+ }+ // The sidecar is written in place, so a link there would put it wherever it points — and a folder or+ // a hard link is not the sidecar this wrote. The page path itself was checked by check-page-files.js.+ const sidecar = stampPathFor(abs);+ let side = null;+ try { side = fs.lstatSync(sidecar); } catch (e) { if (!(e && e.code === 'ENOENT')) throw e; }+ if (side && (!side.isFile() || side.nlink > 1)) return fail(`${sidecar} is not a plain file (a link, junction, hard link or folder); remove it and re-run`);+ let state = { existed: false };+ let entry = null;+ try { entry = fs.lstatSync(abs); } catch (e) { if (!(e && e.code === 'ENOENT')) throw e; }+ if (entry) {+ if (!entry.isFile()) return fail('is not a regular file');+ state = { existed: true, size: entry.size, mtimeMs: entry.mtimeMs, sha256: sha256(fs.readFileSync(abs)) };+ }+ fs.writeFileSync(sidecar, JSON.stringify({ filePath: abs, ...state }));+ return { ok: true, action: 'stamp', filePath: abs, existed: state.existed };+ } catch (e) {+ return fail(`could not stamp the page (${(e && e.code) || e})`);+ }+}++// The stamp for `abs`, or null when there is none. A stamp that cannot be read fails closed — the check can+// no longer tell this run's write from what was there before. Reading never removes it: only a page found+// CHANGED consumes its stamp (consumeStamp). Consuming it on a failed check let the very next check — the+// retry the skill prescribes, or the same command run again — see no stamp and pass the stale page.+function readStamp(abs) {+ const sidecar = stampPathFor(abs);+ let side;+ try { side = fs.lstatSync(sidecar); } catch (e) {+ if (e && e.code === 'ENOENT') return null;+ return { unreadable: `could not be inspected (${(e && e.code) || e})` };+ }+ try {+ if (!side.isFile() || side.nlink > 1) return { unreadable: 'is not a plain file' };+ const stamp = JSON.parse(fs.readFileSync(sidecar, 'utf8'));+ // Trusted only whole, and only for THIS page. A truncated sidecar (`{"existed":true}`) left every field+ // the check compares undefined, so an unchanged page matched nothing and was accepted, the stamp consumed+ // with it; and a stamp copied from another page compared that page's state.+ const whole = !!stamp && typeof stamp.existed === 'boolean' && typeof stamp.filePath === 'string'+ && (!stamp.existed || (Number.isFinite(stamp.size) && Number.isFinite(stamp.mtimeMs) && /^[0-9a-f]{64}$/.test(String(stamp.sha256))));+ if (!whole) return { unreadable: 'is not a dispatch stamp' };+ // The path as stampPageTarget recorded it (path.resolve). Windows compares names ignoring case.+ const same = (a, b) => (process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b);+ if (!same(path.resolve(stamp.filePath), abs)) return { unreadable: 'belongs to another page' };+ return stamp;+ } catch (e) {+ return { unreadable: `could not be read (${(e && e.code) || (e && e.message) || e})` };+ }+}+function consumeStamp(abs) {+ try { fs.rmSync(stampPathFor(abs), { force: true }); } catch { /* best-effort: the next --stamp overwrites it */ }+}++function structuralProblems(code) {+ const text = String(code || '');+ const problems = [];+ if (!text.trim()) return ['file is empty'];+ // hasDefaultExport also refuses a file cut off INSIDE its export (`export default function P(props)`+ // with no body), so say so: the one inline rewrite should write the whole page, not add an export.+ if (!hasDefaultExport(text)) problems.push('no complete default export — missing, or the file ends inside it');+ if (hasUnbalancedBrackets(text)) problems.push('unbalanced brackets — output looks truncated');+ // A cut that leaves every bracket balanced: inside JSX, a template or a comment, or after `a +`.+ if (endsMidStatement(text)) problems.push('stops mid-statement — output looks truncated');+ // On the blanked source, so a fence inside a template literal (a page rendering markdown help) is+ // data; a fence wrapping the file — the model answered in markdown — is code-position text.+ if (/^\s*(```|~~~)/m.test(blankLiterals(text))) problems.push('contains a markdown code fence');+ const elision = findElisionMarker(text);+ if (elision) problems.push(`contains ${elision}`);+ return problems;+}++// Every outcome is a result, never a throw: `ok:false` is what sends the orchestrator to its one inline+// rewrite, and a folder or an unreadable file at the page path used to throw out of readFileSync — an+// uncaught CLI failure instead of that recovery. lstat, not existsSync, so a link there (dangling ones+// included) is reported as what it is: not a page written in place — the dispatch gate+// (check-page-files.js) refuses a link at a page path before any worker runs.+function validatePageOutput({ filePath }) {+ if (!filePath) return { ok: false, filePath, problems: ['--file is required'] };+ const abs = path.resolve(filePath);+ const fail = (problem) => ({ ok: false, filePath: abs, problems: [problem] });+ let entry;+ try { entry = fs.lstatSync(abs); } catch (e) {+ return fail(e && e.code === 'ENOENT' ? 'file was never written' : `file could not be inspected (${(e && e.code) || e})`);+ }+ const stamp = readStamp(abs);+ if (stamp && stamp.unreadable) {+ // A link or hard link there is refused by --stamp too, so re-stamping cannot clear it: say what does.+ const remedy = /plain file/.test(stamp.unreadable) ? 'remove it and re-run' : 'stamp the page again before its next write';+ return fail(`the dispatch stamp ${stamp.unreadable}; ${remedy}`);+ }+ if (entry.isSymbolicLink()) return fail('is a symbolic link or junction, not a page file written in place');+ if (!entry.isFile()) return fail('is not a regular file');+ let bytes;+ try { bytes = fs.readFileSync(abs); } catch (e) { return fail(`file could not be read (${(e && e.code) || e})`); }+ if (stamp && stamp.existed && stamp.size === entry.size && stamp.mtimeMs === entry.mtimeMs && stamp.sha256 === sha256(bytes)) {+ return fail('file is unchanged since the page was dispatched — the worker did not write it');+ }+ // Written since the stamp (or no stamp at all): the stamp has done its job.+ if (stamp) consumeStamp(abs);+ const problems = structuralProblems(bytes.toString('utf8'));+ return { ok: problems.length === 0, filePath: abs, problems };+}++function parseArgv(argv) {+ const out = {};+ for (let i = 0; i < argv.length; i += 1) {+ if (argv[i] === '--file') {+ out.filePath = argv[i + 1];+ i += 1;+ } else if (argv[i] === '--stamp') {+ out.stamp = true;+ }+ }+ return out;+}++function main() {+ const args = parseArgv(process.argv.slice(2));+ const result = args.stamp ? stampPageTarget(args) : validatePageOutput(args);+ process.stdout.write(JSON.stringify(result) + '\n');+ process.exit(result.ok ? 0 : 3);+}++if (require.main === module) main();++module.exports = { validatePageOutput, stampPageTarget, structuralProblems, STAMP_SUFFIX };diff --git a/plugins/model-apps/scripts/lib/page-file-targets.js b/plugins/model-apps/scripts/lib/page-file-targets.jsnew file mode 100644index 000000000..945945822--- /dev/null+++ b/plugins/model-apps/scripts/lib/page-file-targets.js@@ -0,0 +1,380 @@+'use strict';+// Where a generated page may be written — ONE rule for every place a page filename is accepted:+// - /genpage, before it dispatches parallel page workers (scripts/check-page-files.js)+// - /app-builder, when it projects an App Spec into a page plan (lib/page-plan.js)+// - the Layer 1 plan validator the genpage evals run (evals/model-apps/genpage/lib)+// The names come from a plan an AI planner wrote, and workers then write to them unattended, so an+// unsafe name is a write outside the working directory, and two names one filesystem stores as the+// same file are two workers silently overwriting each other. Two copies of this rule had already+// drifted — one checked realpaths, the other did not — so there is only this one.+//+// Raw shapes refused, each as a separate problem code:+// C:\pages\a.tsx /tmp/a.tsx C:a.tsx absolute (either platform's form is refused on every+// platform; `C:a.tsx` is drive-relative, still anywhere)+// pages\a.tsx backslash (a separator on Windows, a filename character elsewhere:+// the same plan would write different files per OS)+// ../outside.tsx x/../../a.tsx traversal (`..` segments; a lone `.` cannot climb and is allowed)+// CON.tsx page:alt.tsx x./a.tsx unportable (a Windows device name, a reserved character — `:` writes+// an NTFS alternate stream — or a trailing dot or space)+// $(x).tsx a;b.tsx my page.tsx shell (a character a shell expands or splits on — the skill's commands+// put page paths in double quotes, some in none; only letters+// and digits of any script, `.`, `-` and `_` are accepted)+// package.json RuntimeTypes.ts extension (every Pages File is a page `.tsx` — references/plan-schema.md;+// any other name is some other file of the working+// directory, which a worker would overwrite with a page)+// a.tsx → anywhere link (the target itself is a symbolic link or junction —+// dangling or not, inside the directory or out: a worker+// writes through it, so `page.tsx → package.json` puts a+// page into package.json — or a HARD link, a plain file+// to lstat whose other names a write rewrites too)+// linked/a.tsx realpath-escape (a parent that resolves through a link or junction+// to outside the directory)+// dead/a.tsx unresolvable (a parent that cannot be resolved — a dangling or looping+// link. existsSync calls a dangling link absent, so the walk+// used to step past it to the in-directory folder above.+// Also any disk error other than "not there": EACCES/EIO+// are refused, never read as absence)+// a.tsx (a folder) not-a-file (the target exists but is not a regular file)+// Page.tsx + page.tsx collision (case-insensitive filesystems store them as one file —+// two names of the plan, or a name whose folder or file is+// ALREADY on disk under another spelling, which the worker+// would write into or over; also two names that reach one+// file through a link or junction inside the directory)++const fs = require('node:fs');+const path = require('node:path');++// The name a case-insensitive filesystem stores: NFC first, so a precomposed and a decomposed spelling+// of one name are one identity too.+const identityOf = (name) => name.normalize('NFC').toLowerCase();++// "Nothing there" is only ever ENOENT, or ENOTDIR (a parent is a file, so nothing can be below it). Any+// other error — EACCES, EPERM, EIO — is not an answer: it propagates, and the file is refused as+// `unresolvable`, rather than "could not look" being read as "nothing there" and waved through.+const isAbsent = (e) => !!e && (e.code === 'ENOENT' || e.code === 'ENOTDIR');++function entryAt(p) {+ try { return fs.lstatSync(p); } catch (e) { if (isAbsent(e)) return null; throw e; }+}++// Windows cannot store these as a file or folder name — a device name (with any extension), a reserved+// character, or a trailing dot or space — and `:` is worse than refused: `page:alt.tsx` writes an NTFS+// alternate data stream `alt.tsx` on a file `page`, so the page lands where no one looks. Checked on+// every platform, for the same reason as backslashes: one plan must mean the same files everywhere.+// See: https://learn.microsoft.com/windows/win32/fileio/naming-a-file#naming-conventions+const WINDOWS_DEVICE = /^(?:con|prn|aux|nul|com[0-9\u00b9\u00b2\u00b3]|lpt[0-9\u00b9\u00b2\u00b3])(?:\..*)?$/i;+// [what the segment has, why that is refused], or null.+function unportableSegment(segment) {+ const unstorable = 'which Windows cannot store as a file name';+ if (/[<>:"|?*\u0000-\u001f]/.test(segment)) return ['a character Windows reserves', unstorable];+ if (/[. ]$/.test(segment)) return ['a trailing dot or space', unstorable];+ if (WINDOWS_DEVICE.test(segment)) return ['a Windows device name', unstorable];+ // An 8.3 short-name form. On a drive that keeps short names (the system drive, by default)+ // `REPORT~1.TSX` can BE `report-dashboard-a.tsx`, so two planned pages would be one file — and whether+ // they are depends on which was written first. No page name needs one. Windows stores the name fine;+ // the problem is what it can refer to.+ if (/~\d/.test(segment)) return ['a Windows short-name form (`~1`)', 'which on Windows can be the short name of another file'];+ return null;+}++// A character of a page file name that a shell leaves alone. The skill's commands put page paths in double+// quotes (`--file "<working-dir>/<file>"`) and some in none (`--code-file <working-dir>/<file>.tsx`), and the+// orchestrator substitutes the name as text: `$(Join-Path .. outside).tsx` passed every other rule, and+// PowerShell expanded it inside the quotes, so the dispatch stamp was written outside the working directory; a+// `;` or a space in an unquoted argument ends it, and the rest runs as another command. A page name needs none of+// that, so only letters and digits (any script, with their combining marks), `.`, `-` and `_` are accepted.+// PowerShell also reads the typographic quotes and dashes as syntax; they are punctuation, not letters.+const SHELL_SAFE = /[\p{L}\p{N}\p{M}._-]/u;++// The first component on the way to a target — a folder or the file itself — that is ALREADY on disk+// under another spelling of the same name (case, or Unicode normalization), as its relative path, or+// null. A case-insensitive filesystem stores the two as one, so `pages/Home.tsx` writes into an existing+// `Pages/` or over an existing `pages/home.tsx`; a case-sensitive one makes a second file or tree beside+// it. Either way the plan does not mean what it says, so it is refused at any level. The identical+// spelling all the way down is that very page, which a re-run rewrites. Listings are cached per folder.+function differentlySpelledOnDisk(root, segments, listings) {+ let dir = root;+ for (let i = 0; i < segments.length; i++) {+ if (!listings.has(dir)) {+ let names = null;+ try { names = fs.readdirSync(dir); } catch (e) { if (!isAbsent(e)) throw e; }+ listings.set(dir, names);+ }+ const names = listings.get(dir);+ if (!names) return null; // this folder is not there yet, so nothing below it can collide+ const hit = names.find((n) => n !== segments[i] && identityOf(n) === identityOf(segments[i]));+ if (hit) return [...segments.slice(0, i), hit].join('/');+ // Not there under any spelling: the next listing fails with ENOENT and ends the walk.+ dir = path.join(dir, segments[i]);+ }+ return null;+}++/**+ * Every problem with `files` as write targets inside `workingDir`, in input order. The link, realpath+ * and existing-file checks run only when `workingDir` is given and exists (a plan projected before its+ * directory exists, or a synthetic eval plan, still gets every lexical check).+ *+ * `built` lists pages ALREADY built, which no worker writes (/app-builder's implemented pages). They are+ * checked first, by the lexical safety rules and for collisions — a new page is never written over one,+ * and two of them colliding is still reported — but not by the write-target rules (the `.tsx` extension,+ * links, the existing-file listing), which guard a file about to be written: HEAD built a plan for an+ * implemented `codeFile` the spec gate accepts, such as `pages/home.jsx`.+ * @param {string[]} files+ * @param {{ workingDir?: string, built?: string[] }} [opts]+ * @returns {{ file: string, code: string, message: string }[]}+ */+function pageFileProblems(files, opts = {}) {+ const problems = [];+ const add = (file, code, message) => problems.push({ file, code, message });+ const root = opts.workingDir ? path.resolve(opts.workingDir) : null;+ let rootReal = null;+ let rootError = null;+ let rootLink = false;+ if (root) {+ // A working directory that does not exist yet leaves only the lexical checks (see above). One that+ // exists but cannot be resolved is not "nothing to check": every written file is refused.+ // The working directory ITSELF must not be a link, the rule generate-page-manifest.js applies to the+ // same directory: `mkdir -p` succeeds silently on a link already at that path, so one planted there+ // redirected every page a worker wrote, and each target resolved inside its realpath and passed. A+ // linked ANCESTOR is still followed — a normal setup (macOS temp dirs sit under a symlinked /var).+ // It is inspected with lstat FIRST, apart from realpath: a DANGLING link there has no realpath+ // (ENOENT), and reading that as "not created yet" left only the lexical checks, so a worker's+ // `mkdir -p` then created the directory through the link.+ let at = null;+ try { at = fs.lstatSync(root); } catch (e) { if (!(e && e.code === 'ENOENT')) rootError = e; }+ rootLink = !!at && at.isSymbolicLink();+ if (at && !rootLink) {+ try { rootReal = fs.realpathSync.native(root); } catch (e) { rootError = e; }+ }+ }+ const seen = new Map();+ // The same file reached under two names — through a link or junction INSIDE the working directory+ // (`alias -> sub` makes `alias/a.tsx` and `sub/a.tsx` one file) — keyed by where it really resolves.+ const seenReal = new Map();+ const listings = new Map();+ // The checks that read the disk. Returns true when it added a problem.+ const onDisk = (file) => {+ const target = path.resolve(root, file);+ const at = entryAt(target);+ if (at && at.isSymbolicLink()) {+ add(file, 'link', `"${file}" is a symbolic link or junction; a worker would write through it to another file`);+ return true;+ }+ if (at && !at.isFile()) {+ add(file, 'not-a-file', `"${file}" already exists and is not a regular file (a folder or a device); a worker cannot write a page there`);+ return true;+ }+ // A HARD link is a plain file to lstat — no link bit, no realpath redirect — yet writing it rewrites+ // every other name of the same file, outside the working directory included. A page this workflow+ // wrote has exactly one name.+ if (at && at.nlink > 1) {+ add(file, 'link', `"${file}" is a hard link (${at.nlink} names for one file); a worker writing it would change the other names too`);+ return true;+ }+ // The target usually does not exist yet (a worker has not written it), so resolve the nearest+ // existing ancestor: that is where a link can redirect a lexically contained path. "Existing" is+ // lstat's answer, so a dangling link on the way stops the walk instead of being stepped past.+ let probe = target;+ while (!entryAt(probe) && path.dirname(probe) !== probe) probe = path.dirname(probe);+ let real;+ try { real = fs.realpathSync.native(probe); } catch (e) {+ add(file, 'unresolvable', `"${file}" passes through a link that cannot be resolved (${(e && e.code) || e}); remove it`);+ return true;+ }+ const rel = path.relative(rootReal, real);+ if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {+ add(file, 'realpath-escape', `"${file}" resolves through a link or junction to outside the working directory`);+ return true;+ }+ const existing = differentlySpelledOnDisk(root, file.split('/').filter((s) => s && s !== '.'), listings);+ if (existing) {+ add(file, 'collision', `"${file}" and the existing "${existing}" collide on a case-insensitive filesystem`);+ return true;+ }+ const resolved = identityOf(path.join(real, path.relative(probe, target)));+ const alias = seenReal.get(resolved);+ if (alias !== undefined) {+ // Two spellings of one name (`Page.tsx` / `page.tsx`) land here too — before the plain name check+ // below — and are reported as what they are; only names that differ otherwise went through a link.+ const why = identityOf(path.posix.normalize(alias)) === identityOf(path.posix.normalize(file))+ ? 'collide on a case-insensitive filesystem'+ : 'are the same file, reached through a link or junction';+ add(file, 'collision', `"${alias}" and "${file}" ${why}`);+ return true;+ }+ seenReal.set(resolved, file);+ return false;+ };+ const check = (raw, written) => {+ const file = String(raw == null ? '' : raw).trim();+ if (!file) { add(file, 'empty', 'a page has an empty file name'); return; }+ if (path.win32.isAbsolute(file) || path.posix.isAbsolute(file) || /^[A-Za-z]:/.test(file)) {+ // `C:page.tsx` is DRIVE-relative, not absolute to path.win32.isAbsolute, yet on Windows it+ // resolves against that drive's current directory — anywhere on the machine.+ add(file, 'absolute', `"${file}" is an absolute path; page files are relative to the working directory`);+ return;+ }+ if (file.includes('\\')) {+ add(file, 'backslash', `"${file}" uses a backslash separator; use forward-slash relative paths only`);+ return;+ }+ // Only `..` can climb out; a lone `.` segment (`./overview.tsx`) cannot, and refusing it would force+ // a full re-plan over a harmless spelling. Its identity is normalized below, so `./a.tsx` and+ // `a.tsx` still collide.+ if (file.split('/').some((segment) => segment === '..')) {+ add(file, 'traversal', `"${file}" contains a ".." traversal segment`);+ return;+ }+ if (written) {+ for (const segment of file.split('/')) {+ const why = segment && segment !== '.' ? unportableSegment(segment) : null;+ if (why) {+ add(file, 'unportable', `"${file}" has ${why[0]} in "${segment}", ${why[1]}`);+ return;+ }+ }+ for (const segment of file.split('/')) {+ const ch = segment && segment !== '.' ? [...segment].find((c) => !SHELL_SAFE.test(c)) : undefined;+ if (ch !== undefined) {+ add(file, 'shell', `"${file}" has ${ch === ' ' ? 'a space' : `"${ch}"`} in "${segment}", which a shell command line would expand or split on; page file names use letters, digits, ".", "-" and "_" only`);+ return;+ }+ }+ if (!/[^/]\.tsx$/i.test(file)) {+ add(file, 'extension', `"${file}" is not a .tsx page file; the plan's File column names pages only`);+ return;+ }+ if (rootError) {+ add(file, 'unresolvable', `"${file}" cannot be checked: the working directory cannot be resolved (${rootError.code || rootError.message})`);+ return;+ }+ if (rootLink) {+ add(file, 'link', `"${file}" would be written through the working directory, which is itself a symbolic link or junction; pass the directory it points to`);+ return;+ }+ if (rootReal) {+ try {+ if (onDisk(file)) return;+ } catch (e) {+ add(file, 'unresolvable', `"${file}" cannot be checked on disk (${(e && e.code) || e}); fix its folder's permissions or pick another name`);+ return;+ }+ }+ }+ const identity = identityOf(path.posix.normalize(file));+ const prior = seen.get(identity);+ if (prior !== undefined) {+ add(file, 'collision', `"${prior}" and "${file}" collide on a case-insensitive filesystem`);+ return;+ }+ seen.set(identity, file);+ // A built page is not refused for its disk state — no worker writes it — but it is still a file a new+ // page must not reach through a link or junction: `alias/a.tsx`, with `alias -> sub`, IS `sub/a.tsx`,+ // and without its real path on record a worker writing `sub/a.tsx` overwrote the built page.+ if (!written && rootReal && !rootError) {+ try {+ const target = path.resolve(root, file);+ let probe = target;+ while (!entryAt(probe) && path.dirname(probe) !== probe) probe = path.dirname(probe);+ const resolved = identityOf(path.join(fs.realpathSync.native(probe), path.relative(probe, target)));+ if (!seenReal.has(resolved)) seenReal.set(resolved, file);+ } catch { /* unresolvable: it simply cannot be matched through a link */ }+ }+ };+ for (const raw of opts.built || []) check(raw, false);+ for (const raw of files || []) check(raw, true);+ return problems;+}++/**+ * The File column of a plan's Pages table, in order. A genpage plan (references/plan-schema.md) has:+ * ## Pages+ * | Page | File | Purpose | Entities |+ * |------|------|---------|----------|+ * | Overview | overview.tsx | Summary cards | account |+ * and the preview the planner hands back for approval has the same table under `### Pages (N total)`, so+ * both headings are read. Returns null when the plan has no Pages table with a File column — a+ * malformed plan, which the caller must refuse, not read as "no pages" — more than one, or rows in a Pages+ * section that are not its File table's rows (see pagesTables).+ * @param {string} plan+ * @param {{ heading?: RegExp }} [opts]+ * @returns {string[]|null}+ */+function pageFilesFromPlan(plan, opts = {}) {+ const { tables, unreadable } = pagesTables(plan, opts);+ return !unreadable && tables.length === 1 ? tables[0] : null;+}++/**+ * Every Pages TABLE of a plan. Under each `##` or `###` heading that begins with the word Pages (or the line+ * `opts.heading` matches), up to the next heading of any level, every header row followed by its delimiter+ * row starts a table, whose rows run to the next such header or the end of the section — a blank line inside+ * one does not end it. Returns { tables, unreadable }: the File column of every table that has one, in order,+ * and whether a section that names files also holds a `|` row that is not one of its File tables' rows, whose+ * files therefore cannot be read: that plan is unreadable, refused rather than the row dropped. Such a row is+ * - one ahead of the section's first header;+ * - a row of a table with no File column beside the File table — a page row turns into a "header" when a+ * delimiter row follows it, and its page vanished from both gates:+ * | Page | File | Purpose |+ * |---|---|---|+ * | A | approved.tsx | Overview |+ * | B | ../outside.tsx | Details | <- read as the header of a second table, which has no File column+ * |---|---|---|+ * - a delimiter row among a table's own rows (a second one under its header).+ * A table with more than one File column is unreadable too: which one names the page is a guess. A row is any+ * line with an unescaped `|` — Markdown makes a table's outer pipes optional, and a row written without its+ * leading one (`B | ../outside.tsx | Details |`) is still a row to a reader, so it is read or refused like any+ * other. An escaped pipe (`\|`) inside a cell is not a column boundary.+ *+ * A section is not judged by its first table: a `| Page | Purpose |` table ahead of the `| Page | File |` one+ * hid it, and a Pages table quoted elsewhere then passed as the plan's only one.+ *+ * Two tables with a File column are AMBIGUOUS, and pageFilesFromPlan refuses them rather than read the+ * first: the plan's `## User Requirements` is the maker's text, verbatim, ahead of `## Pages`, so a Pages+ * table quoted there — under either heading, since a preview can be quoted as easily as a plan — decided the+ * files the gate checked while the workers wrote the real table's. Choosing+ * one by its place in the plan would not help — the orchestrator reading the plan is an AI, and could take+ * the other — so only a plan with one such table says which files the pages are. A heading and its rows count+ * however they are marked: inside a code fence (skipping fenced lines let a fence left open swallow the real+ * section, and the example stand in for it), quoted with `>` or indented — `> ## Pages` over an unquoted table+ * was invisible to both gates, and a reader could still take that table for the plan's. Counting one too many+ * can only refuse a plan, never pick a wrong table. A section with no File column — a maker's own `## Pages`+ * list of what they want, prose, a per-page `### Pages …` specification — names no file, so it is no table.+ * @param {string} plan+ * @param {{ heading?: RegExp }} [opts]+ * @returns {{ tables: string[][], unreadable: boolean }}+ */+function pagesTables(plan, opts = {}) {+ const heading = opts.heading || /^#{2,3}\s+Pages\b/;+ const lines = String(plan || '').replace(/\r\n?/g, '\n').split('\n');+ const cells = (row) => row.replace(/\\\|/g, '\u0000').trim().replace(/^\|/, '').replace(/\|$/, '')+ .split('|').map((c) => c.replace(/\u0000/g, '|').trim());+ // The line with its blockquote markers and indentation taken off: `> > ## Pages` → `## Pages`.+ const bare = (line) => line.replace(/^(?:[ \t]*>)*[ \t]*/, '');+ // `|---|:--:|`: pipes, colons, spaces and at least one dash.+ const isDelimiter = (row) => /^[\s|:-]+$/.test(row) && row.includes('-');+ const tables = [];+ let unreadable = false;+ lines.forEach((line, start) => {+ if (!heading.test(bare(line))) return;+ const rows = [];+ for (let i = start + 1; i < lines.length && !/^#{1,6}\s/.test(bare(lines[i])); i += 1) {+ if (/(?:^|[^\\])\|/.test(bare(lines[i]))) rows.push(bare(lines[i]));+ }+ const starts = [];+ for (let k = 0; k + 1 < rows.length; k += 1) if (!isDelimiter(rows[k]) && isDelimiter(rows[k + 1])) starts.push(k);+ const parsed = starts.map((k, n) => ({+ cols: cells(rows[k]).map((h, c) => (h.toLowerCase() === 'file' ? c : -1)).filter((c) => c !== -1),+ body: rows.slice(k + 2, n + 1 < starts.length ? starts[n + 1] : rows.length),+ }));+ const named = parsed.filter((t) => t.cols.length);+ if (!named.length) return;+ if (starts[0] > 0 || named.length < parsed.length+ || named.some((t) => t.cols.length > 1 || t.body.some(isDelimiter))) unreadable = true;+ tables.push(...named.map((t) => t.body.map((row) => cells(row)[t.cols[0]] || '')));+ });+ return { tables, unreadable };+}++module.exports = { pageFileProblems, pageFilesFromPlan, pagesTables };diff --git a/plugins/model-apps/scripts/lib/page-plan.js b/plugins/model-apps/scripts/lib/page-plan.jsindex b238227f5..d213b02ec 100644--- a/plugins/model-apps/scripts/lib/page-plan.js+++ b/plugins/model-apps/scripts/lib/page-plan.js@@ -16,6 +16,9 @@//// PURE: no I/O, no network. The CLI wrapper (scripts/write-page-plan.js) owns writing the file.+const path = require('node:path');+const { pageFileProblems } = require('./page-file-targets.js');+// Per-page fields required by references/plan-schema.md -> `## Per-Page Specifications`.// Kept as a constant so the tests (and any future validator) assert against one list.const REQUIRED_PAGE_FIELDS = [@@ -95,6 +98,43 @@ function pageFile(p) {return existing || `${pageKey(p)}.tsx`;}+// Where the plan says a page lives. An intent page is written at pageFile(p). An implemented page is+// listed for the navigation graph only (no worker writes it), and its codeFile is shown in the one+// spelling the page-file rule accepts: `pages\home.tsx` and `pages/../pages/report.tsx` — which the+// spec gate accepts — become `pages/home.tsx` and `pages/report.tsx`, so the plan still passes the+// schema validator that polices this same rule.+function normalizePageFile(f) {+ return path.posix.normalize(String(f).trim().replace(/\\/g, '/'));+}+function planFile(p) {+ const implemented = p.source && p.source.kind === 'tsx' && p.source.codeFile;+ return implemented ? normalizePageFile(implemented) : pageFile(p);+}++// The rule is lib/page-file-targets.js, shared with /genpage's pre-dispatch gate and the plan+// validator. No working directory is passed: this module is PURE, so only the lexical and collision+// checks run here — the realpath check is I/O and belongs to check-page-files.js, which the genpage+// flow runs before it dispatches workers. Collisions are named apart because they involve two pages.+//+// Only a page a worker will WRITE (an intent page) is held to the whole rule. An implemented page is in+// the plan for the navigation graph only, and its codeFile already passed the spec gate's own+// confinement check (codeFileConfined, app-spec.js), which accepts the Windows spelling `pages\home.tsx`+// — refusing that here blocked /app-builder for a spec the gate had accepted. Implemented files are+// passed as `built`: normalized, checked first by the lexical rules and for collisions, so a new page is+// never written over one — but not by the write-target rules, such as the `.tsx` extension.+function validatePageTargets(pages) {+ const targets = pages.map((p) => {+ const implemented = Boolean(p.source && p.source.kind === 'tsx' && p.source.codeFile);+ return { key: pageKey(p), file: planFile(p), implemented };+ });+ const [problem] = pageFileProblems(targets.filter((t) => !t.implemented).map((t) => t.file),+ { built: targets.filter((t) => t.implemented).map((t) => t.file) });+ if (!problem) return;+ if (problem.code === 'collision') throw new Error(`buildPagePlan: case-insensitive page file collision — ${problem.message}`);+ const owner = targets.find((t) => String(t.file).trim() === problem.file);+ throw new Error(`buildPagePlan: unsafe page file for "${owner ? owner.key : problem.file}" — ${problem.message}`);+}+/** Entities a page reads, as the plan's comma-separated logical names (or the literal "mock data").* Logical names flow into `--data-sources` on the generate-types command line, so they are held to* the identifier contract rather than merely escaped. */@@ -163,6 +203,7 @@ function buildPagePlan(spec, opts = {}) {const s = spec || {};const pages = (s.pages || []).filter(Boolean);if (!pages.length) throw new Error('buildPagePlan: the App Spec declares no pages[]');+ validatePageTargets(pages);const workingDir = opts.workingDir || '.';const pluginRoot = opts.pluginRoot || '${PLUGIN_ROOT}';@@ -194,7 +235,7 @@ function buildPagePlan(spec, opts = {}) {out.push('| Page | Key | File | Purpose | Entities |');out.push('|------|-----|------|---------|----------|');for (const p of pages) {- out.push(`| ${mdText(p.name, pageKey(p))} | ${pageKey(p)} | ${mdText(pageFile(p))} | ${mdText(p.purpose, 'Generative page')} | ${mdText(pageEntities(p))} |`);+ out.push(`| ${mdText(p.name, pageKey(p))} | ${pageKey(p)} | ${mdText(planFile(p))} | ${mdText(p.purpose, 'Generative page')} | ${mdText(pageEntities(p))} |`);}out.push('');@@ -216,6 +257,11 @@ function buildPagePlan(spec, opts = {}) {out.push('## Connector Bindings');out.push('No connector bindings.', '');+ // /app-builder does not author Custom API calls either. The section is still mandatory: an absent+ // section means the planner forgot part of the contract, while this exact sentinel means "none".+ out.push('## Custom API Bindings');+ out.push('No custom API bindings.', '');+out.push('## Design Preferences');out.push(`- Styling: ${design.styling}`);if (design.layout) out.push(`- Layout: ${design.layout}`);@@ -242,7 +288,7 @@ function buildPagePlan(spec, opts = {}) {const nav = navTargets(p);out.push(`### ${mdText(p.name, pageKey(p))}`);out.push(`- **Key:** ${pageKey(p)}`);- out.push(`- **File:** ${mdText(pageFile(p))}`);+ out.push(`- **File:** ${mdText(planFile(p))}`);out.push(`- **Purpose:** ${mdText(p.purpose, 'Generative page')}`);out.push(`- **Entities:** ${mdText(pageEntities(p))}`);out.push(`- **Needs caching:** ${needsCaching(p)}`);@@ -281,6 +327,7 @@ module.exports = {mdText,pageKey,pageFile,+ planFile,pageEntities,pageDataMode,needsCaching,diff --git a/plugins/model-apps/scripts/lib/pageref-resolver.js b/plugins/model-apps/scripts/lib/pageref-resolver.jsindex c9281a55f..95263c82a 100644--- a/plugins/model-apps/scripts/lib/pageref-resolver.js+++ b/plugins/model-apps/scripts/lib/pageref-resolver.js@@ -1,4 +1,6 @@'use strict';+const { blankNonCodePreservingTemplateExpressions } = require('./source-literals.js');+// Pure STRUCTURAL resolver for generative-page cross-page navigation. Authors emit a link as a stable// symbolic token — pageId: "PAGEREF_<key>" — because the real GenPageId is minted by the server at// deploy time and differs per environment (SDK opaque-identity rule T5: never bake a resolved GUID into@@ -11,14 +13,21 @@// call sites and returns one classified entry per generative call site. Every other function here, and// the build/verify/download consumers, derive from it — so a decoy "PAGEREF_x" string or a stray GUID// in a comment/label (NOT a real nav pageId) can never satisfy parity, resolution, or verification.-// This replaces the earlier bare-token string scan, which a wrong-quoted or misplaced token could evade-// (review R2, Critical 1/C4).+// This replaces the earlier bare-token string scan, which a wrong-quoted or misplaced token could evade.+//+// COMMENT / LITERAL STRIPPING (#588): extractNavTargets scans a code-only mask+// BEFORE scanning for navigateTo call sites. Anything inside a // comment, /* */ block comment, quoted+// string, regex literal, JSX text, or template-literal TEXT is blanked (same-length space substitution,+// preserving all character offsets) so a navigateTo that appears as help text is invisible to NAV_CALL.+// JavaScript inside template `${...}` expressions remains visible because it is executable code.//-// COMMENT / TEMPLATE-LITERAL STRIPPING (addendum Crit 1): extractNavTargets calls stripNonCode()-// BEFORE scanning for navigateTo call sites. Anything inside a // comment, /* */ block comment, or-// backtick template literal is blanked (same-length space substitution, preserving all character-// offsets) so a navigateTo that appears as comment text or template-literal content is invisible to the-// NAV_CALL regex and is therefore NEVER counted as a real call site.+// The call's OBJECT is parsed from that same mask, and each value is then read from the ORIGINAL+// source at the same offsets. The mask blanks a string's contents but keeps its quotes, so it can+// locate `pageType: "…"` and `pageId: "…"` but not say what they hold. One lexer drives both steps:+// a lighter second copy that knew no regexes read the `/*` inside+// u.replace(/\/*$/, "")+// as a comment opener, blanked everything after it, and dropped every later call — so a literal+// "PAGEREF_detail" shipped unresolved while verification passed.// `navigateTo(` immediately followed by an object literal `{`. `\s*` tolerates the multi-line form in// references/rules.md. The method-name prefix (Xrm.Navigation./xrm.Navigation.) is irrelevant to the@@ -30,89 +39,6 @@ const PAGEREF_ANY = /PAGEREF_([A-Za-z0-9_-]+)/; // a PAGEREF token in ANY form (// as a single literal when the full expression is somehow presented as a raw string.const QUOTED = /^(["'`])((?:[^"'`\\]|\\[\s\S])*)\1$/;-// Replace the body of line comments (//), block comments (/* ... */), and backtick template literals-// — including any ${...} expressions inside them — with ASCII space characters. Every character offset-// in the returned string is identical to the same offset in the input, so `valueStart`/`valueEnd`-// spans extracted from the cleaned string are also valid in the original source.-//-// Why spaces (not empty or shorter substitution): NAV_CALL.exec() and objectArgAt/topLevelValue use-// raw offset arithmetic; replacing with equal-length spaces keeps every span valid in both strings.-//-// Why blank backtick template-literal BODIES (but KEEP the backtick delimiters): we want a-// navigateTo that appears as TEMPLATE LITERAL TEXT to be invisible to the scanner — blanking-// the body achieves this. Keeping the delimiter backtick characters means objectArgAt /-// topLevelValue correctly detect a backtick-QUOTED VALUE (their `inStr` branches already-// handle backtick as a string delimiter), so a nav pageId written as `PAGEREF_x` is-// classified as pageref-malformed instead of falling through to `dynamic` (which would-// silently bypass the malformed-HALT gate — security finding C4).-//-// Template ${} expressions: we track { } depth to correctly identify when a ${...} expression ends.-// We do NOT track strings-inside-${} (e.g. a `}` inside a "string" inside `${}` would decrement-// depth early). This is a known conservative trade-off — a navigateTo call inside a ${} expression-// of a template literal is an extreme edge case, and blanking it conservatively is the right-// fail-closed choice.-function stripNonCode(code) {- const out = [...code];- let i = 0;- while (i < code.length) {- const c = code[i];- if (c === '/' && i + 1 < code.length && code[i + 1] === '/') {- // Line comment: blank from // to end of line; preserve the newline itself so line- // numbers (and thus any diagnostics referencing them) are not shifted.- while (i < code.length && code[i] !== '\n') { out[i] = ' '; i++; }- } else if (c === '/' && i + 1 < code.length && code[i + 1] === '*') {- // Block comment: blank from /* to */ inclusive.- out[i] = ' '; out[i + 1] = ' '; i += 2;- while (i < code.length) {- if (code[i] === '*' && i + 1 < code.length && code[i + 1] === '/') {- out[i] = ' '; out[i + 1] = ' '; i += 2; break;- }- out[i] = ' '; i++;- }- } else if (c === '`') {- // Template literal: keep the opening backtick delimiter, blank the body content, keep the- // closing backtick delimiter. The body content (and any ${...} expressions) are blanked so- // a navigateTo inside template text is invisible to NAV_CALL. The delimiters are preserved- // so objectArgAt / topLevelValue can detect a backtick-QUOTED pageId VALUE via their inStr- // branch (see the "Why" comment above). Track { } depth to correctly span ${...} expressions.- i++; // advance past the opening backtick — leave it unchanged in `out`- let depth = 0;- while (i < code.length) {- const cc = code[i];- if (cc === '\\') {- // Escape sequence: blank both the backslash and the escaped character.- out[i] = ' ';- if (i + 1 < code.length) { out[i + 1] = ' '; i += 2; } else i++;- continue;- }- if (depth === 0 && cc === '$' && i + 1 < code.length && code[i + 1] === '{') {- // Start of a ${} expression: blank both characters and increment depth.- out[i] = ' '; out[i + 1] = ' '; i += 2; depth++; continue;- }- if (depth > 0 && cc === '{') { out[i] = ' '; i++; depth++; continue; }- if (depth > 0 && cc === '}') { out[i] = ' '; i++; depth--; continue; }- if (depth === 0 && cc === '`') {- // Closing backtick of the template literal — leave it unchanged in `out`, then stop.- i++; break;- }- out[i] = ' '; i++;- }- } else if (c === '"' || c === "'") {- // Regular string: skip over it WITHOUT blanking — objectArgAt and topLevelValue need the- // string contents intact to correctly identify key/value boundaries inside navigateTo({...}).- i++;- while (i < code.length) {- if (code[i] === '\\') { i += 2; continue; }- if (code[i] === c) { i++; break; }- i++;- }- } else {- i++;- }- }- return out.join('');-}-// Scan the object-literal argument of a navigateTo(...) call from the '{' at `open` to its matching// '}', string-aware so a brace inside a string does not end the object. Returns { text, end } or null// on an unbalanced/broken literal (the caller treats a broken call as having no nav target).@@ -122,8 +48,8 @@ function objectArgAt(code, open) {for (let i = open; i < code.length; i += 1) {const c = code[i];if (inStr) { if (c === '\\') { i += 1; continue; } if (c === inStr) inStr = null; continue; }- // inStr handles backtick-quoted values (delimiters kept by stripNonCode) so their blanked body- // doesn't count as unbalanced braces when scanning the object boundary.+ // inStr handles quoted values — the mask keeps their delimiters and blanks their bodies — so a+ // quote or brace in a value never counts toward the object boundary.if (c === '"' || c === "'" || c === '`') { inStr = c; continue; }if (c === '{') depth += 1;else if (c === '}') { depth -= 1; if (depth === 0) return { text: code.slice(open, i + 1), end: i + 1 }; }@@ -146,8 +72,8 @@ function topLevelValue(objText, key) {for (let i = 0; i < objText.length; i += 1) {const c = objText[i];if (inStr) { if (c === '\\') { i += 1; continue; } if (c === inStr) inStr = null; continue; }- // inStr handles backtick-quoted values (delimiters kept by stripNonCode) so their blanked body- // is not misread as key or bracket content when scanning for the target key.+ // inStr handles quoted values (delimiters kept, bodies blanked by the mask) so a value is never+ // misread as key or bracket content when scanning for the target key.if (c === '"' || c === "'" || c === '`') { inStr = c; continue; }if (c === '{' || c === '[' || c === '(') { depth += 1; continue; }if (c === '}' || c === ']' || c === ')') { depth -= 1; continue; }@@ -194,40 +120,38 @@ function topLevelValue(objText, key) {// partial-collide. Only pageType:'generative' string-literal call sites are returned — a non-generative// or dynamic pageType is not a cross-page genpage navigation.//-// Comment/template stripping (addendum Crit 1): stripNonCode() is called FIRST; the returned cleaned-// string is used for ALL parsing, so a navigateTo that appears inside a // comment, /* */ block-// comment, or backtick template literal is not matched. Spans in the cleaned string are identical to-// spans in the original because stripping replaces characters with same-length spaces.+// Code-mask scanning (#588): call sites are found in a mask that blanks inert strings/comments/JSX+// text/template text but preserves executable template expressions. The object is parsed from the+// same mask (string bodies blanked, quotes kept) and every value is read from the original source at+// the span the mask gives. Both strings are the same length, so every span maps 1:1.function extractNavTargets(code) {const src = String(code || '');- const s = stripNonCode(src);+ const callSites = blankNonCodePreservingTemplateExpressions(src);const out = [];NAV_CALL.lastIndex = 0;let m;- while ((m = NAV_CALL.exec(s)) !== null) {+ while ((m = NAV_CALL.exec(callSites)) !== null) {const open = m.index + m[0].length - 1; // index of the '{' that opens the object argument- const obj = objectArgAt(s, open);+ const obj = objectArgAt(callSites, open);if (!obj) continue;+ // pv.valueStart / pv.valueEnd are relative to obj.text, which starts at `open`; adding `open`+ // makes them absolute offsets into the mask and, equally, into the original source.+ const valueAt = (v) => src.slice(open + v.valueStart, open + v.valueEnd).trim();const pt = topLevelValue(obj.text, 'pageType');- const ptQ = pt && QUOTED.exec(pt.raw);+ const ptQ = pt && QUOTED.exec(valueAt(pt));if (!ptQ || ptQ[2] !== 'generative') continue;const pv = topLevelValue(obj.text, 'pageId');if (!pv) continue;- // pv.valueStart / pv.valueEnd are relative to obj.text which starts at `open` in s.- // Adding `open` makes them absolute offsets into s (and equally into the original code,- // since stripNonCode replaces with equal-length spaces — offsets are always identical in both).const valueStart = open + pv.valueStart;const valueEnd = open + pv.valueEnd;- // Classify from the ORIGINAL source span (not the stripped text): backtick-quoted values have- // their bodies blanked in `s`, so `pv.raw` from `s` is `\` \`` (spaces) and PAGEREF_ANY would- // miss the token. Using `src` at the same offsets recovers the original content (e.g. `\`PAGEREF_x\``)- // so the token is found and classified as pageref-malformed instead of silently falling to `dynamic`.- const rawOrig = src.slice(valueStart, valueEnd).trim();+ // Classify from the ORIGINAL source span: the mask blanks every string body, so a backtick-quoted+ // `PAGEREF_x` is found (and classified as pageref-malformed) only in `src`.+ const rawOrig = valueAt(pv);const canon = CANON.exec(rawOrig);if (canon) { out.push({ kind: 'pageref', key: canon[1], valueStart, valueEnd }); continue; }// A PAGEREF token in any non-canonical form is malformed (single/back-tick quoted, concatenated)// — the resolver can only substitute the canonical double-quoted token, so a malformed one- // would ship UNRESOLVED. See C4.+ // would ship UNRESOLVED — which is why the build halts on one (navMalformedRefs).const anyRef = PAGEREF_ANY.exec(rawOrig);if (anyRef) { out.push({ kind: 'pageref-malformed', key: anyRef[1], raw: rawOrig, valueStart, valueEnd }); continue; }const quoted = QUOTED.exec(rawOrig);@@ -245,8 +169,8 @@ function navReferencedKeys(code) {return [...keys].sort();}-// Sorted-unique PAGEREF tokens used as a nav pageId in a MALFORMED form. The build HALTs on any-// (C4): the resolver substitutes only the canonical double-quoted token, so a malformed ref would+// Sorted-unique PAGEREF tokens used as a nav pageId in a MALFORMED form. The build HALTs on any:+// the resolver substitutes only the canonical double-quoted token, so a malformed ref would// deploy a dead link. Derived from the oracle, so a malformed PAGEREF that is NOT a nav pageId is// ignored.function navMalformedRefs(code) {@@ -298,7 +222,7 @@ function reverseResolveNavIds(code, idToKey) {}// Pure exact-parity between a page's DECLARED navigatesTo targetKeys and the keys its source-// actually references via canonical nav pagerefs. Exact parity is required (C4): a declared edge+// actually references via canonical nav pagerefs. Exact parity is required: a declared edge// missing from the source, or a source ref with no declaration, is an authoring error the caller// HALTs on before deploy.function navTargetParity(declaredKeys, referencedKeysList) {@@ -310,4 +234,4 @@ function navTargetParity(declaredKeys, referencedKeysList) {};}-module.exports = { extractNavTargets, navReferencedKeys, navMalformedRefs, resolvePageRefs, reverseResolveNavIds, navTargetParity, stripNonCode };+module.exports = { extractNavTargets, navReferencedKeys, navMalformedRefs, resolvePageRefs, reverseResolveNavIds, navTargetParity };diff --git a/plugins/model-apps/scripts/lib/source-literals.js b/plugins/model-apps/scripts/lib/source-literals.jsindex 6fe8410a9..1e6ed4210 100644--- a/plugins/model-apps/scripts/lib/source-literals.js+++ b/plugins/model-apps/scripts/lib/source-literals.js@@ -16,7 +16,8 @@// const re = /\(/; `(` is not a bracket here// "The worker says export default X is required." not an export statement//-// MODES: code (incl. JSX expressions), comment, string, template, regex, JSX tag, JSX text.+// MODES: code (incl. JSX expressions), comment, string, template, regex, JSX tag, JSX text. A+// template's `${…}` body is code, read by the same machine (lexInto).// Blanked characters become spaces and newlines are preserved, so output offsets map 1:1 onto the// input and a caller may mix matches across both.@@ -35,16 +36,283 @@ function prevSignificant(src, i) {function expressionPosition(src, i) {const { ch, index } = prevSignificant(src, i);if (ch === '') return true; // start of file+ // A postfix operator ends an operand, so a `/` or `<` after one is an operator too:+ // closed! / total TypeScript's non-null assertion+ // i++ / 2 postfix increment (or decrement)+ // `!` is postfix exactly when it does not itself start an expression, so a prefix `!` still+ // opens one: `return !/\(/.test(s)`, and `if (bad) !/\(/.test(s)` (see closesStatementHead).+ if (ch === '!') return expressionPosition(src, index);+ if ((ch === '+' || ch === '-') && src[index - 1] === ch) return false;+ // A `>` can be a binary relational operator (`count > /re/.test(x)`), the `>` of an arrow's `=>`,+ // a JSX tag close, or a type-argument close after a cast. Only the latter two end an operand.+ // The cast case is intentionally narrow: `total as NonNullable< number > / count` divides, but+ // `count<limit ? () => /re/ : ...` must leave `=>` as an expression-start token before a regex.+ if (ch === '>') return !greaterThanEndsOperand(src, index);if (EXPR_START_PUNCT.has(ch)) return true;- if (/[\w$)\]]/.test(ch)) {- // Could be the tail of a keyword like `return` — read the word back.+ // A `)` usually ends an operand — `counts.get(k)! / total`, `(a + b) / 2` — but the `)` that+ // closes an `if (…)`, `for (…)` or `while (…)` head is followed by a STATEMENT, where an+ // expression starts: `if (x) /re/.test(y)`.+ if (ch === ')') return closesStatementHead(src, index);+ if (/[\w$\]]/.test(ch)) {+ // Could be the tail of a keyword like `return` — read the word back. Built char by char so `src`+ // may be the lexer's partly blanked output ARRAY as well as a string (see blankLiterals).let s = index;while (s >= 0 && /[\w$]/.test(src[s])) s -= 1;- return EXPR_START_WORDS.has(src.slice(s + 1, index + 1));+ let word = '';+ for (let k = s + 1; k <= index; k += 1) word += src[k];+ // ...unless it is a PROPERTY that happens to share a keyword's name — a status count is often+ // keyed `new`, and `counts.new / total` divides. `?.new` is a property too; a spread's+ // `...new Set(x)` is the keyword.+ if (EXPR_START_WORDS.has(word) && isPropertyName(src, s)) return false;+ return EXPR_START_WORDS.has(word);}return false;}+// True when the word that starts after index `s` is reached through `.` (or `?.`), not `...`.+function isPropertyName(src, s) {+ let p = s;+ while (p >= 0 && /\s/.test(src[p])) p -= 1;+ return src[p] === '.' && !(src[p - 1] === '.' && src[p - 2] === '.');+}++// Heuristic for the ambiguous `>` token in dependency-free TSX scanning. The raw shapes this protects:+// total as NonNullable< number > / count `>` closes a cast type argument; `/` is division+// export default () => <Icon /> `>` closes JSX; EOF is complete+// export default () => count > `>` is a relational operator; EOF is truncated+// count<limit ? () => /re/ : () => /none/ the `>` in `=>` is not an angle close+//+// Dependency-free text cannot safely tell a generic instantiation or type-alias tail from a+// relational expression in all TSX contexts. So expression classification is intentionally narrow:+// `/` after `>` divides only when `>` closes a cast's type arguments (`as Foo<Bar>`, `satisfies+// Foo<Bar>`). EOF handling is even stricter below: a final `>` completes only+// when the lexer recorded it as a JSX tag close, and a final type-argument list needs `;`.+function greaterThanEndsOperand(src, close) {+ if (src[close - 1] === '=') return false;+ return greaterThanClosesTypeArguments(src, close) || greaterThanClosesJsxTag(src, close);+}++function greaterThanClosesTypeArguments(src, close) {+ const open = matchingTypeArgumentOpen(src, close);+ if (open === -1) return false;+ return typeArgumentOpenFollowsCast(src, open);+}++// The `<` that a type-argument `>` at `close` closes, by angle depth, or -1. Function types are valid inside type+// arguments (`ReturnType<() => number>`): the arrow's `>` is not an angle close. The span is not judged here. Only a+// cast gives type-argument context (typeArgumentOpenFollowsCast), and after `as` or `satisfies`+// TypeScript parses a type, where `Name<` is always type arguments, so no valid code puts an expression there.+function matchingTypeArgumentOpen(src, close) {+ let depth = 1;+ for (let k = close - 1; k >= 0 && close - k <= LOOKAHEAD; k -= 1) {+ const c = src[k];+ if (c === '>' && src[k - 1] !== '=') depth += 1;+ else if (c === '<') {+ depth -= 1;+ if (depth === 0) return k;+ } else if (c === ';' && depth === 1) {+ return -1;+ }+ }+ return -1;+}++// Type names that take no type arguments: `as number <` can only be a comparison. `this`, `true` and `false` are+// types too, and take none either.+const PRIMITIVE_TYPES = new Set(['any', 'unknown', 'never', 'void', 'undefined', 'null', 'number', 'string',+ 'boolean', 'bigint', 'symbol', 'object', 'this', 'true', 'false']);++// Is the `<` at `open` the start of a cast's type arguments? After `as` or `satisfies` TypeScript parses a type, so+// there `Name<` IS type arguments and a `/` after their `>` divides. The name may be one part of a larger type, so the+// walk back steps over the rest of it to reach the keyword:+// total as number & Brand<"USD"> / count a constituent of an intersection or union+// value as A | B.C<D> / n a qualified name+// total satisfies "n/a" | NonNullable<number> / count a string-literal constituent+// total as | -1 | Brand<"USD"> / count a type that leads with its operator, and a signed literal+// total as V extends U ? 0 : NonNullable<V> / count the false branch of a conditional type+// Each constituent is a (qualified) name, with its own closed type arguments or with indexes (each stepped over whole,+// its brackets matched), a numeric literal with its sign, or a string literal (its quotes are kept when the lexer+// blanks it). Anything else ends the walk and the `<` is not taken for type arguments. The walk is bounded by+// distance, like the other scans here, not by a count of constituents.+function typeArgumentOpenFollowsCast(src, open) {+ const skipSpace = (i) => { while (i >= 0 && /\s/.test(src[i])) i -= 1; return i; };+ const skipName = (i) => { while (i >= 0 && /[\w$.]/.test(src[i])) i -= 1; return i; };+ const wordEndingAt = (e) => { let s = e; while (s >= 0 && /[\w$]/.test(src[s])) s -= 1; let w = ''; for (let k = s + 1; k <= e; k += 1) w += src[k]; return { s, w }; };+ // Steps back over a (qualified) name that ends at `r`, with any indexes after it (`Row[Key]`, `Row["tax" | as][0]`).+ // Each index is matched to its own `[`, so nothing inside one is read by the walk: an operator or a word there belongs+ // to the index's type, never to the cast's. Returns the index before the name, or null when there is none (a tuple,+ // `[A, B]`, is not walked) or an index has no `[` within reach.+ const skipIndexedName = (r) => {+ while (src[r] === ']') {+ let depth = 0;+ let k = r;+ while (k >= 0 && open - k <= LOOKAHEAD && !(src[k] === '[' && depth === 1)) {+ if (src[k] === ']') depth += 1;+ else if (src[k] === '[') depth -= 1;+ k -= 1;+ }+ if (k < 0 || open - k > LOOKAHEAD) return null;+ r = k - 1;+ while (r >= 0 && (src[r] === ' ' || src[r] === '\t')) r -= 1;+ }+ const s = skipName(r);+ return s === r ? null : s;+ };+ // Steps back over one constituent that ends at `r`: a name (qualified or indexed, `Row[Key]`), a literal, either with+ // its own closed type arguments, or a string literal. Returns the index before it, or null.+ const skipConstituent = (r) => {+ if (src[r] === '"' || src[r] === "'") {+ const quote = src[r];+ let k = r - 1;+ while (k >= 0 && !(src[k] === quote && src[k - 1] !== '\\')) k -= 1;+ return k < 0 ? null : k - 1;+ }+ if (src[r] === '>') {+ const o = matchingTypeArgumentOpen(src, r);+ if (o === -1) return null;+ r = skipSpace(o - 1);+ }+ const s = skipIndexedName(r);+ if (s === null) return null;+ // A negative numeric literal type keeps its sign: `-1 | 0`.+ const t = skipSpace(s);+ return src[t] === '-' && /\d/.test(src[s + 1]) ? t - 1 : s;+ };+ // Steps back from a union or intersection operator at `q` over the constituent before it. When the operator leads its+ // type there is none, and it returns the index before the operator. It leads after a non-name (`? | 0`, `: | A`), and+ // after a bare `as`, `satisfies` or `extends` (`as | A`, `extends | 0 | 1`): only there are those words keywords.+ // `as` and `satisfies` are contextual, so with type arguments of its own (`satisfies<T>`), within a longer name+ // (`E.as`), or before `?`, `:` or `extends`, the word names a type; and one inside an index (`Row["tax" | as]`) is+ // never reached, as the index is stepped over whole. The name is taken whole, as `skipConstituent` reads it, so only+ // a word standing alone is a keyword. A type or variable named `as` or `satisfies` with no type arguments, standing+ // alone right before `|` or `&`, is read as the keyword.+ const skipBeforeOperator = (q) => {+ const b = skipSpace(q - 1);+ const s = skipIndexedName(b);+ let word = '';+ if (s !== null) for (let k = s + 1; k <= b; k += 1) word += src[k];+ if (word === 'as' || word === 'satisfies' || word === 'extends') return q - 1;+ const t = skipConstituent(b);+ return t === null ? q - 1 : t;+ };+ // Steps back over a union or intersection of constituents that ends at `r` (`0 | 1`, `string | undefined`), for the+ // parts of a conditional type. A leading operator is part of it: `| 0 | 1`. Returns the index before it, or null.+ const skipCompound = (r) => {+ let s = skipConstituent(r);+ while (s !== null) {+ const q = skipSpace(s);+ if (!((src[q] === '&' || src[q] === '|') && src[q - 1] !== src[q])) return s;+ s = skipBeforeOperator(q);+ }+ return null;+ };+ // The head, the name the `<` belongs to. TypeScript attaches type arguments only to a plain (qualified) type name on+ // the same line as the `<`. An indexed type (`Row[Key] <`), a literal (`0 | 1 <`), a primitive or `this`, or a line+ // break before the `<` (`as Count` then `< high` on the next line) makes that `<` a comparison.+ let end = open - 1;+ while (end >= 0 && (src[end] === ' ' || src[end] === '\t')) end -= 1;+ let p = end;+ while (p >= 0 && /[\w$.]/.test(src[p])) p -= 1;+ // Char by char, not `slice`: `src` may be the lexer's partly blanked output ARRAY (see expressionPosition).+ let name = '';+ for (let k = p + 1; k <= end; k += 1) name += src[k];+ if (!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(name) || PRIMITIVE_TYPES.has(name)) return false;+ while (open - p <= LOOKAHEAD) {+ const q = skipSpace(p);+ const op = src[q];+ if ((op === '&' || op === '|') && src[q - 1] !== op) {+ // The constituent before the operator, or, when the operator leads its type (`as | A | B<C>`, a false branch+ // `: | A | B<C>`), nothing: what comes before it then decides, as it does for any other type.+ p = skipBeforeOperator(q);+ continue;+ }+ // A conditional type's false branch: `as V extends U ? 0 | 1 : NonNullable<V> / count`. Step back over the true+ // branch, its `?`, the extends type and `extends` itself, to the checked type. Each part may be a union or an+ // intersection. A conditional chained in a false branch is walked one link per turn of the loop. A ternary or an+ // object property has no `extends` before its `?`, so the walk refuses it here, and so it does a conditional nested+ // in a true branch or a parenthesized type in any part.+ if (op === ':' && src[q - 1] !== ':') {+ let r = skipCompound(skipSpace(q - 1));+ if (r === null) return false;+ r = skipSpace(r);+ if (src[r] !== '?' || src[r - 1] === '?') return false;+ r = skipCompound(skipSpace(r - 1));+ if (r === null) return false;+ const { s, w } = wordEndingAt(skipSpace(r));+ if (w !== 'extends') return false;+ r = skipCompound(skipSpace(s));+ if (r === null) return false;+ p = r;+ continue;+ }+ break;+ }+ // Only a cast. A `:` looked like an annotation's, but no valid code puts a division directly after an annotation's+ // type (`const x: Foo<T> / 2` is no TypeScript), and every `:` it matched was an object property's, a ternary's or a+ // case clause's: `{ a: start < anchor + padding, b: end > /}/ }`, `[c ? t : start < Math.max(x, 0), end > /}/]`.+ // After `as` or `satisfies`, TypeScript itself parses a type, so `Name<` there IS type arguments.+ const before = prevWordOrPunct(src, p + 1);+ return before === 'as' || before === 'satisfies';+}+++function prevWordOrPunct(src, before) {+ let p = before - 1;+ while (p >= 0 && /\s/.test(src[p])) p -= 1;+ if (src[p] === ':') return ':';+ let e = p;+ while (p >= 0 && /[\w$]/.test(src[p])) p -= 1;+ let word = '';+ for (let k = p + 1; k <= e; k += 1) word += src[k];+ return word;+}++function greaterThanClosesJsxTag(src, close) {+ let depth = 0;+ for (let k = close; k >= 0 && close - k <= LOOKAHEAD; k -= 1) {+ if (src[k] === '>') depth += 1;+ else if (src[k] === '<') {+ depth -= 1;+ if (depth !== 0) continue;+ if (src[k + 1] === '/') return true;+ return /[A-Za-z_$/>]/.test(src[k + 1] || '') && expressionPosition(src, k);+ } else if (src[k] === ';') {+ return false;+ }+ }+ return false;+}++// True when the `)` at `close` ends the head of an `if`, `for`, `while` or `with` statement. The+// matching `(` is found by counting back over `src` — the lexer's output, where brackets inside+// strings, comments and regexes are already blanked — and bounded, so a long expression costs at+// most LOOKAHEAD characters; past that, the `)` is taken to end an operand.+const STATEMENT_HEADS = new Set(['if', 'for', 'while', 'with']);+function closesStatementHead(src, close) {+ let depth = 0;+ for (let j = close; j >= 0 && close - j <= LOOKAHEAD; j -= 1) {+ if (src[j] === ')') depth += 1;+ else if (src[j] === '(' && --depth === 0) {+ let { word, start } = wordBefore(src, j);+ // `for await (const x of xs)` — the head's keyword is the word before `await`.+ if (word === 'await') ({ word, start } = wordBefore(src, start + 1));+ return STATEMENT_HEADS.has(word) && !isPropertyName(src, start);+ }+ }+ return false;+}++// The word that ends just before index `j` (whitespace skipped), and the index before its start.+function wordBefore(src, j) {+ let e = j - 1;+ while (e >= 0 && /\s/.test(src[e])) e -= 1;+ let s = e;+ while (s >= 0 && /[\w$]/.test(src[s])) s -= 1;+ let word = '';+ for (let k = s + 1; k <= e; k += 1) word += src[k];+ return { word, start: s };+}+// `<` in a .tsx file is ambiguous: JSX, or a TypeScript type-parameter list. Both can appear right// after `=`, so position alone cannot separate them:// const updateField = <K extends keyof FormState>(key: K) => { … } // generic arrow@@ -169,12 +437,33 @@ function looksLikeTypeParams(src, i) {* @param {string} code* @returns {string} same length as `code`, non-code regions replaced by spaces*/-function blankLiterals(code) {+function blankLiterals(code, opts) {const src = String(code || '');+ // Reports each comment's [start, end) to the caller (commentRanges below), so code that must read+ // COMMENT text uses this lexer's view of what a comment is rather than a regex that takes the `//`+ // in "https://…" for one. Optional: the blanked output is the same either way.+ const onComment = opts && typeof opts.onComment === 'function' ? opts.onComment : null;+ const onRegexEnd = opts && typeof opts.onRegexEnd === 'function' ? opts.onRegexEnd : null;// split('') and NOT [...src]: the spread iterates by CODE POINT, so an astral character (an emoji// in a label, which generated pages do use) makes array indices drift out of step with the UTF-16// offsets everything else here uses, corrupting the output.const out = src.split('');+ lexInto(src, out, 0, { onComment, onRegexEnd });+ return out.join('');+}++// The lexer itself. From `start` it blanks inert text into `out` — `src` split into UTF-16 units,+// possibly already partly blanked by an enclosing call — and judges regex and JSX positions on it.+//+// With `untilCloseBrace` it reads the body of a template's `${…}` instead, and returns the index of+// the `}` that closes it (src.length when none does). That body is ordinary code — strings,+// comments, regexes, nested templates and JSX — so it gets this same lexer, not a lighter scanner.+// A brace counter that knew no JSX read the `/` of `</span>` in+// `${<span>Save</span>}`+// as the start of a regex that swallowed the closing `}`, and the apostrophe in `${<p>it's</p>}` as a+// string. Either way the template never ended, and the page's `export default` vanished with it.+// Otherwise it returns src.length.+function lexInto(src, out, start, { onComment = null, onRegexEnd = null, onJsxTagEnd = null, untilCloseBrace = false, onEnd = null } = {}) {const blank = (from, to) => {for (let k = Math.max(0, from); k < to && k < src.length; k += 1) if (src[k] !== '\n') out[k] = ' ';};@@ -183,7 +472,9 @@ function blankLiterals(code) {let jsxDepth = 0; // open JSX elements in the CURRENT expression framelet angleDepth = 0; // nested < > inside a tag's type argumentsconst frames = []; // JSX-expression frames: { returnMode, braceDepth, savedJsxDepth }- let i = 0;+ let braceDepth = 0; // `{` opened in plain code inside a `${…}` body (untilCloseBrace)+ let unterminated = false; // a string, regex, template, comment or closing tag ran off the end+ let i = start;const leaveJsxExpr = () => {const f = frames.pop();@@ -210,13 +501,16 @@ function blankLiterals(code) {if (c === '/' && n === '/') {const end = src.indexOf('\n', i);blank(i, end === -1 ? src.length : end);+ if (onComment) onComment(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;+ if (end === -1) unterminated = true;blank(i, stop);+ if (onComment) onComment(i, stop);i = stop;continue;}@@ -228,26 +522,32 @@ function blankLiterals(code) {if (src[j] === '\n') { j = -1; break; } // a string cannot span a raw newline}if (j === -1) { i += 1; continue; }+ if (j >= src.length) unterminated = true;blank(i + 1, j);i = Math.min(j + 1, src.length);continue;}if (c === '`') {- // Template literal. `${}` expressions are blanked with the rest: no declaration lives inside- // one, and tracking their nesting would only add ways to be wrong.- 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;- }+ // Template literal. Its body — `${}` expressions included — is blanked: no declaration lives+ // inside one. But where it ENDS is found by lexing each `${…}` body with this same lexer+ // (strings, comments, regexes, nested templates and JSX alike). Counting bare braces+ // ended `[${rows.map((r) => `{"id":"${r.id}"}`).join(",")}]` at the `}` in the nested+ // template's TEXT, and everything up to the next backtick — `export default` included — was+ // misread, so a complete page failed as truncated and later nav calls went unseen.+ const j = scanTemplateLiteral(src, i, out, onComment).end;+ if (j >= src.length) unterminated = true;blank(i + 1, j);i = Math.min(j + 1, src.length);continue;}- if (c === '/' && expressionPosition(src, i)) {+ // Position is judged on the blanked output, not the raw source: every comment before `i` is+ // already spaces there, so a comment's last word is not mistaken for the previous token —+ // return (+ // // Instructions+ // <Text>1) Pick a record</Text>+ // read `Instructions` as the token before `<`, took the JSX for a comparison, lexed its text as+ // code and reported `1)` as an unbalanced bracket.+ if (c === '/' && expressionPosition(out, i)) {// Regex literal: scan to the unescaped closing `/`, honouring a character class so `/[/]/`// does not terminate early.let j = i + 1;@@ -260,11 +560,13 @@ function blankLiterals(code) {else if (src[j] === '/' && !inClass) break;}if (j === -1) { i += 1; continue; }+ if (j >= src.length) unterminated = true;+ else if (onRegexEnd) onRegexEnd(j);blank(i + 1, j);i = Math.min(j + 1, src.length);continue;}- if (c === '<' && /[A-Za-z_$>]/.test(n || '') && expressionPosition(src, i) && !looksLikeTypeParams(src, i)) {+ if (c === '<' && /[A-Za-z_$>]/.test(n || '') && expressionPosition(out, i) && !looksLikeTypeParams(src, i)) {mode = 'jsxTag';i += 1;continue;@@ -276,6 +578,12 @@ function blankLiterals(code) {if (top.braceDepth === 0) { leaveJsxExpr(); i += 1; continue; }top.braceDepth -= 1; i += 1; continue;}+ } else if (untilCloseBrace) {+ if (c === '{') braceDepth += 1;+ else if (c === '}') {+ if (braceDepth === 0) return i;+ braceDepth -= 1;+ }}i += 1;continue;@@ -294,19 +602,23 @@ function blankLiterals(code) {if (c === '/' && n === '/') {const end = src.indexOf('\n', i);blank(i, end === -1 ? src.length : end);+ if (onComment) onComment(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;+ if (end === -1) unterminated = true;blank(i, stop);+ if (onComment) onComment(i, stop);i = stop;continue;}if (c === '"' || c === "'") { // attribute valuelet j = i + 1;while (j < src.length && src[j] !== c) j += 1;+ if (j >= src.length) unterminated = true;blank(i + 1, j);i = Math.min(j + 1, src.length);continue;@@ -316,23 +628,18 @@ function blankLiterals(code) {// 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.+ // malformed expression that follows on the same line. Mirrors the `code`-mode scanner: the+ // body is blanked, and its end is found by the expression-aware scanner.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;- }+ const j = scanTemplateLiteral(src, i, out, onComment).end;+ if (j >= src.length) unterminated = true;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 follows+ if (onJsxTagEnd) onJsxTagEnd(i + 1);mode = jsxDepth > 0 ? 'jsxText' : 'code';i += 2;continue;@@ -344,6 +651,7 @@ function blankLiterals(code) {if (c === '<') { angleDepth += 1; i += 1; continue; }if (c === '>') {if (angleDepth > 0) { angleDepth -= 1; i += 1; continue; }+ if (onJsxTagEnd) onJsxTagEnd(i);jsxDepth += 1;mode = 'jsxText';i += 1;@@ -358,6 +666,8 @@ function blankLiterals(code) {if (c === '<' && n === '/') { // closing tagconst end = src.indexOf('>', i);const stop = end === -1 ? src.length : end + 1;+ if (end === -1) unterminated = true;+ else if (onJsxTagEnd) onJsxTagEnd(end);jsxDepth = Math.max(0, jsxDepth - 1);mode = jsxDepth > 0 ? 'jsxText' : 'code';i = stop;@@ -367,6 +677,74 @@ function blankLiterals(code) {blank(i, i + 1);i += 1;}+ // Where the lexer stopped: a complete module ends in plain code, with nothing left open.+ if (onEnd) onEnd({ open: unterminated || mode !== 'code' || frames.length > 0 });+ return src.length;+}++// Index of the `}` that closes the `${…}` whose body starts at `start`, or src.length. The body is+// lexed into `scratch` — a `src.split('')` the caller owns and whose blanks inside the body do not+// matter to it (the lexer passes its own output, which blanks the whole template anyway) — or into+// a fresh copy when none is given. `onComment` hears the body's comments: they are real comments,+// so an elision marker or a comment inside an import there counts like any other.+function scanTemplateExpressionEnd(src, start, scratch, onComment) {+ return lexInto(src, scratch || src.split(''), start, { untilCloseBrace: true, onComment: onComment || null });+}++function scanTemplateLiteral(src, start, scratch, onComment) {+ const expressions = [];+ let view = scratch || null; // one copy for every `${…}` in this template, made on the first+ for (let i = start + 1; i < src.length; i += 1) {+ const c = src[i];+ if (c === '\\') { i += 1; continue; }+ if (c === '`') return { end: i, expressions };+ if (c === '$' && src[i + 1] === '{') {+ if (!view) view = src.split('');+ const exprStart = i + 2;+ const exprEnd = scanTemplateExpressionEnd(src, exprStart, view, onComment);+ expressions.push({ start: exprStart, end: exprEnd });+ i = exprEnd < src.length ? exprEnd : src.length;+ }+ }+ return { end: src.length, expressions };+}++/**+ * Blank inert source while leaving executable JavaScript inside template `${...}` expressions.+ *+ * Raw shapes this must separate:+ * `help: navigateTo({ pageId: "PAGEREF_x" })` template TEXT, inert+ * `${navigateTo({ pageId: "PAGEREF_x" })}` template EXPRESSION, executable+ * `${`nested ${navigateTo({ pageId: "PAGEREF_x" })}`}` nested expression, executable+ * `${"navigateTo({ pageId: \"PAGEREF_x\" })"}` string inside expression, inert+ * `${/navigateTo\({ pageId: "PAGEREF_x" }\)/}` regex inside expression, inert+ * `${slash-star navigateTo({ pageId: "PAGEREF_x" }) star-slash real}` comments in expressions are inert+ * `escaped \` and \${ text` escaped template text, inert+ *+ * `blankLiterals` intentionally blanks whole template bodies for declaration/bracket checks. The+ * navigation oracle needs a different view: template text is still data, but `${...}` is live code.+ * This overlays recursively blanked expression bodies back onto the normal blanked output without+ * changing `blankLiterals` for its existing callers.+ */+function blankNonCodePreservingTemplateExpressions(code) {+ const src = String(code || '');+ const out = blankLiterals(src).split('');+ const scratch = src.split(''); // raw copy every `${…}` body below is lexed into+ for (let i = 0; i < src.length; i += 1) {+ if (src[i] !== '`' || out[i] !== '`') continue;+ const { end, expressions } = scanTemplateLiteral(src, i, scratch);+ for (const expr of expressions) {+ // Keep executable substitutions from being concatenated through blanked template text. In+ // `${Xrm.Navigation.navigateTo} text ${({ pageType: "generative", pageId: "PAGEREF_x" })}`+ // the two expressions are independent, but blanking the `${` / `}` delimiters to spaces made+ // call-site regexes see `navigateTo ({ ... })`. A same-length semicolon at the close boundary+ // preserves offsets while making the expression boundary syntactically non-whitespace.+ if (expr.end < out.length && out[expr.end] !== '\n') out[expr.end] = ';';+ const blanked = blankNonCodePreservingTemplateExpressions(src.slice(expr.start, expr.end));+ for (let k = 0; k < blanked.length; k += 1) out[expr.start + k] = blanked[k];+ }+ i = end;+ }return out.join('');}@@ -383,11 +761,257 @@ function blankLiterals(code) {* export default <expr|function|class|async function>* export { P as default } / export { default } from './x'*/-const DEFAULT_EXPORT = /(?:^[ \t]*|[;}][ \t]*)export[ \t]+default[ \t\r\n]+[\w$({[*]/m;+// Identifiers may be non-ASCII (`Página`), so every name below is matched by Unicode property.+const DEFAULT_EXPORT = /(?:^[ \t]*|[;}][ \t]*)export[ \t]+default[ \t\r\n]+[\p{ID_Continue}$({[*]/gmu;const NAMED_DEFAULT_EXPORT = /(?:^[ \t]*|[;}][ \t]*)export[ \t]*\{[^}]*\bdefault\b[^}]*\}/m;function hasDefaultExport(code) {const bare = blankLiterals(code);- return DEFAULT_EXPORT.test(bare) || NAMED_DEFAULT_EXPORT.test(bare);+ if (NAMED_DEFAULT_EXPORT.test(bare)) return true;+ // Any complete one will do: TypeScript overloads declare the signature(s) before the body —+ // export default function f(x: string): string;+ // export default function f(x: any) { return x; }+ for (const m of bare.matchAll(DEFAULT_EXPORT)) {+ if (defaultExportIsComplete(bare, m.index + m[0].length - 1)) return true;+ }+ return false;+}++// A write cut off INSIDE its export statement still matches DEFAULT_EXPORT, and its brackets balance+// because the cut came before any was opened:+// export default function GeneratedComponent(props) the body never came+// export default GeneratedComp cut mid-name+// So a function or class must reach its body, and a bare exported name must be one the module has.+// `at` is where the exported thing starts in `bare` (blanked code, so strings and comments are gone).+function defaultExportIsComplete(bare, at) {+ const rest = bare.slice(at);+ // `async` and `abstract` only modify what follows. Cut right after one, or inside the keyword it+ // modifies (`export default abstract clas`), the export is incomplete. Followed by `;` or a line+ // break instead, the word is a plain exported name (it is a legal identifier), handled below.+ const mod = /^(async|abstract)\b[ \t]*/.exec(rest);+ if (mod) {+ const after = rest.slice(mod[0].length);+ if (!after.trim()) return false;+ if (!/^(?:function|class)\b/.test(after) && !/^(?:;|\r?\n)/.test(after)) {+ // Only an async ARROW is left — `async (x) => …`, `async x => …` — and it needs its `=>` and body.+ return mod[1] === 'async' && /=>/.test(after) && !/=>\s*$/.test(after);+ }+ }+ const fn = /^(?:async[ \t\r\n]+)?function\b\s*\*?\s*(?:[\p{ID_Start}$_][\p{ID_Continue}$\u200c\u200d]*)?\s*/u.exec(rest);+ if (fn) {+ // Type parameters come first and may hold parentheses of their own: `<T extends (a: A) => void>`.+ let k = fn[0].length;+ if (rest[k] === '<') k = skipTypeArguments(rest, k);+ while (k < rest.length && /\s/.test(rest[k])) k += 1;+ if (rest[k] !== '(') return false;+ let depth = 0;+ for (; k < rest.length; k += 1) {+ if (rest[k] === '(') depth += 1;+ else if (rest[k] === ')') { depth -= 1; if (depth === 0) return hasDeclarationBody(rest, k + 1); }+ }+ return false;+ }+ const cls = /^(?:abstract[ \t\r\n]+)?class\b/.exec(rest);+ if (cls) return hasDeclarationBody(rest, cls[0].length);+ const name = /^([\p{ID_Start}$_][\p{ID_Continue}$\u200c\u200d]*)[ \t]*(?:;|\r?\n|$)/u.exec(rest);+ if (!name) {+ // A member chain at EOF is syntactically complete: `export default UI.Spinner` and+ // `export default pages.Home` are valid exports whether the base is imported or local. A cut at+ // `React.memo` before its call is a known syntactically-complete limit documented for this gate;+ // only truly dangling `React.` / `React?.` tails stay rejected by DANGLING_TAIL below.+ const member = /^([\p{ID_Start}$_][\p{ID_Continue}$]*)(?:\s*\??\.\s*[\p{ID_Start}$_][\p{ID_Continue}$]*)+[ ]*$/u.exec(rest);+ if (member) return true;+ // So is an arrow's parameter list with the arrow cut off — `export default ()`,+ // `(props: { a: string })`, `(props): JSX.Element` of `export default (props) => <div/>;` —+ // when the group cannot be an expression: empty, spreading at its own level, annotating a type at+ // its own level, or followed by a return type (after a leading group a `:` can only start one; a+ // ternary needs its `?` first). Such a group is parameters, so an `=>` must follow. A ternary's+ // `:` inside the group is not an annotation, nor is a return type's, which follows `)`. A bare+ // `(props)` reads exactly like the valid `export default (GeneratedComponent)`, so it passes; so+ // does a parenthesized function or class.+ if (rest[0] === '(' && !/^\(\s*(?:async\s+)?(?:function|class)\b/.test(rest)) {+ let depth = 0;+ let annotated = false;+ let ternary = false;+ let spread = false;+ for (let k = 0; k < rest.length; k += 1) {+ const c = rest[k];+ if (c === '(' || c === '[' || c === '{') depth += 1;+ else if (c === ')' || c === ']' || c === '}') {+ if (--depth > 0) continue;+ if (c === ')') {+ const inner = rest.slice(1, k).trim();+ const params = !inner || spread || (annotated && !ternary) || /^\s*:/.test(rest.slice(k + 1));+ if (params && !/=>/.test(rest.slice(k + 1))) return false;+ }+ break;+ } else if (depth === 1 && c === '.' && rest.startsWith('...', k)) {+ spread = true;+ k += 2;+ } else if (depth === 1 && c === ':') {+ let p = k - 1;+ while (p >= 0 && /\s/.test(rest[p])) p -= 1;+ if (rest[p] !== ')') annotated = true;+ } else if (depth === 1 && c === '?' && rest[k + 1] !== ':' && rest[k + 1] !== '.') ternary = true;+ }+ }+ // Any other expression — `memo(Page)`, `(props) => …`, `{ … }` — is taken as written (its brackets+ // are checked separately), unless it stops at a token that needs more: `React.`, `Page as`,+ // `cond ?`, `a &&`, an arrow's `=>`.+ return !DANGLING_TAIL.test(rest) && !/(?<![\p{ID_Continue}$])(?:as|satisfies|keyof)\s*$/u.test(rest);+ }+ // `export default GeneratedComponent;` — the module must declare or import the name.+ return declaresName(bare, name[1]);+}++// True when `name` is a local object binding. This is narrower than declaresName on purpose:+// `export default pages.Home` is complete when `pages` is an object literal, but `React.memo` at EOF+// is usually a truncated call on an imported namespace and remains rejected.+function declaresObjectName(bare, name) {+ const w = `(?<![\\p{ID_Continue}$])${name.replace(/\$/g, '\\$')}(?![\\p{ID_Continue}$])`;+ return new RegExp(`(?<![\\p{ID_Continue}$.])(?:const|let|var)\\s+${w}\\s*=\\s*\\{`, 'u').test(bare);+}++// True when `bare` (blanked code) DECLARES or imports `name` — not merely mentions it:+// const|let|var|function|class|enum|interface|type|namespace NAME+// import NAME from … import * as NAME from … import { A as NAME, NAME } from …+// const { a: NAME, NAME = 1, ...NAME } = … const [NAME, , NAME] = …+// A parameter, a property or a call argument is not a binding the module can export — and neither is+// the `as` of `import * as React`, which let a write cut two characters into `export default async`+// pass as `export default as`.+function declaresName(bare, name) {+ const w = `(?<![\\p{ID_Continue}$])${name.replace(/\$/g, '\\$')}(?![\\p{ID_Continue}$])`;+ const direct = new RegExp(`(?<![\\p{ID_Continue}$.])(?:(?:const|let|var|class|enum|interface|type|namespace)\\s+|function\\s*\\*?\\s*|import\\s+(?:type\\s+)?|\\*\\s*as\\s+)${w}`, 'u');+ if (direct.test(bare)) return true;+ const group = /(?<![\p{ID_Continue}$.])(?:import|const|let|var)\s*(?:type\s+)?(?:[\p{ID_Start}$_][\p{ID_Continue}$]*\s*,\s*)?([{[])/gu;+ for (const m of bare.matchAll(group)) {+ if (bindsInGroup(bare, m.index + m[0].length - 1, w, name)) return true;+ }+ // A later declarator of a list — `const Header = () => null, GeneratedComponent = () => null;` —+ // follows a `,` at the list's own depth, before its `;` (or the block that holds it closes). A+ // `const` declarator always has an initializer, so `, NAME` followed by neither `=` nor a type+ // annotation is not one. (A type with no `=` after it is a syntax error the build reports; a cut+ // cannot produce one, since the rest of the file still follows.) A `let` / `var` declarator may+ // stand alone, or assert `NAME!: T`. A later declarator may also be a pattern:+ // `const a = 1, { GeneratedComponent } = lib;`.+ const list = /(?<![\p{ID_Continue}$.])(const|let|var)\s/gu;+ const declarator = new RegExp(`\\s*${w}\\s*(?:!\\s*:|[=:,;\\n]|$)`, 'uy');+ const constDeclarator = new RegExp(`\\s*${w}\\s*[=:]`, 'uy');+ const pattern = /\s*[{[]/y;+ for (const m of bare.matchAll(list)) {+ const re = m[1] === 'const' ? constDeclarator : declarator;+ let depth = 0;+ for (let k = m.index + m[0].length; k < bare.length; k += 1) {+ const c = bare[k];+ if (c === '(' || c === '[' || c === '{') depth += 1;+ else if (c === ')' || c === ']' || c === '}') { if (--depth < 0) break; }+ else if (depth === 0 && c === ';') break;+ else if (depth === 0 && c === ',') {+ re.lastIndex = k + 1;+ if (re.test(bare)) return true;+ pattern.lastIndex = k + 1;+ if (pattern.test(bare) && bindsInGroup(bare, pattern.lastIndex - 1, w, name)) return true;+ }+ }+ }+ return false;+}++// True when the import `{…}` or destructuring `{…}` / `[…]` opening at `open` binds the name `w`+// matches. A binding is followed by `,`, the closing bracket, a default `=` or nothing — so neither+// `NAME:` (a key), `NAME as X` (renamed away), the keywords of `{ A as B }` / `{ type A }`, nor a+// computed key `{ [NAME]: x }` counts; only in an array pattern does `]` end a binding.+function bindsInGroup(bare, open, w, name) {+ const close = matchingBracket(bare, open);+ if (close === -1) return false;+ const inner = bare.slice(open + 1, close);+ for (const hit of inner.matchAll(new RegExp(w, 'gu'))) {+ const after = inner.slice(hit.index + name.length);+ if (/^\s*(?:[,}\]]|=(?![=>])|$)/.test(after) && !/^\s*\]\s*:/.test(after)) return true;+ }+ return false;+}++// Index of the bracket that closes the `{` or `[` at `open`, or -1. Only that bracket kind is+// counted; `bare` is blanked, so none hides in a string or comment.+function matchingBracket(bare, open) {+ const o = bare[open];+ const c = o === '{' ? '}' : ']';+ let depth = 0;+ for (let k = open; k < bare.length; k += 1) {+ if (bare[k] === o) depth += 1;+ else if (bare[k] === c && --depth === 0) return k;+ }+ return -1;+}++// Index just past the `>` that closes the type-argument list opening at `k` (the `>` of an `=>`+// inside it does not count), or rest.length when none does.+function skipTypeArguments(rest, k) {+ let angle = 0;+ for (; k < rest.length; k += 1) {+ if (rest[k] === '<') angle += 1;+ else if (rest[k] === '>' && rest[k - 1] !== '=') { angle -= 1; if (angle === 0) return k + 1; }+ }+ return rest.length;+}++// Tokens after which a `{` opens an object TYPE, not the declaration's body:+// (props): { id: string } { the first group is the return type, the second the body+// extends React.Component<{ id: string }> { inside type arguments+// (): A | { b: 1 } { (): () => { c: 1 } { (x): x is { d: 1 } {+const TYPE_EXPECTED = new Set([':', '|', '&', ',', '?', '=>', 'extends', 'implements', 'keyof', 'typeof', 'infer', 'is', 'asserts', 'readonly', 'unique']);+// A word that can only start a STATEMENT: met before the body, the declaration ended without one —+// export default function GeneratedComponent()+// if (ready) { … }+// (`new` and `import` are left out: both can appear in a type, `new () => T`, `import("./x").T`.)+const STATEMENT_WORDS = new Set(['if', 'else', 'try', 'catch', 'finally', 'for', 'while', 'do', 'switch', 'with', 'return', 'throw', 'break', 'continue', 'debugger', 'const', 'let', 'var', 'function', 'class', 'interface', 'enum', 'namespace', 'module', 'declare', 'export']);++// True when a declaration's body `{` follows `from` — after the parameter list of a function, or the+// `class` keyword. A `;`, a bare `=` or a statement keyword before it means the declaration ended+// without one.+function hasDeclarationBody(rest, from) {+ let paren = 0;+ let angle = 0;+ let bracket = 0;+ let prev = ')'; // the token before `from`+ for (let k = from; k < rest.length; k += 1) {+ const c = rest[k];+ if (/\s/.test(c)) continue;+ const nested = paren > 0 || angle > 0 || bracket > 0;+ if (c === '{') {+ if (!nested && !TYPE_EXPECTED.has(prev)) return true;+ // An object type (or a brace inside a type argument or parameter list): skip the whole group.+ let depth = 0;+ for (; k < rest.length; k += 1) {+ if (rest[k] === '{') depth += 1;+ else if (rest[k] === '}') { depth -= 1; if (depth === 0) break; }+ }+ if (k >= rest.length) return false;+ prev = '}';+ continue;+ }+ if (/[\p{ID_Continue}$]/u.test(c)) {+ let j = k;+ while (j < rest.length && /[\p{ID_Continue}$]/u.test(rest[j])) j += 1;+ prev = rest.slice(k, j);+ // A statement word — unless reached as a property of a qualified type: `(): Schema.module {`.+ let p = k - 1;+ while (p >= 0 && /\s/.test(rest[p])) p -= 1;+ if (!nested && STATEMENT_WORDS.has(prev) && rest[p] !== '.') return false;+ k = j - 1;+ continue;+ }+ if (c === '=' && rest[k + 1] === '>') { prev = '=>'; k += 1; continue; }+ if (!nested && (c === ';' || c === '=')) return false;+ if (c === '(') paren += 1;+ else if (c === ')') paren = Math.max(0, paren - 1);+ else if (c === '<') angle += 1;+ else if (c === '>') angle = Math.max(0, angle - 1);+ else if (c === '[') bracket += 1;+ else if (c === ']') bracket = Math.max(0, bracket - 1);+ prev = c;+ }+ return false;}/**@@ -407,4 +1031,107 @@ function hasUnbalancedBrackets(code) {return stack.length > 0;}-module.exports = { blankLiterals, hasDefaultExport, hasUnbalancedBrackets, expressionPosition };+// A token that cannot end a module: an operator, `.` / `?.`, `,` / `?` / `:`, an arrow's `=>`, or a+// reserved word that needs what follows — an operand, or the rest of its statement (`export`,+// `const`, `function`, `if`, …). `x++` and `x!` can end one, and so can `>` (a JSX tag), `/` (the end+// of a regex) and `debugger`, so none of those is on the list. A word reached through `.` is a+// property (`counts.new`, `api.delete`), and `void` is left off because it is also a complete TYPE:+// `type Handler = (e: Event) => void`.+const DANGLING_TAIL = /(?:=>|\?\.|[.,?:=&|^~*%<]|(?<!\+)\+|(?<!-)-|(?<![\p{ID_Continue}$.])(?:new|typeof|delete|await|yield|in|instanceof|extends|export|import|default|const|let|var|function|class|interface|enum|return|throw|if|else|for|while|do|switch|case|try|catch|finally|with))\s*$/u;++/**+ * True when `code` stops mid-statement: inside a string, template, comment or JSX element, or right+ * after a token that needs more. Every bracket balances in+ * export default () => <div>Loading const note = `unfinished const total = count *+ * so hasUnbalancedBrackets cannot see these cuts. A complete module ends in plain code.+ */+function endsMidStatement(code) {+ const src = String(code || '');+ const out = src.split('');+ const regexEnds = new Set();+ const jsxTagEnds = new Set();+ let open = false;+ lexInto(src, out, 0, { onRegexEnd: (index) => regexEnds.add(index), onJsxTagEnd: (index) => jsxTagEnds.add(index), onEnd: (end) => { open = end.open; } });+ const bare = out.join('');+ return open || DANGLING_TAIL.test(bare) || hasDanglingFinalOperator(out, regexEnds, jsxTagEnds);+}++function hasDanglingFinalOperator(out, regexEnds, jsxTagEnds) {+ const { ch, index } = prevSignificant(out, out.length);+ if (ch === '>') return !jsxTagEnds.has(index);+ if (ch === '/') return !regexEnds.has(index);+ if (ch === '!') return expressionPosition(out, index);+ return false;+}++/**+ * The comments in TSX source, found by the same lexer as blankLiterals — so a `//` inside a string,+ * template or JSX text ("https://…", "a // b") is never taken for one.+ * @param {string} code+ * @returns {{ start: number, end: number, text: string }[]}+ */+function commentRanges(code) {+ const src = String(code || '');+ const ranges = [];+ blankLiterals(src, { onComment: (start, end) => ranges.push({ start, end, text: src.slice(start, end) }) });+ return ranges;+}++/**+ * The first marker showing a generator ELIDED or DEFERRED code instead of writing it, or null. One rule+ * for every gate that asks "is this page complete?" — the genpage evals and the worker-output check+ * before a parallel page is accepted — so they cannot disagree about the same file.+ *+ * Raw shapes, each matched only where it can mean elision:+ * // TODO: wire the save handler a TODO/FIXME comment+ * // ... rest of the component a comment that opens with an ellipsis+ * /* ... *\/ the same, as a block comment+ * ... a bare line standing in for code+ * The same words in a string or JSX text are UI copy, never elision: "Loading…" and "Search+ * documents…" appear in committed samples and in real captured pages, and 'TODO' is an ordinary+ * status value on a task board.+ * @param {string} code+ * @returns {string|null}+ */+function findElisionMarker(code) {+ const src = String(code || '');+ for (const { text } of commentRanges(src)) {+ // The comment without its delimiters, or a JSDoc block's leading `*` on each line — so+ // /**+ // * TODO implement save+ // */+ // opens with TODO, as `// TODO implement save` does.+ const body = text.replace(/^\/\/+|^\/\*+|\*+\/$/g, '').replace(/^[ \t]*\*+/gm, '').trim();+ // FIXME is never prose, in any case. TODO is — a status on a task board ("board order: TODO ->+ // IN_PROGRESS -> DONE", "each todo: title, due date and owner") — so it counts only as a marker:+ // opening the comment (`// TODO wire paging`, or `// Todo:` in any case with its colon), or+ // written `TODO:` inside one.+ if (/\bfixme\b/i.test(body) || /^TODO\b/.test(body) || /^todo\s*:/i.test(body) || /\bTODO\s*:/.test(body)) {+ return 'a TODO/FIXME comment';+ }+ if (/^(\.\.\.|…)/.test(body)) return 'a comment that elides code (`// ...`)';+ // The one phrasing that only ever stands in for code. "The rest of the file/code" is not on this+ // list: "upload the rest of the file in 4 MB chunks" is how a file-handling page describes itself.+ if (/\bomitted for brevity\b/i.test(body)) return 'a comment that elides code ("omitted for brevity")';+ }+ // Comments and strings are blanked here, but executable `${...}` template bodies are kept: an+ // ellipsis inside an IIFE in a template is code, not template text. A line holding only `...`+ // always fails closed as a placeholder. The text alone cannot reliably distinguish every legal+ // multiline spread/rest from an elided block without a full parser, so generated code must write+ // the spread and operand together: `...rows`, not `...` followed by `rows` on the next line.+ if (bareEllipsisElidesCode(blankNonCodePreservingTemplateExpressions(src))) return 'a bare `...` line standing in for code';+ return null;+}++function bareEllipsisElidesCode(mask) {+ return /^[ ]*(\.\.\.|…)[ ]*$/m.test(mask);+}+function ellipsisFollowedByStatement(mask, k) {+ if (!/[\w$]/.test(mask[k])) return false;+ let j = k;+ while (j < mask.length && /[\w$]/.test(mask[j])) j += 1;+ const word = mask.slice(k, j);+ return STATEMENT_WORDS.has(word) || word === 'import' || word === 'export';+}++module.exports = { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, expressionPosition, scanTemplateExpressionEnd };diff --git a/plugins/model-apps/scripts/list-connections.js b/plugins/model-apps/scripts/list-connections.jsindex 1b8b1f75c..15fb79c69 100644--- a/plugins/model-apps/scripts/list-connections.js+++ b/plugins/model-apps/scripts/list-connections.js@@ -57,15 +57,28 @@ function extractConnectorId(connectionId) {return match ? match[1] : '';}+function usableConnection(row) {+ return Boolean(row.connectorId && row.connectionId);+}++function usableConnectionRows(rows, source) {+ const usable = rows.filter(usableConnection);+ if (rows.length && !usable.length) {+ throw new Error(`pac connection list ${source} contained ${rows.length} row(s), but no usable connection rows with both connection and connector identifiers`);+ }+ return usable;+}+function parseJsonConnections(raw) {+ let parsed;try {- const parsed = JSON.parse(raw);- const rows = Array.isArray(parsed) ? parsed : parsed?.value;- if (!Array.isArray(rows)) return null;- return rows.map(mapConnectionRow).filter((row) => row.connectorId || row.connectionId || row.displayName);+ parsed = JSON.parse(raw);} catch {return null;}+ const rows = Array.isArray(parsed) ? parsed : parsed?.value;+ if (!Array.isArray(rows)) return null;+ return usableConnectionRows(rows.map(mapConnectionRow), 'JSON');}function parseFixedWidthTable(raw) {@@ -83,7 +96,7 @@ function parseFixedWidthTable(raw) {end: matches[index + 1]?.index,}));- return lines+ return usableConnectionRows(lines.slice(separatorIndex + 1).filter((line) => line.trim() && !/^-+$/.test(line.trim())).map((line) => {@@ -92,8 +105,7 @@ function parseFixedWidthTable(raw) {row[range.name] = line.slice(range.start, range.end).trim();}return mapConnectionRow(row);- })- .filter((row) => row.connectorId || row.connectionId || row.displayName);+ }), 'fixed-width table');}function parseWhitespaceTable(raw) {@@ -107,18 +119,22 @@ function parseWhitespaceTable(raw) {// with no dashed separator. Names may contain spaces, so splitting each row on// whitespace loses the boundary. The connector API path is the stable delimiter.if (normalizedHeaders.join(',') === 'id,name,apiid,status') {- return lines+ // Every connection row in this layout carries its connector's API path, so a line that does too but does+ // not match is a connection row read wrong — a changed column layout, say. It is kept as a row with no+ // ids, so usableConnectionRows fails closed when no row has both, where dropping it read the listing as+ // "no connections"; beside a usable row it is dropped. A line WITHOUT the path is not a connection at all+ // — a message such as "No connections found.", a notice, the wrapped tail of a long name — and is+ // dropped. The Status column may be several words ("Not connected"), or empty.+ return usableConnectionRows(lines.slice(headerIndex + 1)- .map((line) => line.match(/^(\S+)\s+(.+?)\s+(\/providers\/Microsoft\.PowerApps\/apis\/\S+)\s+(\S+)\s*$/i))- .filter(Boolean)- .map((match) => mapConnectionRow({- Id: match[1],- Name: match[2],- 'API Id': match[3],- Status: match[4],- }));+ .map((line) => {+ const match = line.match(/^(\S+)\s+(.+?)\s+(\/providers\/Microsoft\.PowerApps\/apis\/\S+)(?:\s+(.+?))?\s*$/i);+ if (match) return mapConnectionRow({ Id: match[1], Name: match[2], 'API Id': match[3], Status: match[4] || '' });+ return /\/providers\/Microsoft\.PowerApps\/apis\//i.test(line) ? { connectorId: '', connectionId: '', displayName: line.trim() } : null;+ })+ .filter(Boolean), 'Id/Name/API Id table');}- return lines+ return usableConnectionRows(lines.slice(headerIndex + 1).filter((line) => !/^-+$/.test(line.trim())).map((line) => {@@ -128,8 +144,7 @@ function parseWhitespaceTable(raw) {row[header] = values[index] || '';});return mapConnectionRow(row);- })- .filter((row) => row.connectorId || row.connectionId || row.displayName);+ }), 'whitespace table');}function parsePacConnectionList(raw) {diff --git a/plugins/model-apps/scripts/promote-intent-pages.js b/plugins/model-apps/scripts/promote-intent-pages.jsindex c138264c6..e374478b3 100644--- a/plugins/model-apps/scripts/promote-intent-pages.js+++ b/plugins/model-apps/scripts/promote-intent-pages.js@@ -22,7 +22,7 @@ const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/datconst { migrateAppSpec } = require('./lib/app-spec.js');const { pageKey, pageFile } = require('./lib/page-plan.js');const { navReferencedKeys, navMalformedRefs, navTargetParity } = require('./lib/pageref-resolver.js');-const { hasDefaultExport, hasUnbalancedBrackets } = require('./lib/source-literals.js');+const { blankLiterals, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets } = require('./lib/source-literals.js');// A generated page must be a real React module. We deliberately do NOT typecheck here (the plugin// ships with no dependencies, so there is no TS parser to call, and typechecking is the build's@@ -30,8 +30,8 @@ const { hasDefaultExport, hasUnbalancedBrackets } = require('./lib/source-litera// truncated write, or prose returned instead of code.//// Every check runs over literal-blanked source (see lib/source-literals.js). A substring search —-// even one over pageref-resolver's stripNonCode, which deliberately PRESERVES ordinary string-// bodies — accepted prose that merely MENTIONS an export:+// even one over a copy that deliberately PRESERVES ordinary string bodies — accepted prose that+// merely MENTIONS an export:// /* export default */ -> promoted// const prose = "export default GeneratedComponent"; -> promoted// Promotion is sticky (the page is then marked implemented and skipped on the next run), so a@@ -45,9 +45,18 @@ function structuralProblems(code) {if (hasUnbalancedBrackets(code)) {out.push('unbalanced brackets — the file looks truncated');}- // A worker that answers in prose usually still opens a fence; a real .tsx never contains one.- // Both CommonMark fence markers count.- if (/^\s*(```|~~~)/m.test(code)) out.push('contains a markdown code fence — the worker returned prose, not a module');+ // A cut that leaves every bracket balanced: inside JSX, a template or a comment, or after `a +`.+ if (endsMidStatement(code)) out.push('stops mid-statement — the file looks truncated');+ // A worker that answers in prose usually still opens a fence; a real .tsx never has one in CODE.+ // Both CommonMark fence markers count. On the blanked source, as genpage-worker-output.js checks it: a+ // fence inside a template literal (a page rendering markdown help) is data, and refusing it here made the+ // two gates disagree about the same page.+ if (/^\s*(```|~~~)/m.test(blankLiterals(code))) out.push('contains a markdown code fence — the worker returned prose, not a module');+ // Elided code — `// TODO: …`, `// ...`, "omitted for brevity" — the same shared rule the worker gate and+ // Layer 2 apply. Promotion checked only the structure, so a page that elided its body was promoted and+ // went on through /app-builder.+ const elision = findElisionMarker(code);+ if (elision) out.push(`contains ${elision} — the page is incomplete`);return out;}diff --git a/plugins/model-apps/scripts/tests/add-page-to-solution.test.js b/plugins/model-apps/scripts/tests/add-page-to-solution.test.jsindex 6521c32fa..6ffc820d4 100644--- a/plugins/model-apps/scripts/tests/add-page-to-solution.test.js+++ b/plugins/model-apps/scripts/tests/add-page-to-solution.test.js@@ -128,7 +128,7 @@ test('the appmodule is packaged BEFORE any page or connection reference', async});test('a connection reference that does not exist fails the run instead of packaging a partial solution', async () => {- const { cli, emitted } = harness({+ const { cli, calls, emitted } = harness({argv: [ENV, 'sol', 'app-1', '--connection-refs', 'new_missing'],refLookup: (requestPath) =>requestPath.includes("EntityDefinitions(LogicalName='connectionreference')")@@ -138,6 +138,34 @@ test('a connection reference that does not exist fails the run instead of packagawait cli.main();assert.equal(emitted[0].ok, false);assert.match(String(emitted[0].payload.message || emitted[0].payload), /new_missing.*not found/);+ assert.equal(+ calls.filter((call) => call.path === 'AddSolutionComponent').length,+ 0,+ 'missing connection references must be validated before any solution mutation',+ );+});++test('all requested connection references are validated before adding the app or pages', async () => {+ const { cli, calls, emitted } = harness({+ argv: [ENV, 'sol', 'app-1', '--page-ids', 'p1,p2', '--connection-refs', 'new_missing'],+ refLookup: (requestPath) => {+ if (requestPath.includes("EntityDefinitions(LogicalName='uxagentproject')")) {+ return { status: 200, data: { ObjectTypeCode: 10372 } };+ }+ if (requestPath.includes("EntityDefinitions(LogicalName='connectionreference')")) {+ return { status: 200, data: { ObjectTypeCode: 10158 } };+ }+ return { status: 200, data: { value: [] } };+ },+ });+ await cli.main();+ assert.equal(emitted[0].ok, false);+ assert.match(String(emitted[0].payload.message || emitted[0].payload), /new_missing.*not found/);+ assert.deepEqual(+ calls.filter((call) => call.path === 'AddSolutionComponent'),+ [],+ 'a failed connection-reference lookup must leave app and pages unmodified',+ );});test('a connection reference logical name with a quote is OData-escaped, not injected', async () => {diff --git a/plugins/model-apps/scripts/tests/generate-page-manifest.test.js b/plugins/model-apps/scripts/tests/generate-page-manifest.test.jsindex 4c2493b85..f93ac07f4 100644--- a/plugins/model-apps/scripts/tests/generate-page-manifest.test.js+++ b/plugins/model-apps/scripts/tests/generate-page-manifest.test.js@@ -154,7 +154,10 @@ test('CLI: writes package.json and genpage.d.ts to working dir', () => {test('CLI: idempotent — does NOT overwrite without --force', () => {const dir = mkdirTemp();try {- fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"already-here"}');+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify(buildPackageJson('already-here', []), null, 2) + '\n'+ );const r = runScript([dir, 'my-page']);assert.equal(r.code, 0);const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));@@ -191,6 +194,119 @@ test('CLI: --features charts includes d3 in written package.json', () => {}});+test('CLI: rerunning with a new feature refuses a stale package.json instead of reporting success', () => {+ const dir = mkdirTemp();+ try {+ const first = runScript([dir, 'chart-page']);+ assert.equal(first.code, 0);++ const second = runScript([dir, 'chart-page', '--features', 'charts']);+ assert.equal(second.code, 2);+ assert.match(second.stderr, /package\.json/);+ assert.match(second.stderr, /d3/);+ assert.match(second.stderr, /--force/);++ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));+ assert.equal(pkg.dependencies.d3, undefined, 'existing package.json must not be silently overwritten');+ assert.equal(pkg.devDependencies['@types/d3'], undefined, 'existing package.json must not be silently overwritten');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++// Windows PowerShell's `Set-Content -Encoding UTF8` writes a byte-order mark, which npm reads fine and JSON.parse+// refuses — so a valid package.json halted every rerun. It is read without the mark, and left as it is.+test('CLI: an existing package.json saved with a UTF-8 byte-order mark is read, and left as it is', () => {+ const dir = mkdirTemp();+ try {+ assert.equal(runScript([dir, 'bom-page']).code, 0);+ const file = path.join(dir, 'package.json');+ const withBom = `\uFEFF${fs.readFileSync(file, 'utf8')}`;+ fs.writeFileSync(file, withBom, 'utf8');+ const again = runScript([dir, 'bom-page']);+ assert.equal(again.code, 0, again.stderr);+ assert.equal(fs.readFileSync(file, 'utf8'), withBom, 'the file is not rewritten');+ // CONTROL: a manifest broken past the mark is still refused.+ fs.writeFileSync(file, '\uFEFF{ not json', 'utf8');+ const broken = runScript([dir, 'bom-page']);+ assert.equal(broken.code, 2);+ assert.match(broken.stderr, /could not be parsed/);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++// A package.json whose dependencies cannot be checked is not proof the page's dependencies are there.+test('CLI: an existing package.json that cannot be verified is refused, not skipped as fine', () => {+ const dir = mkdirTemp();+ try {+ // Unparseable: nothing proves it has the dependencies, but --force can regenerate a regular file.+ fs.writeFileSync(path.join(dir, 'package.json'), '{ "name": "half-written",');+ const broken = runScript([dir, 'broken-page']);+ assert.equal(broken.code, 2);+ assert.match(broken.stderr, /could not be parsed[\s\S]*--force/);+ assert.equal(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'), '{ "name": "half-written",', 'left as it was');+ // Not a regular file: never read or written through, and --force is not offered as a way out.+ fs.rmSync(path.join(dir, 'package.json'));+ fs.mkdirSync(path.join(dir, 'package.json'));+ const odd = runScript([dir, 'odd-page']);+ assert.equal(odd.code, 2);+ assert.match(odd.stderr, /is a directory[\s\S]*replace it with a regular file/);+ assert.doesNotMatch(odd.stderr, /--force/);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++// A dependency whose value npm cannot use — null, an object, an empty string — installs nothing, so it is+// missing, not drifted: the stale-manifest gate refuses it instead of reporting success over it. A usable+// entry for the same package in the other section still counts.+test('CLI: a dependency with no usable version counts as missing', () => {+ for (const bad of [null, {}, '', ' ']) {+ const dir = mkdirTemp();+ try {+ const pkg = buildPackageJson('odd-deps', []);+ const [name] = Object.keys(pkg.dependencies);+ pkg.dependencies[name] = bad;+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(pkg, null, 2) + '\n');+ const r = runScript([dir, 'odd-deps']);+ assert.equal(r.code, 2, `${JSON.stringify(bad)}: ${r.stdout}`);+ assert.match(r.stderr, new RegExp(`missing requested generated-page dependencies: dependencies\\.${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}=`), JSON.stringify(bad));+ // CONTROL: the same package, usable in the other section, satisfies it.+ pkg.devDependencies[name] = buildPackageJson('x', []).dependencies[name];+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(pkg, null, 2) + '\n');+ assert.equal(runScript([dir, 'odd-deps']).code, 0, `${JSON.stringify(bad)} beside a usable entry`);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ }+});++// A version the user pinned or bumped is their edit, not staleness: failing on it would make every+// rerun fail unless --force threw the edit away. It is kept, and reported, so an old pin is visible.+test('CLI: a package present at a different version is kept and reported, not refused', () => {+ const dir = mkdirTemp();+ try {+ const pkg = buildPackageJson('pinned-page', []);+ const [name] = Object.keys(pkg.dependencies);+ pkg.dependencies[name] = '0.0.1-user-pin';+ // A package the user moved to the other section still installs, so it still counts as present.+ const [devName] = Object.keys(pkg.devDependencies);+ pkg.dependencies[devName] = pkg.devDependencies[devName];+ delete pkg.devDependencies[devName];+ const body = JSON.stringify(pkg, null, 2) + '\n';+ fs.writeFileSync(path.join(dir, 'package.json'), body);+ const r = runScript([dir, 'pinned-page']);+ assert.equal(r.code, 0, r.stderr);+ assert.equal(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'), body, 'the user\'s edits are untouched');+ const out = JSON.parse(r.stdout);+ assert.equal(out.files['package.json'].wrote, false);+ assert.deepEqual(out.files['package.json'].versionDrift, [`${name} 0.0.1-user-pin (generated pages expect ${buildPackageJson('x', []).dependencies[name]})`]);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});+test('CLI: stdout is valid JSON summary', () => {const dir = mkdirTemp();try {@@ -525,12 +641,12 @@ test('without --force a hard-linked existing file is skipped, and the run stillconst work = fs.mkdtempSync(path.join(os.tmpdir(), 'gpm-hlskip-'));try {const victim = path.join(outside, 'precious.json');- fs.writeFileSync(victim, '{"keep":true}');+ fs.writeFileSync(victim, JSON.stringify(buildPackageJson('already-here', []), null, 2) + '\n');try { fs.linkSync(victim, path.join(work, 'package.json')); }catch { return t.skip('cannot create a hard link on this filesystem'); }const r = runScript([work, 'probe-page']);assert.strictEqual(r.code, 0, `a run without --force must not fail on an existing file; stderr: ${r.stderr}`);- assert.strictEqual(fs.readFileSync(victim, 'utf8'), '{"keep":true}', 'the linked file is untouched');+ assert.strictEqual(JSON.parse(fs.readFileSync(victim, 'utf8')).name, 'already-here', 'the linked file is untouched');assert.ok(fs.existsSync(path.join(work, 'genpage.d.ts')), 'and the other output is still written');return undefined;} finally {diff --git a/plugins/model-apps/scripts/tests/genpage-command-quoting.test.js b/plugins/model-apps/scripts/tests/genpage-command-quoting.test.jsnew file mode 100644index 000000000..a2f5227ae--- /dev/null+++ b/plugins/model-apps/scripts/tests/genpage-command-quoting.test.js@@ -0,0 +1,114 @@+'use strict';+// /genpage's commands are run by an AI that substitutes each `<…>` placeholder as TEXT, then hands the line to+// PowerShell or bash. A double-quoted value was expanded before the script ran (`"Revenue $100"` arrived as+// `Revenue `, and a `$` in a parent folder's name changed the path), and a bare one split on a space+// (`--code-file D:\Work Projects\…` became two arguments). So every `<…>` value in a command template is+// single-quoted — the rule stated once under "Instructions" in skills/genpage/SKILL.md. Nothing executes these+// templates in a test, so without this a template could drift back unseen.+const { test } = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');++const DIR = path.join(__dirname, '..', '..', 'skills', 'genpage');+const FILES = ['SKILL.md', 'edit-flow.md', 'verify-flow.md'];++// The command text of a skill document, line by line:+// - every line of a ```powershell / ```bash block, except comments and the body of a single-quoted here-string+// (`$prompt = @'` … `'@`), which is data, not command text;+// - every inline code span, anywhere else (a ```markdown log format included), that starts like a command:+// `--flag …`, `node …`, `pac …`, or a lowercase command word followed by a flag, a placeholder, a quote, a `$` or+// a path (`mkdir -p <folder-name>`, `upload --page-id <id>`). JSON examples (`{ "intent": "<need>" }`), a+// `key: value` snippet and prose (`Replaced PAGEREF_<name> tokens`) are not commands. A span that wraps onto the+// next source line, as soft-wrapped prose and quotes do, is read whole (a quote's `>` dropped), and the line it+// wrapped onto is not read again on its own.+const INLINE_COMMAND = /`((?:--|node |pac |[a-z][\w.-]*\s+[-<'"$./\\])[^`]*)`/g;+function commandText(text) {+ const out = [];+ const lines = text.split(/\r?\n/);+ const unquote = (l) => l.replace(/^\s*>\s?/, '');+ let fence = null;+ let hereString = false;+ for (let i = 0; i < lines.length; i += 1) {+ const line = lines[i];+ const open = /^\s*```(\w*)/.exec(line);+ if (open) { fence = fence === null ? (open[1] || 'plain') : null; hereString = false; continue; }+ if (fence !== null && /^(powershell|pwsh|bash|sh)$/.test(fence)) {+ if (hereString) { if (/^\s*'@/.test(line)) hereString = false; continue; }+ if (/@'\s*$/.test(line)) hereString = true;+ if (!/^\s*#/.test(line)) out.push({ n: i + 1, code: line });+ continue;+ }+ let joined = line;+ let k = i;+ while ((joined.split('`').length - 1) % 2 === 1 && k + 1 < lines.length && k - i < 3 && lines[k + 1].trim() && !/^\s*```/.test(lines[k + 1])) {+ k += 1;+ joined += ` ${unquote(lines[k]).trim()}`;+ }+ for (const m of joined.matchAll(INLINE_COMMAND)) out.push({ n: i + 1, code: m[1] });+ i = k;+ }+ return out;+}++test('every <…> value in a /genpage command template is single-quoted, never double-quoted or bare', () => {+ const bad = [];+ for (const f of FILES) {+ for (const { n, code } of commandText(fs.readFileSync(path.join(DIR, f), 'utf8'))) {+ if (/"@?<[^"]*>[^"]*"/.test(code)) bad.push(`${f}:${n}: double-quoted: ${code.trim()}`);+ else if (/(?:^|[\s(])<[A-Za-z][^<>'"\s]*>/.test(code)) bad.push(`${f}:${n}: bare: ${code.trim()}`);+ }+ }+ assert.deepEqual(bad, []);+});++// Free text reaches a script only through a file the skill writes with its file tool. A here-string in a command block+// would carry it as code: a single-quoted one ends at a line that begins with `'@` (or `‘@`, `’@`), and the rest of that+// line runs — so no command block may open one.+test('no /genpage command block carries text in a here-string', () => {+ const bad = [];+ for (const f of FILES) {+ let fence = null;+ fs.readFileSync(path.join(DIR, f), 'utf8').split(/\r?\n/).forEach((line, i) => {+ const open = /^\s*```(\w*)/.exec(line);+ if (open) { fence = fence === null ? (open[1] || 'plain') : null; return; }+ if (fence !== null && /^(powershell|pwsh|bash|sh)$/.test(fence) && /@['"\u2018\u2019\u201c\u201d]\s*$|<<-?\s*['"]?\w+['"]?\s*$/.test(line)) {+ bad.push(`${f}:${i + 1}: ${line.trim()}`);+ }+ });+ }+ assert.deepEqual(bad, []);+});++test('the command-text reader sees what it guards', () => {+ const doc = [+ '```powershell',+ '# a comment with "<x>" is not a command',+ "$prompt = @'",+ 'Build a page for "<customer>" and <orders>',+ "'@",+ 'node x.js --plan "<working-dir>/plan.md"',+ 'node x.js --code-file <working-dir>/a.tsx',+ "node x.js --file '<working-dir>/a.tsx'",+ '```',+ 'Prose `--connectors "<working-dir>/c.json"` and a JSON example `{ "intent": "<need>" }`.',+ 'Make it: `mkdir -p <folder-name>`, then `upload --page-id \'<id>\'`; not commands: `pageId: "PAGEREF_<x>"`, `Replaced PAGEREF_<name> tokens`.',+ '> names come from `pac model genpage list',+ '> --app-id <id>`. Never guess them, and `pac model list` too.',+ '```markdown',+ "- Command: `node x.js --env '<org-url>'`",+ '```',+ ].join('\n');+ assert.deepEqual(commandText(doc).map((c) => c.code.trim()), [+ "$prompt = @'",+ 'node x.js --plan "<working-dir>/plan.md"',+ 'node x.js --code-file <working-dir>/a.tsx',+ "node x.js --file '<working-dir>/a.tsx'",+ '--connectors "<working-dir>/c.json"',+ 'mkdir -p <folder-name>',+ "upload --page-id '<id>'",+ 'pac model genpage list --app-id <id>',+ 'pac model list',+ "node x.js --env '<org-url>'",+ ]);+});diff --git a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.jsindex 5a74cbaaf..69d06fc0b 100644--- a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js+++ b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js@@ -33,11 +33,14 @@ function mdFiles() {}const rel = (p) => p.replace(PLUGIN + path.sep, '').replace(/\\/g, '/');+// Every document is read with its line endings normalized: a Windows checkout turns them into CRLF, and a+// check measured in characters then read differently there than on the LF checkout it was written on.+const readDoc = (p) => fs.readFileSync(p, 'utf8').replace(/\r\n/g, '\n');test('no Connectors dispatch line uses the retired enabled/disabled vocabulary', () => {const offenders = [];for (const f of mdFiles()) {- const lines = fs.readFileSync(f, 'utf8').split(/\r?\n/);+ const lines = readDoc(f).split(/\r?\n/);lines.forEach((line, i) => {// Only DECLARATION lines: a dispatch template row (`> - Connectors: …`) or an input-spec// bullet (`- **Connectors** — …` / `- **Connectors: …**`). Prose that merely mentions the@@ -51,8 +54,8 @@ test('no Connectors dispatch line uses the retired enabled/disabled vocabulary',});test('the orchestrator emits the exact token the page-builder triggers on', () => {- const skill = fs.readFileSync(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'), 'utf8');- const builder = fs.readFileSync(path.join(PLUGIN, 'agents', 'genpage-page-builder.md'), 'utf8');+ const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));+ const builder = readDoc(path.join(PLUGIN, 'agents', 'genpage-page-builder.md'));// Consumer side: the page-builder reads connectors.md and emits connector code only on the// positive token, and treats the negative token (or an absent line) as no connectors.@@ -77,8 +80,8 @@ test('the connectors rollback gate is documented where the scripts enforce it',// When the follow-up change removes the gate, invert it again: assert NO prose references the// flag, because a probe of a removed flag prints `disabled` (unknown flags are fail-closed) and// would silently turn connector authoring back off.- const builder = fs.readFileSync(path.join(PLUGIN, 'agents', 'genpage-connector-builder.md'), 'utf8');- const skill = fs.readFileSync(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'), 'utf8');+ const builder = readDoc(path.join(PLUGIN, 'agents', 'genpage-connector-builder.md'));+ const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));const probe = /feature-flags\.js"?\s+connectors\b/;assert.match(builder, probe, 'the connector-builder owns the gate and must probe it');assert.match(skill, probe, 'Phase 4.5 must re-probe the gate before deploying bindings');@@ -88,7 +91,7 @@ test('the connectors rollback gate is documented where the scripts enforce it',});test('connector metadata discovery uses the PAC connector name, not the full API resource path', () => {- const builder = fs.readFileSync(path.join(PLUGIN, 'agents', 'genpage-connector-builder.md'), 'utf8');+ const builder = readDoc(path.join(PLUGIN, 'agents', 'genpage-connector-builder.md'));assert.match(builder,/terminal segment|final path segment/i,@@ -107,7 +110,7 @@ test('connector metadata discovery uses the PAC connector name, not the full API});test('connector-builder defines setup when no suitable connection exists', () => {- const builder = fs.readFileSync(path.join(PLUGIN, 'agents', 'genpage-connector-builder.md'), 'utf8');+ const builder = readDoc(path.join(PLUGIN, 'agents', 'genpage-connector-builder.md'));assert.match(builder, /power-apps\s+create-connection/, 'connector-builder must document the connection-creation command');assert.match(builder, /POWERAPPS_CLI_ENABLE_BROWSER_CONNECTION/, 'interactive connector setup gate must be explicit');// Bare /needs_input/ is the agent's universal return shape and was already present, so it@@ -134,8 +137,8 @@ test('connector-builder defines setup when no suitable connection exists', () =>});test('genpage orchestrator defines inline recovery for a worker missing declared tools', () => {- const skill = fs.readFileSync(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'), 'utf8');- const editFlow = fs.readFileSync(path.join(PLUGIN, 'skills', 'genpage', 'edit-flow.md'), 'utf8');+ const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));+ const editFlow = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'edit-flow.md'));// No `s` flag and no unbounded `[\s\S]*`: with them, `.*` spans the whole document and any doc// containing "missing" … "file" … "tool" anywhere passes. Anchor to the new sentence instead.assert.match(skill, /declared\s+file\s+or\s+process-execution\s+tools\s+are\s+unavailable/i);@@ -157,11 +160,115 @@ test('genpage orchestrator defines inline recovery for a worker missing declared);});+test('genpage orchestrator gates planner output with deterministic plan provenance checks', () => {+ const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));+ const editFlow = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'edit-flow.md'));++ assert.match(skill, /genpage-plan-provenance\.js[\s\S]{0,500}prepare/i, 'create flow must quarantine stale genpage-plan.md before planner writeback');+ assert.match(skill, /genpage-plan-provenance\.js[\s\S]{0,500}verify/i, 'create flow must hash-check the written plan against the approved body');+ assert.match(skill, /approved\s+plan\s+body/i, 'create flow must verify against the approved plan body, not mere file existence');+ assert.match(editFlow, /genpage-plan-provenance\.js[\s\S]{0,500}prepare/i, 'edit flow must quarantine stale genpage-edit-plan.md before planner writeback');+ assert.match(editFlow, /genpage-plan-provenance\.js[\s\S]{0,500}verify/i, 'edit flow must hash-check the written edit plan against the approved body');+ // `prepare` refuses a link at the plan path or the quarantine folder; carrying on would let the+ // planner write the approved plan through it.+ for (const [flow, text] of [['create', skill], ['edit', editFlow]]) {+ const prep = text.indexOf('genpage-plan-provenance.js" prepare');+ assert.ok(prep > -1, `${flow} flow runs prepare`);+ assert.match(text.slice(prep, prep + 700), /Continue only on `"ok":true`[\s\S]{0,300}halt/, `${flow} flow halts when prepare refuses`);+ }+});++test('genpage orchestrator validates worker output completeness before accepting parallel results', () => {+ const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));++ assert.match(skill, /genpage-worker-output\.js/, 'multi-page flow must call the deterministic worker-output validator');+ assert.match(skill, /unbalanced|default export|markdown code fence/i, 'skill text must name the completeness checks that trigger inline fallback');+ assert.match(skill, /inline fallback|Phase 5b page-builder workflow inline/i, 'invalid worker output must use the same inline fallback path as missing output');+});++// #585 item 2: every page that can ship passes the gate — a worker's (5c), and one the orchestrator+// writes itself (5b), which is also what the 5c fallback runs.+test('the completeness gate also runs on pages written inline, including the fallback', () => {+ const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));+ const fastPath = skill.split(/#### 5b\. Single-page fast path/)[1].split(/#### 5c\. Multi-page/)[0];+ assert.match(fastPath, /genpage-worker-output\.js/, 'the single-page path runs the gate');+ assert.match(fastPath, /rewrite the page once[\s\S]{0,120}halt/i, 'a page that keeps failing halts instead of deploying');+ assert.match(fastPath, /5c fallback/, 'the fallback is the same path, so it is covered');+});++// #588 item 4: page filenames are checked by the deterministic gate BEFORE any worker is dispatched —+// a link or junction escape cannot be spotted by reading the plan.+test('genpage orchestrator runs the page-file gate before dispatching page workers', () => {+ const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));+ const gate = skill.indexOf('check-page-files.js');+ assert.ok(gate > -1, 'the skill must run scripts/check-page-files.js');+ const dispatch = skill.indexOf('genpage-worker-output.js');+ assert.ok(dispatch > gate, 'the filename gate must come before workers run and their output is checked');+ // Anywhere in the gate's own section: a fixed window broke as the list of refused names grew.+ const rest = skill.slice(gate);+ const next = rest.search(/\n#{2,6}\s/);+ assert.match(next < 0 ? rest : rest.slice(0, next), /halt and\s+re-plan/i, 'a refused filename halts; it is never rewritten after approval');+});++test('single-page inline generation treats missing or malformed Custom API Bindings as a halt', () => {+ const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));+ const fastPath = skill.split(/#### 5b\. Single-page fast path/)[1].split(/#### 5c\. Multi-page/)[0];++ assert.match(fastPath, /No custom API bindings\./, 'the exact sentinel must remain the only no-actions value');+ assert.match(fastPath, /missing[\s\S]{0,120}malformed[\s\S]{0,160}halt|halt[\s\S]{0,160}missing[\s\S]{0,120}malformed/i, 'single-page generation must halt on missing or malformed Custom API sections');+ assert.doesNotMatch(fastPath, /empty\/missing\/malformed section, as\s+having no Custom APIs/i, 'single-page generation must not downgrade malformed Custom API sections to none');+});++// #585 item 3, the other two readers: the orchestrator's Custom API phase and the page-builder worker.+// Only the exact sentinel means "none" — a missing, empty or malformed section is a broken plan.+test('the Custom API phase and the page builder never read a missing or malformed section as none', () => {+ const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));+ const phase = skill.slice(skill.indexOf("**If it prints `enabled`:** read the plan's `## Custom API Bindings`"));+ assert.ok(phase.length > 0, 'the Custom API phase is where it was');+ assert.match(phase.slice(0, 700), /only when its body is exactly `No custom API bindings\.`/);+ assert.match(phase.slice(0, 700), /missing, empty, or malformed, \*\*halt\*\*/);+ const builder = readDoc(path.join(PLUGIN, 'agents', 'genpage-page-builder.md'));+ assert.match(builder, /That sentinel is the only way a plan says\s+"none"/);+ assert.match(builder, /\*\*stop and report it instead of writing the page\*\*/);+ assert.doesNotMatch(builder, /is missing entirely, or contains no binding row, the page has \*\*no Custom APIs\*\*/);+});++// A plan made while `custom-api` was ON still carries its binding table after the flag is turned OFF.+// Page generation takes that table as permission to emit executeAction/executeFunction calls, while the+// OFF branch drops actions.json and --actions — so skipping the phase "regardless of the plan" deployed+// pages calling Custom APIs that were never bound. OFF with a real table must halt before generation.+test('a disabled Custom API probe halts on a plan that still carries a binding table', () => {+ const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));+ const start = skill.indexOf("**If it prints `disabled`:** Custom API support is OFF.");+ assert.ok(start > -1, 'the disabled branch of the Custom API phase is where it was');+ const off = skill.slice(start, skill.indexOf("**If it prints `enabled`:** read the plan's `## Custom API Bindings`"));+ assert.match(off, /actual binding table[\s\S]{0,200}\*\*halt before page generation\*\*/, 'a real table under a disabled probe halts');+ assert.match(off, /only a body of exactly `No custom API bindings\.` continues/, 'only the sentinel lets a disabled run go on');+ assert.match(off, /missing, empty, or malformed section halts too/, 'a broken section halts under a disabled probe as well');+ assert.doesNotMatch(off, /regardless of what the\s+plan's/i, 'the disabled branch must not ignore the plan');+ assert.doesNotMatch(off, /Any other section body/i, 'no body but the sentinel means "none"');+ const fastPath = skill.split(/#### 5b\. Single-page fast path/)[1].split(/#### 5c\. Multi-page/)[0];+ assert.match(fastPath, /3b\. Only when the Phase 4\.6 probe printed `enabled` \*\*and\*\*/, 'inline generation reads Custom API guidance only under an enabled probe');+});++// The manifest generator exits 2 when an existing package.json lacks a package a requested feature needs+// (and when the working directory is a link). The step used to say "do not block the workflow if the+// script returns non-zero", so a charts rerun carried on over the stale manifest the check exists to stop.+test('the manifest step halts on exit 2 instead of carrying on over a stale package.json', () => {+ const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));+ const start = skill.indexOf('scripts/generate-page-manifest.js');+ assert.ok(start > -1, 'the manifest step is where it was');+ const step = skill.slice(start, skill.indexOf('### Phase 1: Plan', start));+ assert.match(step, /\*\*Continue only on exit 0\.\*\*/);+ assert.match(step, /\*\*Exit 2 — halt\*\*[\s\S]{0,400}--force/, 'exit 2 halts and surfaces the merge / --force choice');+ assert.doesNotMatch(step, /do\s+not\s+block\s+the\s+workflow/i, 'no non-zero exit is waved through');+});+test('page generation rejects Griffel borderWidth shorthand before deploy', () => {- const rules = fs.readFileSync(path.join(PLUGIN, 'references', 'rules.md'), 'utf8');- const builder = fs.readFileSync(path.join(PLUGIN, 'agents', 'genpage-page-builder.md'), 'utf8');- const skill = fs.readFileSync(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'), 'utf8');- const editFlow = fs.readFileSync(path.join(PLUGIN, 'skills', 'genpage', 'edit-flow.md'), 'utf8');+ const rules = readDoc(path.join(PLUGIN, 'references', 'rules.md'));+ const builder = readDoc(path.join(PLUGIN, 'agents', 'genpage-page-builder.md'));+ const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));+ const editFlow = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'edit-flow.md'));assert.match(rules, /borderWidth/i, 'rules must name the runtime-only Griffel failure');assert.match(builder, /borderWidth/i, 'page-builder must scan its output for the shorthand');assert.match(skill, /borderWidth/i, 'inline page generation must run the same scan');@@ -176,6 +283,419 @@ test('page generation rejects Griffel borderWidth shorthand before deploy', () =}});+// Measured against the PAC CLI: `pac model genpage transpile` accepted a `string` assigned to a+// `number` and a selected column that does not exist, exited 0 and wrote JavaScript. So no instruction+// may present it as a type check — a worker that believes it is one ships unchecked types with false+// confidence — and the page-builder, the one place that names the command, must say what it is not.+//+// The claim can be worded many ways ("to type-check the page", "a clean transpile means it is+// type-safe", "catches type errors", "fails on type errors", "type errors are caught during+// transpilation"), and one exact phrase in four files would miss all of them. So+// every agent, skill and reference document is read CLAUSE by clause, and a clause fails when it+// ATTRIBUTES a type guarantee to transpiling that no negation governs. It is a tripwire, not a parser: a+// correct sentence it flags is reworded with the checker as its subject, or with the denial stated+// directly. And its vocabulary is FINITE — the claim families below, each pinned by a predicate — so it+// catches the wordings those families describe and their near variants, not every sentence that could+// mean the same. A new wording it misses is a new family (and a new predicate), not a bug in the rest.+// · Attribution, not co-occurrence. A claim belongs to the actor named nearest before it in its clause+// — transpiling, a checker the reader runs itself (`tsc`, the TypeScript compiler, the type checker,+// an `npm run` script) or the reader ("you") — so "Use `tsc` to type-check the page after+// transpiling it" is about tsc, unless transpiling is what runs that checker ("Transpile runs `tsc`+// to type-check the page"). A claim with no actor before it is an instruction, and belongs to+// transpiling only when transpiling is its MEANS ("Type-check the page by transpiling it", "To+// type-check the page, run the transpile"), never its time ("Type-check separately before+// transpiling"). A PASSIVE claim whose agent is a checker named after it ("After transpiling, the+// page is type-checked by `tsc`") is that checker's, again unless transpiling runs it.+// · A clause with no subject of its own continues the previous one only when it opens with the claim:+// `it`/`this`/`that` or nothing, then a claim verb in the third person ("…, but it type-checks",+// "… and reports type errors", "That validates the types") — built from the same stems as the claim+// families, so the two vocabularies cannot drift apart. What `it` continues is the actor named last:+// "Transpile the page, then run `tsc`. It type-checks every prop." is about tsc.+// · A negation governs a claim only from just before it, in its own clause, with nothing between but+// words that carry the denial to it ("is not proof that the page is", "does not mean the", "by+// itself"). A negation of anything else — "does not bundle and type-checks", "does not need a flag to+// type-check" — does not excuse the claim, and neither does a hedge: "does not always / necessarily /+// fully / really type-check" says that sometimes it does. Inline emphasis is not a word in between:+// "does **not** type-check" is a denial.+// · List items, table cells, headings and paragraphs are separate units, so a "not" in one bullet never+// excuses the next; fenced code is skipped.+const CATCHING = ['catch', 'detect', 'flag', 'report', 'find', 'surface', 'prevent', 'reject', 'stop', 'spot', 'check', 'warn', 'raise', 'throw'];+// The same verbs as past participles, in the same order: "type errors are caught".+const CAUGHT = ['caught', 'detected', 'flagged', 'reported', 'found', 'surfaced', 'prevented', 'rejected', 'stopped', 'spotted', 'checked', 'warned', 'raised', 'thrown'];+// The verbs of a step that FAILS on them: "fails on type errors", "errors out on a type mismatch".+const FAILING = ['fail', 'error', 'break', 'abort', 'halt', 'exit'];+const CHECKING = ['validat', 'verif', 'check'];+const BEING = ['is', 'acts as', 'serves as', 'works as', 'doubles as'];+const TYPE_ERROR = String.raw`typ(?:e|ing) (?:errors?|mistakes?|bugs?|issues?|problems?|mismatch(?:es)?)`;+// One alternative per claim family. The test pins a predicate for each, so a family added here without+// one fails there.+const CLAIM_FAMILIES = [+ // "type checker" included: a mention of the checker is the checker's own (see the host rule in+ // attributed), so it counts only when transpiling runs it — "Transpile uses the type checker".+ String.raw`\btype[- ]?check\w*`,+ String.raw`\btype[- ]?safe\w*`,+ // A catching VERB, a few words or a condition away ("checks whether the page has type errors"). A bare+ // "a type error … still transpiles" says the opposite of a claim, and so do a contrast in between+ // ("checks syntax even with type errors") and a denial right after ("warns that type errors are not+ // checked").+ String.raw`\b(?:${CATCHING.join('|')})\w* (?:(?:(?:an? |the )?(?:error|exception|warning|user|maker|developer) )?(?:whether|if|when) (?:\w+ ){0,3}?(?:has|have|contains?|hits?) (?:any )?|(?:(?!even\b|despite\b|regardless\b|though\b|although\b|while\b|yet\b)\w+ ){0,3}?)${TYPE_ERROR}\b(?! (?:(?:are|is|were|was) (?:not|never)\b|(?:aren|isn|weren|wasn)['’]t\b|(?:remain|remains|go|goes|stay|stays) un\w+))`,+ // …the same in the passive. A negation never stands in for the adverb: "are not caught" is no claim.+ String.raw`\b${TYPE_ERROR} (?:are|is|get|gets|will be|would be)(?: (?!not\b|never\b)\w+)? (?:${CAUGHT.join('|')})\b`,+ // …and a step that FAILS on them, or exits non-zero: "exits non-zero on type errors". A plain exit is+ // left out on purpose — "exits 0 even with type errors" is the truth, and says so.+ String.raw`\b(?:(?:${FAILING.join('|')})\w*(?: out)?|(?:exit|return)\w* (?:with )?(?:a )?non-?zero(?: (?:exit )?(?:code|status))?) (?:on|over|with|for|at) (?:\w+ ){0,2}?${TYPE_ERROR}\b`,+ String.raw`\btype (?:correctness|soundness|analysis|validation|verification)\b`,+ // The ABSENCE of type errors: "guarantees no type errors", "the page is free of type errors". The "no" is+ // the claim's own word, so it never reads as a negation governing it.+ String.raw`\b(?:no|zero|free of|without any) ${TYPE_ERROR}\b`,+ String.raw`\btypes? (?:are|is) (?:valid|correct|checked|verified|sound|safe)\b`,+ String.raw`\b(?:${CHECKING.join('|')})\w* (?:the |its |their |all |every )?types?\b`,+ String.raw`\b(?:correct|valid|sound|safe) typ(?:es|ing)\b`,+ String.raw`\b(?:${BEING.join('|')}) (?:a |an |the )?type[- ]?checker\b`,+];+const TYPE_CLAIM = new RegExp(CLAIM_FAMILIES.join('|'), 'gi');+// The same families as a predicate in the third person: what a clause with no subject of its own must+// open with to continue the previous one.+const THIRD_PERSON = [+ String.raw`type[- ]?checks`,+ String.raw`(?:${[...CATCHING, ...CHECKING, ...FAILING].join('|')})\w*s`,+ 'guarantees|ensures|proves|confirms|performs|provides|means|shows|implies|does|returns',+ String.raw`is (?:a |an |the )?(?:type[- ]?check(?:er)?|type[- ]?safe)`,+ ...BEING.filter((b) => b !== 'is'),+].join('|');+const CONTINUES = new RegExp(String.raw`^(?:(?:and|but|then|so|yet|while|whereas|although|though|however),?\s+)?(?:(?:it|this|that)\s+)?(?:also |then |still |now |just |only |even |simply |already |therefore |thus )?(?:${THIRD_PERSON})\b`, 'i');+const NEGATION = /\b(?:not|never|no|nor|without|neither|cannot)\b|n't\b/gi;+// The only words that may stand between a negation and the claim it denies. No hedge: "always",+// "necessarily", "fully" and "really" each turn the denial into "sometimes".+const BRIDGE = /^(?:a|an|the|any|its|their|this|that|there|page|pages|code|file|types?|is|are|be|being|been|by|itself|on|own|proof|guarantee|evidence|sign|mean|means|imply|implies|ensure|ensures|show|shows|prove|proves|of|for|actually|also|even|therefore|thus|in|way)$/i;+// Clause boundaries: `;`, a `:` that is not a URL's, a spaced dash, a comma before a conjunction, and the+// conjunctions that start a new statement.+const CLAUSE_BREAK = /\s*(?:;|:(?!\/\/)|\s[—–]\s|,(?=\s*(?:and|but|then|so|yet|while|whereas|although|though|however)\b)|(?<=\S)\s+(?=(?:and|but|then|whereas|although|though)\s))\s*/i;+// Who a claim can belong to: `t` transpiling (the whole command is one mention), `x` a checker the reader+// runs itself — named, or a generic "type-check script" — and `r` the reader.+const ACTOR = new RegExp([+ String.raw`(?<t>\x60pac model genpage transpile\x60|transpil\w*)`,+ String.raw`(?<x>\x60?\btsc\b\x60?|\bTypeScript compiler\b|\btype[- ]?checker\b|\x60npm run [^\x60]*\x60|\btype[- ]?check(?:ing)? (?:script|command|step|task|job)\b)`,+ String.raw`(?<r>\b(?:you|yourself|we)\b)`,+].join('|'), 'gi');+// Transpiling running the checker makes the checker's claim its own: "Transpile runs `tsc` to type-check".+const OWNS = /\b(?:runs|invokes|uses|calls|executes|wraps|includes|contains|has|applies|launches|spawns)\b/i;+// The last word before transpiling that makes it an instruction's MEANS: "by transpiling", "with the+// transpile", "run the transpile", "in the transpile step". Anything else — "before", "after", "you" —+// makes it the instruction's time, or someone else's act.+const MEANS = /^(?:by|with|via|using|through|run|running|use|in|during|within)$/i;+const FILLER = /^(?:the|a|an|its|this|that|your|every|each|page|pages|code|file|it|them)$/i;+// A passive claim, and the words that name its agent after it: "…is type-checked BY `tsc`".+const AUX = /\b(?:is|are|be|been|being|was|were|gets?|got)\s+(?:(?!not\b|never\b)\w+\s+)?$/i;+const AGENT = /^(?:by|with|using|via|through)$/i;+const gapWords = (text) => text.split(/\s+/).map((w) => w.replace(/[^\w-]/g, '')).filter((w) => w && !FILLER.test(w));+// Inline emphasis is not a word between a negation and its claim: "does **not** type-check" denies it.+const plain = (text) => text.replace(/\*+/g, '').replace(/(^|[\s(])_([^_\s][^_]*?)_(?=$|[\s).,;:!?])/g, '$1$2');++function governed(clause, claimIndex) {+ let last = null;+ for (const m of clause.slice(0, claimIndex).matchAll(NEGATION)) last = m;+ if (!last) return false;+ const words = clause.slice(last.index + last[0].length, claimIndex).trim().split(/\s+/).filter(Boolean);+ if (words.every((w) => BRIDGE.test(w))) return true;+ // A denial carried through a coordination: "does not bundle or type-check", "does not minify, bundle or+ // type-check". The claim is the last item of a list the negation heads: `or`/`nor`, then bridge words at+ // most. A new subject after the `or` ("…, or it type-checks") is no such list.+ let i = words.length - 1;+ while (i >= 0 && BRIDGE.test(words[i])) i -= 1;+ return i > 0 && /^n?or$/i.test(words[i]);+}++function actorsOf(clause) {+ return [...clause.matchAll(ACTOR)].map((m) => ({ kind: m.groups.t ? 't' : m.groups.x ? 'x' : 'r', start: m.index, end: m.index + m[0].length }));+}++// Is the claim at [at, end) made of transpiling? See the header.+function attributed(clause, actors, at, end, continued) {+ // A claim that is part of a checker's own name ("run the type-check script") is that checker's,+ // unless transpiling is what runs it ("Transpile includes a type-check step").+ const host = actors.find((a) => a.kind === 'x' && a.start <= at && end <= a.end);+ if (host) {+ const runner = actors.filter((a) => a.kind === 't' && a.end <= host.start).pop();+ return !!runner && OWNS.test(clause.slice(runner.end, host.start));+ }+ const next = actors.find((a) => a.start >= end);+ // A PASSIVE claim whose agent is a checker named after it — "the page is type-checked by `tsc`", "type+ // errors are caught by the type checker" — is that checker's, unless transpiling is what runs it.+ const passive = AUX.test(clause.slice(0, at)) || /\b(?:is|are|gets?|be)\b/i.test(clause.slice(at, end));+ if (passive && next && next.kind === 'x' && gapWords(clause.slice(end, next.start)).some((w) => AGENT.test(w))) {+ const runner = actors.filter((a) => a.kind === 't' && a.start < next.start).pop();+ return !!runner && OWNS.test(clause.slice(runner.end, next.start));+ }+ const before = actors.filter((a) => a.start < at);+ if (before.length) {+ const near = before[before.length - 1];+ if (near.kind === 't') return true;+ const owner = before[before.length - 2];+ return near.kind === 'x' && !!owner && owner.kind === 't' && OWNS.test(clause.slice(owner.end, near.start));+ }+ if (continued) return true;+ if (!next || next.kind !== 't') return false;+ const gap = gapWords(clause.slice(end, next.start));+ // Nothing but filler between the two: "To type-check the page, transpile it" and "For type-checking,+ // transpile the page" are purposes; without the "to" or "for" ("Type-check, transpile, upload.") it is+ // a list of steps.+ if (!gap.length) return /\b(?:to|for)\s+$/i.test(clause.slice(0, at));+ return MEANS.test(gap[gap.length - 1]);+}++// Paragraphs, list items and table cells, as separate units (a heading is a unit too, so what `It` refers+// to after one is decided by the heading itself). Fenced code is skipped — it is commands, not claims.+function docUnits(markdown) {+ const units = [];+ let cur = [];+ let fenced = false;+ const flush = () => { if (cur.length) units.push(cur.join(' ')); cur = []; };+ for (const raw of String(markdown).split(/\r?\n/)) {+ const line = raw.trim();+ if (/^(```|~~~)/.test(line)) { flush(); fenced = !fenced; continue; }+ if (fenced) continue;+ if (!line) { flush(); continue; }+ if (/^#{1,6}\s/.test(line)) { flush(); units.push(line.replace(/^#+\s*/, '')); continue; }+ if (line.startsWith('|')) { flush(); for (const cell of line.split('|')) if (cell.trim()) units.push(cell.trim()); continue; }+ const item = /^(?:[-*+]|\d+[.)]|>)\s+/.exec(line);+ if (item) flush();+ cur.push(item ? line.slice(item[0].length) : line);+ }+ flush();+ return units;+}++function transpileTypeClaims(markdown) {+ const found = [];+ let prev = false; // is the actor named last transpiling — what `it` would continue+ for (const unit of docUnits(markdown)) {+ for (const sentence of unit.split(/(?<=[.!?])\s+(?=[A-Z`(*"'])/)) {+ for (const raw of sentence.split(CLAUSE_BREAK)) {+ const clause = plain(raw.trim());+ const actors = actorsOf(clause);+ const continued = prev && CONTINUES.test(clause);+ if ((continued || actors.some((a) => a.kind === 't')) && !found.includes(sentence)+ && [...clause.matchAll(TYPE_CLAIM)].some((m) => !governed(clause, m.index) && attributed(clause, actors, m.index, m.index + m[0].length, continued))) {+ found.push(sentence);+ }+ prev = actors.length ? actors[actors.length - 1].kind === 't' : continued;+ }+ }+ }+ return found;+}++test('the transpile claim detector catches reworded claims and allows negated ones', () => {+ for (const claim of [+ 'Run `pac model genpage transpile` to type-check the page before deploy.',+ 'A clean transpile means the page is type-safe.',+ 'Transpilation catches type errors early.',+ 'The transpile step validates the types of every prop.',+ 'Use the transpile as a typecheck, then upload.',+ 'After transpiling, the types are correct.',+ 'Transpile performs static type analysis.',+ 'Transpile catches typing mistakes.',+ 'A clean transpile guarantees type correctness.',+ 'The transpiler acts as a type checker.',+ // A negation that governs something ELSE does not excuse the claim — in its clause, beyond a+ // conjunction, or too far before it.+ 'Transpile does not bundle dependencies, but it type-checks the page.',+ 'Transpile does not bundle and type-checks the page.',+ 'Transpile does not require the reader to install anything to type-check the page.',+ 'Transpile does not need a flag to type-check the page.',+ // …but not past a new subject.+ 'Transpile does not bundle anything, or it type-checks the page.',+ // A hedge is not a denial: each says that sometimes it does.+ 'Transpile does not always type-check the page.',+ 'Transpile does not necessarily type-check the page.',+ 'Transpile does not fully type-check the page.',+ 'Transpile does not really type-check the page.',+ // An instruction whose MEANS is transpiling, and a checker that transpiling runs.+ 'Type-check the page by transpiling it.',+ 'To type-check the page, run the transpile.',+ 'To type-check the page, transpile it.',+ 'Type-check the page with `pac model genpage transpile`.',+ 'Type-check in the transpile step.',+ 'Transpile runs `tsc` to type-check the page.',+ // A step that FAILS on type errors, and the passive of catching them, are the same guarantee.+ 'The transpile step fails on type errors.',+ 'Transpile rejects code with type errors.',+ 'Type errors are caught during transpilation.',+ 'Run the transpile. It fails on type errors.',+ // A checker named after an ACTIVE claim is its instrument, not its agent — and a passive one's agent+ // that transpiling runs is transpiling's.+ 'Transpile type-checks the page with `tsc`.',+ 'Transpiling runs `tsc`, which means the page is type-checked by `tsc`.',+ // A purpose with "for", a non-zero exit, and a checker step that transpiling itself includes.+ 'For type-checking, transpile the page.',+ '`pac model genpage transpile` exits non-zero on type errors.',+ 'Transpile returns a non-zero exit code for type errors.',+ 'Run the transpile. It exits non-zero on type errors.',+ 'Run the transpile. It returns non-zero on type errors.',+ // A checking or warning verb reaches the type errors across a few words, as the catching verbs do.+ 'Transpile checks for type errors.',+ 'The transpile step checks the page for type errors.',+ 'Transpile warns about type errors.',+ 'Transpile throws on type errors.',+ 'Transpile raises an error on type mismatches.',+ 'Transpile raises type errors early.',+ 'Transpile checks whether the page has type errors.',+ // Type soundness, and the absence of type errors, are the same guarantee.+ 'The transpiler proves type soundness.',+ 'Transpilation guarantees no type errors.',+ 'A clean transpile means the page is free of type errors.',+ 'Transpile warns when the page has type errors.',+ 'Transpile throws if the code contains type errors.',+ 'Transpile throws an exception if the page has type errors.',+ 'Transpile warns the user when the page has type errors.',+ 'Type errors are checked during transpilation.',+ 'Transpile includes a type-check step.',+ 'Transpile has a type-check step.',+ 'Transpile contains a type-check step.',+ 'Transpile uses the type checker.',+ // `it`, `this` or `that` carries the subject across a clause, a sentence, a blank line, or into the+ // next list item.+ 'Run the transpile. It type-checks the page.',+ 'Run the transpile; this type-checks the page.',+ 'Run the transpile. That validates the types.',+ 'Run the transpile. It does not bundle. It type-checks the page.',+ 'Transpile the page.\n\nIt type-checks every prop.',+ '- Transpile does not bundle anything.\n- It type-checks the page.',+ // Each list item, table cell and heading is its own unit, so a negation in one never excuses the next.+ '- Transpile does not bundle anything\n- Transpile type-checks the page',+ '| Transpile does not bundle | Transpile type-checks the page |',+ '## Transpile does not bundle\nTranspile type-checks the page.',+ ]) {+ assert.ok(transpileTypeClaims(claim).length > 0, `must be caught: ${claim}`);+ }+ for (const fine of [+ '`pac model genpage transpile` only transpiles the page: it does not type-check it.',+ 'A clean transpile is not proof that the types are correct.',+ 'A clean transpile is therefore no proof that the page is type-safe.',+ 'A transpile that succeeds does not mean the page is type-safe.',+ 'Transpile never type-checks.',+ 'Transpile cannot type-check.',+ 'It passes TypeScript and `pac model genpage transpile`, then logs a runtime error.',+ 'Run the type check separately, before you upload the page.',+ 'Transpile first, then type-check separately with `tsc`.',+ 'Transpile the page and use `tsc` to type-check it.',+ // A claim belongs to the actor named nearest before it: a checker, or the reader.+ 'Use `tsc` to type-check the page after transpiling it.',+ 'After transpiling it, use `tsc` to type-check the page.',+ 'Transpile emits JavaScript while `tsc` type-checks the source.',+ 'After transpiling, the type checker catches type errors.',+ 'After transpiling, the TypeScript compiler reports type errors.',+ // A passive claim whose agent is a checker named after it is that checker's.+ 'After transpiling, the page is type-checked by `tsc`.',+ 'After transpiling, type errors are caught by the type checker.',+ // The failure and passive families deny the same way, and emphasis around a denial is no word between.+ 'Type errors are not caught during transpilation.',+ 'The transpile step does not fail on type errors.',+ 'Transpile does **not** type-check the page.',+ 'Transpile does *not* type-check the page.',+ 'Transpile does _not_ type-check the page.',+ // A negation carries through a list it heads.+ 'Transpile does not bundle or type-check the page.',+ 'Transpile does not minify, bundle or type-check the page.',+ 'Transpile does not bundle it or type-check it.',+ // The truth about the exit code, a generic checker step, and a "for" purpose served by a checker.+ '`pac model genpage transpile` exits 0 even with type errors.',+ "After transpiling, run the project's type-check script.",+ 'For type-checking, use `tsc`.',+ 'Run the transpile. That means you must type-check it yourself.',+ // An instruction whose TIME is transpiling is not about it.+ 'Type-check separately before transpiling.',+ 'Type-check the page before you transpile it.',+ 'Type-check the page in a separate step before transpiling it.',+ 'Type-check, transpile, upload.',+ // …and so does a check for type errors the reader runs, or one that is denied.+ 'Transpile the page, then check it for type errors with `tsc`.',+ 'Transpile does not check for type errors.',+ 'After transpiling, `tsc` checks for type errors.',+ // A contrast between the verb and the type errors, or a denial right after them, is the truth.+ 'Transpile checks syntax even with type errors.',+ // …and so is denying that absence.+ 'A clean transpile does not mean there are no type errors.',+ 'Transpile does not guarantee the page is free of type errors.',+ 'Transpile reports success despite type errors.',+ 'Transpile warns that type errors are not checked.',+ 'Transpile warns that type errors aren’t checked.',+ "Transpile warns that type errors aren't checked.",+ 'Transpile warns that type errors remain unchecked.',+ 'Transpile checks syntax while type errors remain.',+ 'Transpile reports success yet type errors remain.',+ // `It` continues the MOST RECENT subject — here `tsc`.+ 'Transpile the page, then run `tsc`. It type-checks every prop.',+ 'Transpile before invoking the type checker.',+ // A type error named as a SUBJECT is the opposite of a claim.+ '`pac model genpage transpile` only transpiles the page: a type error still transpiles and writes JavaScript.',+ '- Transpile the page.\n- It does not type-check it.',+ // A sentence that continues with something other than `it` making the claim is about something else.+ '`pac model genpage transpile` only transpiles the page. That is what the type check in Step 5 is for.',+ 'Transpile the page; it is important to type-check it too.',+ // After a heading, `It` is whatever the heading names.+ 'Transpile the page.\n\n## The type checker\nIt type-checks every prop.',+ // A unit boundary ends a subject: joined up, each of these would make transpile the subject of the+ // next unit's claim.+ '- Transpile the page\n- The `tsc` step type-checks every prop',+ '| Transpile the page | The `tsc` step type-checks every prop |',+ '## Transpile the page\nThe `tsc` step type-checks every prop.',+ // …even with no checker named to take the claim, where only the boundary keeps it apart — and so+ // does a clause boundary before "and".+ '- Transpile the page\n- The type check is a separate step',+ '| Transpile the page | The type check is a separate step |',+ '## Transpile the page\nThe type check is a separate step.',+ 'Transpile the page and the type check runs separately.',+ // Fenced code is commands, not claims.+ '```\ntranspile && npm run typecheck\n```',+ ]) {+ assert.deepEqual(transpileTypeClaims(fine), [], `must be allowed: ${fine}`);+ }+});++// One third-person predicate per claim family. Each must be caught both in a clause about transpiling and+// as the continuation of one: the claim families and the continuation vocabulary are built from the same+// stems, and this is what proves they agree — a family added to one without the other fails here.+const FAMILY_PREDICATES = [+ 'type-checks the page',+ 'is type-safe',+ 'reports type errors',+ 'ensures type errors are caught',+ 'fails on type errors',+ 'guarantees type correctness',+ 'guarantees no type errors',+ 'means the types are correct',+ 'validates the types',+ 'guarantees correct types',+ 'acts as a type checker',+];+test('every claim family is caught directly and as a continuation, so the two vocabularies cannot drift', () => {+ assert.strictEqual(FAMILY_PREDICATES.length, CLAIM_FAMILIES.length, 'one pinned predicate per claim family');+ FAMILY_PREDICATES.forEach((p, i) => assert.match(p, new RegExp(CLAIM_FAMILIES[i], 'i'), `predicate ${i} pins its own family`));+ assert.strictEqual(CAUGHT.length, CATCHING.length, 'one past participle per catching verb');+ const catching = CATCHING.map((v) => `${v}${/ch$/.test(v) ? 'es' : 's'} type errors`);+ const caught = CAUGHT.map((c) => `ensures type errors are ${c}`);+ const failing = FAILING.map((v) => `${v}s on type errors`);+ const checking = ['validates the types', 'verifies the types', 'checks the types'];+ assert.ok(CHECKING.every((stem) => checking.some((p) => p.startsWith(stem))), 'every checking stem is pinned');+ const serving = BEING.filter((b) => b !== 'is').map((b) => `${b} a type checker`);+ for (const p of [...FAMILY_PREDICATES, ...catching, ...caught, ...failing, ...checking, ...serving]) {+ for (const text of [`Transpile ${p}.`, `Run the transpile. It ${p}.`, `Run the transpile; this ${p}.`, `Transpile does not bundle anything, and ${p}.`]) {+ assert.ok(transpileTypeClaims(text).length > 0, `must be caught: ${text}`);+ }+ }+ for (const c of CAUGHT) assert.ok(transpileTypeClaims(`Type errors are ${c} during transpilation.`).length > 0, `must be caught: ${c}`);+});++test('no genpage instruction presents transpilation as a type check', () => {+ for (const file of mdFiles()) {+ assert.deepEqual(transpileTypeClaims(readDoc(file)), [], `${rel(file)} must not present transpilation as a type check`);+ }+ const builder = readDoc(path.join(PLUGIN, 'agents', 'genpage-page-builder.md'));+ assert.match(builder, /genpage transpile`\s+only transpiles the page: it does not type-check it/, 'the page-builder must say transpilation is not a type check');+});+// --- App Spec schema split -------------------------------------------------//// app-spec-schema.md is read IN FULL at the start of every /app-builder run, so the conditional@@ -187,8 +707,8 @@ test('page generation rejects Griffel borderWidth shorthand before deploy', () =// missing a business process flow nobody realised it could have) rather than as an error.test('every advanced schema section is named in the pointer table, and vice versa', () => {- const core = fs.readFileSync(path.join(PLUGIN, 'references', 'app-spec-schema.md'), 'utf8');- const adv = fs.readFileSync(path.join(PLUGIN, 'references', 'app-spec-schema-advanced.md'), 'utf8');+ const core = readDoc(path.join(PLUGIN, 'references', 'app-spec-schema.md'));+ const adv = readDoc(path.join(PLUGIN, 'references', 'app-spec-schema-advanced.md'));// Sections in the advanced doc: "## globalChoices[] (optional — …)" → "globalChoices[]"const sections = [...adv.matchAll(/^## (\S+)/gm)].map((m) => m[1]);@@ -209,7 +729,7 @@ test('every advanced schema section is named in the pointer table, and vice verstest('the core schema no longer carries the moved sections', () => {// A section left in BOTH docs is worse than in neither: the two copies drift and an author// follows whichever they happened to read.- const core = fs.readFileSync(path.join(PLUGIN, 'references', 'app-spec-schema.md'), 'utf8');+ const core = readDoc(path.join(PLUGIN, 'references', 'app-spec-schema.md'));const coreSections = [...core.matchAll(/^## (\S+)/gm)].map((m) => m[1]);for (const moved of ['globalChoices[]', 'webResources[]', 'commands[]', 'businessRules[]', 'dashboards[]', 'roleGrants[]']) {assert.ok(!coreSections.includes(moved), `${moved} must live only in app-spec-schema-advanced.md`);@@ -220,7 +740,7 @@ test('the skill tells the agent when to read the advanced schema', () => {// The split only stays safe while the skill body routes the reader to it. Without this line an// agent reads the core doc, never opens the advanced one, and quietly cannot author half the// conditional features.- const skill = fs.readFileSync(path.join(PLUGIN, 'skills', 'app-builder', 'SKILL.md'), 'utf8');+ const skill = readDoc(path.join(PLUGIN, 'skills', 'app-builder', 'SKILL.md'));assert.match(skill, /app-spec-schema-advanced\.md/, '/app-builder must point at the advanced schema');assert.match(skill, /conditional feature/i, 'and say when to read it');});@@ -236,7 +756,7 @@ function dispatchTemplates() {[path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'), /^> - (.+)$/gm],[path.join(PLUGIN, 'skills', 'app-builder', 'SKILL.md'), /^\s+> - (.+)$/gm],]) {- const src = fs.readFileSync(file, 'utf8');+ const src = readDoc(file);const lines = [...src.matchAll(re)].map((m) => m[1].trim());// Split into blocks on "Target file", which starts each template.let cur = null;@@ -264,7 +784,7 @@ test('every page-builder dispatch template carries the same required field set',test('every dispatch field the page-builder documents is one a template actually sends', () => {// Catches the reverse drift: a consumer input bullet nobody produces is dead documentation that// an agent will still try to honour.- const builder = fs.readFileSync(path.join(PLUGIN, 'agents', 'genpage-page-builder.md'), 'utf8');+ const builder = readDoc(path.join(PLUGIN, 'agents', 'genpage-page-builder.md'));// The input spec is the bulleted block under "You will be invoked with a prompt that includes:".const specBlock = builder.split(/You will be invoked with a prompt that includes:/)[1] || '';const spec = specBlock.split(/\n#{2,}\s/)[0];@@ -292,3 +812,20 @@ test('Telemetry uses enabled|disabled and is never conflated with the Connectorsassert.doesNotMatch(tel, /binding\(s\)|\bnone\b/, `${t.file}: Telemetry must not use the Connectors vocabulary: ${tel}`);}});++// A worker that writes nothing leaves an earlier attempt's page in place, and it passes every content check.+// Each target is stamped before it is written, in both paths, so the gate can refuse a page left as it was.+test('genpage stamps every page target before it is written, in both paths', () => {+ const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));+ const fastPath = skill.split(/#### 5b\. Single-page fast path/)[1].split(/#### 5c\. Multi-page/)[0];+ const multi = skill.split(/#### 5c\. Multi-page/)[1];+ const stamp = /genpage-worker-output\.js" --stamp --file/;+ assert.match(fastPath, stamp, 'the single-page path stamps its target');+ assert.ok(fastPath.search(stamp) < fastPath.search(/write the `\.tsx` file/i), 'before it writes it');+ assert.match(multi, stamp, 'the multi-page path stamps every target');+ assert.ok(multi.search(stamp) < multi.search(/Fire all invocations in a single message/), 'before it dispatches the workers');+ assert.match(multi, /exactly as its dispatch stamp\s+recorded it/, 'and the gate names what an unchanged page means');+ // The plan's File values already end in `.tsx`, and every command appends it: `<filename>` is the stem.+ assert.match(fastPath, /`<filename>` is the page's `File` value from the plan without its `\.tsx`\s+extension/, 'the single-page path says what <filename> is');+ assert.match(multi, /`<filename>` and `\[filename\]` are each page's `File` value from the\s+plan without its `\.tsx` extension/, 'and so does the multi-page path');+});diff --git a/plugins/model-apps/scripts/tests/genpage-plan-provenance.test.js b/plugins/model-apps/scripts/tests/genpage-plan-provenance.test.jsnew file mode 100644index 000000000..d9136bf1b--- /dev/null+++ b/plugins/model-apps/scripts/tests/genpage-plan-provenance.test.js@@ -0,0 +1,538 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');++const { preparePlanProvenance, verifyPlanProvenance, planTargets } = require('../genpage-plan-provenance.js');++// What the planner hands back for approval (agents/genpage-planner.md Step 5) — a PREVIEW, with full+// prefixed names — and what it then writes (Step 6): a different document, suffixes only. The gate+// must accept the pair; a whole-document hash never could.+const PREVIEW = [+ '## Genpage Plan',+ '',+ '### Pages (2 total)',+ '| Page | File | Purpose | Entities |',+ '|------|------|---------|----------|',+ '| Overview | overview.tsx | Summary cards | contoso_project |',+ '| Details | details.tsx | One record | contoso_project |',+ '',+ '### Data Strategy',+ '- Entities to create: contoso_project (contoso_name, contoso_stage)',+ '',+ '### Localization',+ '- English only — no localization needed',+].join('\n');+const WRITTEN = [+ '# Genpage Plan',+ '## User Requirements',+ 'Projects overview and details.',+ '## Pages',+ '| Page | File | Purpose | Entities |',+ '|------|------|---------|----------|',+ '| Details | details.tsx | One record | project |',+ '| Overview | overview.tsx | Summary cards | project |',+ '## Entity Creation Required',+ '### project',+ '| Suffix | Type |',+ '|---|---|',+ '| name | Text |',+ '## Per-Page Specifications',+ '### Overview',+ '- **File:** overview.tsx',+].join('\r\n');+const PAGE_ID = '6e0c28a2-cdbf-41ec-9186-d10fd5de6e35';+const EDIT_PREVIEW = `## Genpage Edit Plan\n\n### Current State\n- **File:** ${PAGE_ID}/page.tsx\n- **Data:** Mock data\n\n### Proposed Changes\n1. Add a search box\n`;+const EDIT_WRITTEN = `# Genpage Edit Plan\n\n## File Being Edited\n- **Absolute path:** D:\\work\\edit\\${PAGE_ID}\\page.tsx\n- **App ID:** 11111111-2222-3333-4444-555555555555\n- **Page ID:** ${PAGE_ID}\n`;++// An edit plan lives in `genpage-edit-plan.md` (skills/genpage/edit-flow.md), and verify reads each file as the+// kind its name says.+const EDIT = 'genpage-edit-plan.md';+function tmpPlan(content, name = 'genpage-plan.md') {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-plan-prov-'));+ const planPath = path.join(dir, name);+ if (content !== undefined) fs.writeFileSync(planPath, content, 'utf8');+ return planPath;+}++test('preparePlanProvenance quarantines a stale plan before planner dispatch', () => {+ const planPath = tmpPlan('# Genpage Plan\nstale\n');++ const result = preparePlanProvenance({ planPath });++ assert.equal(result.ok, true);+ assert.equal(fs.existsSync(planPath), false, 'stale plan must not remain at the authoritative path');+ assert.ok(result.quarantinedPath, 'quarantine path reported');+ assert.equal(fs.readFileSync(result.quarantinedPath, 'utf8'), '# Genpage Plan\nstale\n');+});++test('what a plan targets: the Pages files of a create, the page id of an edit, in either document', () => {+ assert.deepEqual(planTargets(PREVIEW), { kind: 'create', targets: ['details.tsx', 'overview.tsx'] });+ assert.deepEqual(planTargets(WRITTEN), { kind: 'create', targets: ['details.tsx', 'overview.tsx'] });+ assert.deepEqual(planTargets(EDIT_PREVIEW), { kind: 'edit', targets: [PAGE_ID] });+ assert.deepEqual(planTargets(EDIT_WRITTEN), { kind: 'edit', targets: [PAGE_ID] });+ assert.equal(planTargets('## Genpage Plan\n### Data Strategy\n- none\n'), null);+ // A create plan's per-page File line holding a GUID path is still a create, decided by its table.+ const guidFile = WRITTEN.replace('- **File:** overview.tsx', `- **File:** ${PAGE_ID}/page.tsx`);+ assert.equal(planTargets(guidFile).kind, 'create');+});++// The preview approved in plan mode and the file the planner writes are different documents by design.+test('verifyPlanProvenance accepts the written plan when it targets exactly the approved pages', () => {+ const create = verifyPlanProvenance({ planPath: tmpPlan(WRITTEN), approvedPlan: PREVIEW });+ assert.equal(create.ok, true, create.error);+ assert.deepEqual(create.targets, ['details.tsx', 'overview.tsx']);+ assert.match(create.writtenHash, /^[a-f0-9]{64}$/, 'the verified file is recorded by hash for the log');+ const edit = verifyPlanProvenance({ planPath: tmpPlan(EDIT_WRITTEN, EDIT), approvedPlan: EDIT_PREVIEW });+ assert.equal(edit.ok, true, edit.error);+});++// A stale plan from an earlier run, or one the planner re-derived, targets other pages.+test('verifyPlanProvenance halts when the written plan targets other pages than were approved', () => {+ for (const [what, written] of [+ ['an extra page', WRITTEN.replace('| Overview | overview.tsx | Summary cards | project |', '| Overview | overview.tsx | Summary cards | project |\r\n| Admin | admin.tsx | Settings | project |')],+ ['a missing page', WRITTEN.replace('| Details | details.tsx | One record | project |\r\n', '')],+ ['a renamed page file', WRITTEN.replace('| Details | details.tsx |', '| Details | detail-view.tsx |')],+ ['no Pages table at all', WRITTEN.replace(/## Pages[\s\S]*?## Entity/, '## Entity')],+ ['an edit plan instead', EDIT_WRITTEN],+ ]) {+ const result = verifyPlanProvenance({ planPath: tmpPlan(written), approvedPlan: PREVIEW });+ assert.equal(result.ok, false, what);+ assert.match(result.error, /approved plan named details\.tsx, overview\.tsx/, what);+ }+ const otherPage = verifyPlanProvenance({ planPath: tmpPlan(EDIT_WRITTEN.replace(/6e0c28a2/g, '7f1d39b3'), EDIT), approvedPlan: EDIT_PREVIEW });+ assert.equal(otherPage.ok, false, 'an edit plan for another page');+});++// A Pages table quoted in the requirements used to be read in place of the real one — here one naming exactly+// the approved pages, while the real table adds a page nobody approved. Two Pages sections name nothing, so+// the written plan no longer matches.+test('verifyPlanProvenance halts when the written plan has a second Pages table, a quoted one included', () => {+ const quoted = ['```', '## Pages', '| Page | File | Purpose | Entities |', '|---|---|---|---|',+ '| Details | details.tsx | x | project |', '| Overview | overview.tsx | y | project |', '```'].join('\r\n');+ const written = WRITTEN+ .replace('Projects overview and details.', `Projects overview and details, like this:\r\n${quoted}`)+ .replace('| Overview | overview.tsx | Summary cards | project |', '| Overview | overview.tsx | Summary cards | project |\r\n| Admin | admin.tsx | Settings | project |');+ assert.equal(planTargets(written), null);+ assert.equal(verifyPlanProvenance({ planPath: tmpPlan(written), approvedPlan: PREVIEW }).ok, false);+ // CONTROL: a page whose name begins with "Pages" has a `### Pages …` specification, which is no second+ // Pages section of a written plan.+ const named = WRITTEN.replace('| Overview | overview.tsx |', '| Pages Admin | overview.tsx |').replace('### Overview', '### Pages Admin');+ assert.deepEqual(planTargets(named), { kind: 'create', targets: ['details.tsx', 'overview.tsx'] });+ assert.equal(verifyPlanProvenance({ planPath: tmpPlan(named), approvedPlan: PREVIEW }).ok, true);+});++// An edit plan quotes the page's earlier prompts, and a prompt can hold a Pages table: read by its content, the+// preview for one page and a written plan for ANOTHER were both "create a.tsx", and the edit of the wrong page was+// certified. The plan's file name says which kind it is, and only that kind's target is read.+test('verifyPlanProvenance reads an edit plan as an edit, whatever its quoted prompt holds', () => {+ const table = 'Build this:\n## Pages\n| Page | File |\n|---|---|\n| A | a.tsx |';+ const preview = EDIT_PREVIEW.replace('- **Data:** Mock data\n', `- **Data:** Mock data\n- **Original prompt:** ${table}\n`);+ const context = `\n## Original Page Context\n- **Original prompt (from prompt.txt):** ${table}\n`;+ assert.deepEqual(planTargets(preview, { kind: 'edit' }), { kind: 'edit', targets: [PAGE_ID] });+ const other = verifyPlanProvenance({ planPath: tmpPlan(EDIT_WRITTEN.replace(/6e0c28a2/g, '7f1d39b3') + context, EDIT), approvedPlan: preview });+ assert.equal(other.ok, false, 'an edit of another page');+ assert.match(other.error, /approved plan named 6e0c28a2/);+ // CONTROL: the same quoted prompt, the same page.+ const same = verifyPlanProvenance({ planPath: tmpPlan(EDIT_WRITTEN + context, EDIT), approvedPlan: preview });+ assert.equal(same.ok, true, same.error);+ // …and a create plan is read by its Pages table alone: without one it names nothing, never a page id in its text.+ assert.equal(planTargets(`# Genpage Plan\n- **Page ID:** ${PAGE_ID}\n`, { kind: 'create' }), null);+});++// The preview's prompt snippet may quote anything — a `## File Being Edited` section included, which, read first,+// named another page: the correct written plan then halted and a wrong one passed. The preview is read by its own+// Current State block, and the written plan by its File Being Edited section.+test('verifyPlanProvenance reads the preview by its Current State and the written plan by its own section', () => {+ const other = '7f1d39b3-cdbf-41ec-9186-d10fd5de6e35';+ const preview = EDIT_PREVIEW.replace('- **Data:** Mock data\n', `- **Data:** Mock data\n- **Original prompt:** Example:\n## File Being Edited\n- **Page ID:** ${other}\n`);+ assert.deepEqual(planTargets(preview, { kind: 'edit', doc: 'preview' }), { kind: 'edit', targets: [PAGE_ID] });+ assert.equal(verifyPlanProvenance({ planPath: tmpPlan(EDIT_WRITTEN, EDIT), approvedPlan: preview }).ok, true, 'the approved page passes');+ assert.equal(verifyPlanProvenance({ planPath: tmpPlan(EDIT_WRITTEN.replace(/6e0c28a2/g, '7f1d39b3'), EDIT), approvedPlan: preview }).ok, false, 'another page halts');+ // A written plan without its section names nothing, whatever else it quotes; nor does a preview without its block.+ assert.equal(planTargets(`# Genpage Edit Plan\n## Original Page Context\n- **File:** ${PAGE_ID}/page.tsx\n`, { kind: 'edit', doc: 'written' }), null);+ assert.equal(planTargets(`## Genpage Edit Plan\n## File Being Edited\n- **Page ID:** ${PAGE_ID}\n`, { kind: 'edit', doc: 'preview' }), null);+ // …and one whose section has neither a label nor a path names nothing: a page path quoted elsewhere in the plan is+ // not the page it edits.+ const bare = `# Genpage Edit Plan\n## File Being Edited\n- **App ID:** 11111111-2222-3333-4444-555555555555\n## Original Page Context\n- **File:** ${other}/page.tsx\n`;+ assert.equal(planTargets(bare, { kind: 'edit', doc: 'written' }), null);+ // CONTROL: a written plan whose section has no Page ID label is read by the page folder in the section's own path.+ const noLabel = EDIT_WRITTEN.replace(`- **Page ID:** ${PAGE_ID}\n`, '') + `\n## Original Page Context\n- **File:** ${other}/page.tsx\n`;+ assert.deepEqual(planTargets(noLabel, { kind: 'edit', doc: 'written' }), { kind: 'edit', targets: [PAGE_ID] });+});++test('verifyPlanProvenance halts when the planner wrote nothing, or the approval names no pages', () => {+ const missing = verifyPlanProvenance({ planPath: tmpPlan(), approvedPlan: PREVIEW });+ assert.equal(missing.ok, false);+ assert.match(missing.error, /planner did not write/);+ const vague = verifyPlanProvenance({ planPath: tmpPlan(WRITTEN), approvedPlan: 'Approved!' });+ assert.equal(vague.ok, false);+ assert.match(vague.error, /approved plan body names no pages/);+});++// An overlong id was truncated to its first 36 characters and certified. Both GUID patterns are bounded+// like the upload parser's (lib/genpage-cli.js parsePageId), and a Page ID label whose value is malformed+// makes the plan name nothing — never a GUID found elsewhere, since the edit worker reads that label.+test('an overlong or malformed page id is refused, never truncated to a valid-looking one', () => {+ const overlong = EDIT_WRITTEN.replace(`**Page ID:** ${PAGE_ID}`, `**Page ID:** ${PAGE_ID}deadbeef`);+ assert.equal(planTargets(overlong), null, 'a labelled id that runs on names nothing (the path still holds the valid one)');+ assert.equal(planTargets(EDIT_WRITTEN.replace(`**Page ID:** ${PAGE_ID}`, `**Page ID:** ${PAGE_ID}-x`)), null, 'a hyphen continues the token too');+ assert.equal(planTargets(EDIT_PREVIEW.replace(`${PAGE_ID}/page.tsx`, `deadbeef${PAGE_ID}/page.tsx`)), null, 'a folder GUID with a longer token in front');+ assert.equal(planTargets(`Edit deadbeef${PAGE_ID}/page.tsx\n`), null, '…in the folder fallback too');+ // CONTROLS: the id inside backticks or braces, or followed by punctuation, still ends cleanly.+ for (const shape of [`\`${PAGE_ID}\``, `{${PAGE_ID}}`, `${PAGE_ID}.`]) {+ assert.deepEqual(planTargets(EDIT_WRITTEN.replace(`**Page ID:** ${PAGE_ID}`, `**Page ID:** ${shape}`)), { kind: 'edit', targets: [PAGE_ID] }, shape);+ }+ const refused = verifyPlanProvenance({ planPath: tmpPlan(overlong, EDIT), approvedPlan: EDIT_PREVIEW });+ assert.equal(refused.ok, false);+ assert.match(refused.error, /targets no pages, but the approved plan named 6e0c28a2/);+ // Every label must hold the SAME well-formed id. A pattern search skipped a malformed first label and+ // certified a valid-looking one later in the document — a quoted prompt, say.+ const quoted = `${overlong}\n## User Request\n> "Change the page, **Page ID:** ${PAGE_ID}"\n`;+ assert.equal(planTargets(quoted), null, 'a malformed label is not rescued by a later valid one');+ const other = '7f1d39b3-cdbf-41ec-9186-d10fd5de6e35';+ assert.equal(planTargets(`${EDIT_WRITTEN}\n- **Page ID:** ${other}\n`), null, 'two labels in the section naming different pages are ambiguous');+ assert.deepEqual(planTargets(`${EDIT_WRITTEN}\n- **Page ID:** \`${PAGE_ID}\`\n`), { kind: 'edit', targets: [PAGE_ID] }, 'labels that agree are fine');+});++// The written plan copies the page's earlier prompts in full, and quoted text there may carry a label of+// its own. Only the structured `## File Being Edited` section is read, so such a prompt can no longer+// block every later edit of the page.+test('a Page ID label quoted in the embedded prompt neither blocks nor redirects an edit', () => {+ const other = '11111111-2222-3333-4444-555555555555';+ for (const prompt of [`…opens the details page (**Page ID:** ${other})…`, 'Show the **Page ID:** in the footer']) {+ const written = `${EDIT_WRITTEN}\n## Original Page Context\n- **Original prompt (from prompt.txt):** ${prompt}\n`;+ assert.deepEqual(planTargets(written), { kind: 'edit', targets: [PAGE_ID] }, prompt);+ assert.equal(verifyPlanProvenance({ planPath: tmpPlan(written, EDIT), approvedPlan: EDIT_PREVIEW }).ok, true, prompt);+ }+ // Without the section, the FIRST label is the plan's: a later one neither blocks nor rescues it.+ const bare = `# Genpage Edit Plan\n- **Page ID:** ${PAGE_ID}\n\nThe prompt said: Show the **Page ID:** in the footer\n`;+ assert.deepEqual(planTargets(bare), { kind: 'edit', targets: [PAGE_ID] });+ assert.equal(planTargets(`# Genpage Edit Plan\n- **Page ID:** ${PAGE_ID}x\n\n(**Page ID:** ${PAGE_ID})\n`), null);+ // A section without a label falls back to the folder in its absolute path, never to a quoted label.+ const noLabel = EDIT_WRITTEN.replace(`- **Page ID:** ${PAGE_ID}\n`, '') + `\n## Original Page Context\n(**Page ID:** ${other})\n`;+ assert.deepEqual(planTargets(noLabel), { kind: 'edit', targets: [PAGE_ID] });+});++// The approval PREVIEW has no `## File Being Edited` section: it names its page in its own `- **File:**`+// line and quotes the first ~100 characters of the page's prompt a few lines later. A label read anywhere+// came out of that quote and decided the approved target — on every later edit of that page, since its+// first prompt never changes.+test('a Page ID label quoted in the preview\u2019s prompt snippet neither blocks nor redirects the approval', () => {+ const other = '11111111-2222-3333-4444-555555555555';+ for (const snippet of ['…1. Show the **Page ID:** in the footer', `…1. Like **Page ID:** ${other}`, `Copy the layout of **File:** ${other}/page.tsx`]) {+ const preview = EDIT_PREVIEW.replace('- **Data:** Mock data\n', `- **Data:** Mock data\n- **Original prompt:** ${snippet}\n`);+ assert.deepEqual(planTargets(preview), { kind: 'edit', targets: [PAGE_ID] }, snippet);+ const verified = verifyPlanProvenance({ planPath: tmpPlan(EDIT_WRITTEN, EDIT), approvedPlan: preview });+ assert.equal(verified.ok, true, `${snippet}: ${verified.error}`);+ // …wherever the snippet sits relative to the File line.+ const snippetFirst = `## Genpage Edit Plan\n\n### Current State\n- **Original prompt:** ${snippet}\n- **File:** ${PAGE_ID}/page.tsx\n`;+ assert.deepEqual(planTargets(snippetFirst), { kind: 'edit', targets: [PAGE_ID] }, `${snippet}, before the File line`);+ }+ // The snippet is the prompt's first ~100 characters, newlines included, so a quoted label can even+ // BEGIN a line; the preview's own File line still decides.+ const multiLine = EDIT_PREVIEW.replace('- **Data:** Mock data\n', `- **Data:** Mock data\n- **Original prompt:** Build a details page\n- **Page ID:** ${other}\n`);+ assert.deepEqual(planTargets(multiLine), { kind: 'edit', targets: [PAGE_ID] });+ // Without a File line, a label that BEGINS a line is still read — and a mid-line one never is.+ assert.deepEqual(planTargets(`# Genpage Edit Plan\n- **Page ID:** ${PAGE_ID}\n`), { kind: 'edit', targets: [PAGE_ID] });+ assert.deepEqual(planTargets(`# Genpage Edit Plan\n**Page ID:** \`${PAGE_ID}\`\n`), { kind: 'edit', targets: [PAGE_ID] });+ assert.equal(planTargets(`# Genpage Edit Plan\nThe prompt said: like **Page ID:** ${other}\n`), null);+});++// The approval sidecar is written IN PLACE by the orchestrator after `prepare`, so a link at its+// conventional path — or a hard link, whose other name the write would rewrite — is refused up front.+test('prepare refuses an approval sidecar that is a link, a hard link or a folder, and keeps a plain stale one', (t) => {+ const planPath = tmpPlan('stale\n');+ const dir = path.dirname(planPath);+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-plan-outside-'));+ t.after(() => { fs.rmSync(dir, { recursive: true, force: true }); fs.rmSync(outside, { recursive: true, force: true }); });+ const sidecar = path.join(dir, '.approved-genpage-plan.md');+ fs.writeFileSync(path.join(outside, 'victim.md'), 'keep me');+ fs.linkSync(path.join(outside, 'victim.md'), sidecar);+ const hard = preparePlanProvenance({ planPath });+ assert.equal(hard.ok, false);+ assert.match(hard.error, /\.approved-genpage-plan\.md is not a plain file/);+ assert.equal(fs.readFileSync(planPath, 'utf8'), 'stale\n', 'nothing is quarantined while it refuses');+ fs.unlinkSync(sidecar);+ fs.mkdirSync(sidecar);+ assert.equal(preparePlanProvenance({ planPath }).ok, false, 'a folder there is refused too');+ fs.rmdirSync(sidecar);+ if (linkOrSkip(t, path.join(outside, 'victim.md'), sidecar, 'file')) {+ assert.equal(preparePlanProvenance({ planPath }).ok, false, 'and a symbolic link');+ fs.unlinkSync(sidecar);+ }+ fs.writeFileSync(sidecar, 'last run\n');+ assert.equal(preparePlanProvenance({ planPath }).ok, true, 'a plain sidecar from an earlier run is simply overwritten later');+ assert.equal(fs.readFileSync(path.join(outside, 'victim.md'), 'utf8'), 'keep me');+});++// A link at either path this writes through is refused, dangling ones included: existsSync called a+// dangling link at the plan path absent and left it for the planner to write through, and+// mkdir({ recursive }) plus rename followed a link at `.genpage-provenance` out of the working directory.+function linkOrSkip(t, target, at, type) {+ try { fs.symlinkSync(target, at, type); return true; } catch (e) { t.skip(`cannot create a ${type} link here: ${e.message}`); return false; }+}++test('prepare refuses a link or a folder at the plan path, dangling links included', (t) => {+ const planPath = tmpPlan();+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-plan-outside-'));+ t.after(() => { fs.rmSync(path.dirname(planPath), { recursive: true, force: true }); fs.rmSync(outside, { recursive: true, force: true }); });+ if (!linkOrSkip(t, path.join(outside, 'approved.md'), planPath, 'file')) return;+ const dangling = preparePlanProvenance({ planPath });+ assert.equal(dangling.ok, false, 'a dangling link is not "no plan here"');+ assert.match(dangling.error, /symbolic link or junction/);+ assert.ok(fs.lstatSync(planPath).isSymbolicLink(), 'left for the user to remove, not followed');+ fs.writeFileSync(path.join(outside, 'approved.md'), 'outside\n');+ assert.equal(preparePlanProvenance({ planPath }).ok, false, 'a live link too');+ assert.equal(fs.readFileSync(path.join(outside, 'approved.md'), 'utf8'), 'outside\n', 'its target is untouched');+ fs.unlinkSync(planPath);+ fs.mkdirSync(planPath);+ const folder = preparePlanProvenance({ planPath });+ assert.equal(folder.ok, false);+ assert.match(folder.error, /not a regular file/);+});++test('prepare refuses a quarantine folder that is a link or a file, and moves nothing', (t) => {+ const planPath = tmpPlan('stale\n');+ const dir = path.dirname(planPath);+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-plan-outside-'));+ t.after(() => { fs.rmSync(dir, { recursive: true, force: true }); fs.rmSync(outside, { recursive: true, force: true }); });+ const quarantine = path.join(dir, '.genpage-provenance');+ if (!linkOrSkip(t, outside, quarantine, 'junction')) return;+ const linked = preparePlanProvenance({ planPath });+ assert.equal(linked.ok, false);+ assert.match(linked.error, /not a plain directory/);+ assert.equal(fs.readFileSync(planPath, 'utf8'), 'stale\n', 'the stale plan is not moved');+ assert.deepEqual(fs.readdirSync(outside), [], 'nothing lands outside the working directory');+ fs.unlinkSync(quarantine);+ fs.writeFileSync(quarantine, 'not a folder');+ assert.match(preparePlanProvenance({ planPath }).error, /not a plain directory/);+});++// A dangling link already at the quarantine name is an entry like any other: the stale plan takes the+// next free slot, rather than replacing the link.+test('prepare never replaces an existing entry in the quarantine folder, a dangling link included', (t) => {+ const planPath = tmpPlan('stale\n');+ const dir = path.dirname(planPath);+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const quarantine = path.join(dir, '.genpage-provenance');+ fs.mkdirSync(quarantine);+ const hash = require('node:crypto').createHash('sha256').update('stale\n', 'utf8').digest('hex').slice(0, 12);+ const taken = path.join(quarantine, `genpage-plan.stale-${hash}.md`);+ const takenToo = path.join(quarantine, `genpage-plan.stale-${hash}-1.md`);+ if (!linkOrSkip(t, path.join(dir, 'gone.md'), taken, 'file')) return;+ fs.symlinkSync(path.join(dir, 'gone-too.md'), takenToo, 'file');+ const r = preparePlanProvenance({ planPath });+ assert.equal(r.ok, true, r.error);+ assert.equal(path.basename(r.quarantinedPath), `genpage-plan.stale-${hash}-2.md`, 'both the base name and the first suffix are taken');+ assert.ok(fs.lstatSync(taken).isSymbolicLink() && fs.lstatSync(takenToo).isSymbolicLink(), 'the existing entries are untouched');+});++test('prepare reports a failed quarantine as a result, not a throw', (t) => {+ const planPath = tmpPlan('stale\n');+ t.after(() => fs.rmSync(path.dirname(planPath), { recursive: true, force: true }));+ t.mock.method(fs, 'renameSync', () => { throw new Error('EBUSY: resource busy or locked'); });+ const r = preparePlanProvenance({ planPath });+ assert.equal(r.ok, false);+ assert.match(r.error, /could not quarantine the earlier plan: EBUSY/);+});++// Only "nothing there" means nothing there: a path that cannot even be inspected is not a missing plan —+// reading it as one would skip the quarantine and let a stale plan pass for this run's.+test('a plan path that cannot be inspected or read fails the gate instead of reading as absent', (t) => {+ const planPath = tmpPlan(WRITTEN);+ t.after(() => fs.rmSync(path.dirname(planPath), { recursive: true, force: true }));+ const denied = () => { const e = new Error('EACCES: permission denied'); e.code = 'EACCES'; throw e; };+ const lstat = t.mock.method(fs, 'lstatSync', denied);+ const prep = preparePlanProvenance({ planPath });+ assert.equal(prep.ok, false);+ assert.match(prep.error, /could not quarantine the earlier plan: EACCES/);+ const inspect = verifyPlanProvenance({ planPath, approvedPlan: PREVIEW });+ assert.equal(inspect.ok, false);+ assert.match(inspect.error, /could not inspect .*EACCES/);+ lstat.mock.restore();+ t.mock.method(fs, 'readFileSync', denied);+ const read = verifyPlanProvenance({ planPath, approvedPlan: PREVIEW });+ assert.equal(read.ok, false);+ assert.match(read.error, /could not read .*EACCES/);+});++// What verify certifies must be the file written in place, not whatever a link points at.+test('verify refuses a written plan that is a link or a folder', (t) => {+ const planPath = tmpPlan();+ const dir = path.dirname(planPath);+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.writeFileSync(path.join(dir, 'elsewhere.md'), WRITTEN);+ if (!linkOrSkip(t, path.join(dir, 'elsewhere.md'), planPath, 'file')) return;+ const linked = verifyPlanProvenance({ planPath, approvedPlan: PREVIEW });+ assert.equal(linked.ok, false, 'a link to a matching plan is still not the plan');+ assert.match(linked.error, /not a plain file \(a link, junction, hard link or folder\)/);+ fs.unlinkSync(planPath);+ fs.mkdirSync(planPath);+ assert.match(verifyPlanProvenance({ planPath, approvedPlan: PREVIEW }).error, /not a plain file \(a link, junction, hard link or folder\)/);+});++// The skill acts on the CLI's exit code and JSON line, so that contract is pinned end to end.+test('the CLI prepares and verifies by exit code: 0 on success, 3 on a failed gate, 1 on a usage error', () => {+ const { spawnSync } = require('node:child_process');+ const script = path.join(__dirname, '..', 'genpage-plan-provenance.js');+ const run = (...args) => spawnSync(process.execPath, [script, ...args], { encoding: 'utf8' });+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-plan-prov-cli-'));+ try {+ const planPath = path.join(dir, 'genpage-plan.md');+ const approved = path.join(dir, '.approved-genpage-plan.md');+ fs.writeFileSync(planPath, 'stale\n');+ const prep = run('prepare', '--plan', planPath);+ assert.equal(prep.status, 0, prep.stdout);+ assert.equal(JSON.parse(prep.stdout).ok, true);+ assert.equal(fs.existsSync(planPath), false, 'quarantined');+ // A second prepare with nothing to move is still a success, and a colliding stale name gets its own slot.+ assert.equal(run('prepare', '--plan', planPath).status, 0);+ fs.writeFileSync(planPath, 'stale\n');+ const again = JSON.parse(run('prepare', '--plan', planPath).stdout);+ assert.notEqual(again.quarantinedPath, JSON.parse(prep.stdout).quarantinedPath, 'an identical stale plan does not overwrite the first');++ fs.writeFileSync(approved, PREVIEW);+ const missing = run('verify', '--plan', planPath, '--approved', `@${approved}`);+ assert.equal(missing.status, 3);+ assert.match(JSON.parse(missing.stdout).error, /planner did not write/);+ fs.writeFileSync(planPath, WRITTEN);+ assert.equal(run('verify', '--plan', planPath, '--approved', `@${approved}`).status, 0);+ fs.writeFileSync(planPath, WRITTEN.replace('details.tsx', 'other.tsx'));+ assert.equal(run('verify', '--plan', planPath, '--approved', `@${approved}`).status, 3);++ assert.equal(run('verify', '--plan', planPath).status, 3, 'verify without --approved fails the gate');+ // An approved file that is missing, or a link rather than the file the orchestrator wrote, fails the+ // gate with a result — it used to throw out of the CLI.+ const gone = run('verify', '--plan', planPath, '--approved', `@${path.join(dir, 'no-such-approved.md')}`);+ assert.equal(gone.status, 3, gone.stderr);+ assert.match(JSON.parse(gone.stdout).error, /^could not read the approved plan: ENOENT/);+ const linkedApproved = path.join(dir, 'linked-approved.md');+ let linked = true;+ try { fs.symlinkSync(approved, linkedApproved, 'file'); } catch { linked = false; }+ if (linked) {+ const viaLink = run('verify', '--plan', planPath, '--approved', `@${linkedApproved}`);+ assert.equal(viaLink.status, 3);+ assert.match(JSON.parse(viaLink.stdout).error, /could not read the approved plan: .* is not a regular file/);+ }+ assert.equal(run('prepare').status, 3, 'prepare without --plan fails the gate');+ assert.equal(run('bogus').status, 1, 'an unknown command is a usage error');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++// The working directory itself must not be a link — the rule the page-file gate and the manifest generator+// apply. With no plan there yet, prepare returned ok at once, and the planner then wrote the plan (and the+// orchestrator its approval sidecar) wherever a link planted at the working directory points.+test('prepare refuses a working directory that is itself a link or junction, even with no plan yet', (t) => {+ const parent = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-plan-rootlink-'));+ t.after(() => fs.rmSync(parent, { recursive: true, force: true }));+ const real = path.join(parent, 'real');+ fs.mkdirSync(real);+ const linked = path.join(parent, 'linked');+ fs.symlinkSync(real, linked, 'junction');+ const refused = preparePlanProvenance({ planPath: path.join(linked, 'genpage-plan.md') });+ assert.equal(refused.ok, false);+ assert.match(refused.error, /is a symbolic link or junction — pass the directory it points to as the working directory$/);+ assert.equal(preparePlanProvenance({ planPath: path.join(real, 'genpage-plan.md') }).ok, true, 'the real directory is fine');+ fs.mkdirSync(path.join(real, 'app'));+ assert.equal(preparePlanProvenance({ planPath: path.join(linked, 'app', 'genpage-plan.md') }).ok, true, 'so is one below a linked ancestor');+});++// The page-file rule allows a harmless `.` segment and normalizes it for identity, so provenance compares+// the same spelling: an approved `./overview.tsx` and a written `overview.tsx` are one page.+test('create targets are compared with . segments dropped', () => {+ const dotted = PREVIEW.replace('| overview.tsx |', '| ./overview.tsx |');+ assert.notEqual(dotted, PREVIEW, 'precondition: the preview names ./overview.tsx');+ assert.deepEqual(planTargets(dotted), { kind: 'create', targets: ['details.tsx', 'overview.tsx'] });+ const verified = verifyPlanProvenance({ planPath: tmpPlan(WRITTEN), approvedPlan: dotted });+ assert.equal(verified.ok, true, verified.error);+});++// The page must END the preview's File line: `page\.tsx\b` also took `<guid>/page.tsx.bak`, a different file,+// and since an edit's provenance compares only the GUID, that approval certified a plan for the real page.+test('a File line or path naming something other than page.tsx itself names nothing', () => {+ for (const tail of ['page.tsx.bak', 'page.tsxx', 'page.tsx-old', 'page.tsx~', 'page.tsx+old', 'page.tsx#1', 'page.tsx/old.tsx', 'page.tsx(1)', 'page.tsx:alt', 'page.tsx\u00e9']) {+ assert.equal(planTargets(EDIT_PREVIEW.replace(`${PAGE_ID}/page.tsx`, `${PAGE_ID}/${tail}`)), null, tail);+ }+ // CONTROLS: a backticked value, trailing blanks, and Windows line endings still end cleanly.+ for (const shape of [`\`${PAGE_ID}/page.tsx\``, `${PAGE_ID}/page.tsx `]) {+ assert.deepEqual(planTargets(EDIT_PREVIEW.replace(`${PAGE_ID}/page.tsx`, shape)), { kind: 'edit', targets: [PAGE_ID] }, shape);+ }+ assert.deepEqual(planTargets(EDIT_PREVIEW.replace(/\n/g, '\r\n')), { kind: 'edit', targets: [PAGE_ID] });+ // …and so does sentence punctuation, a closing mark or a note after the path, on the File line and in the+ // folder path. Another page's path sits AHEAD of the File line, so only the File line itself can answer.+ const other = '11111111-2222-3333-4444-555555555555';+ const ahead = `## Genpage Edit Plan\n\nLike ${other}/page.tsx\n\n${EDIT_PREVIEW.replace('## Genpage Edit Plan\n\n', '')}`;+ for (const shape of [`${PAGE_ID}/page.tsx.`, `${PAGE_ID}/page.tsx,`, `${PAGE_ID}/page.tsx;`, `\`${PAGE_ID}/page.tsx\`.`, `${PAGE_ID}/page.tsx)`, `${PAGE_ID}/page.tsx (edit)`]) {+ assert.deepEqual(planTargets(ahead.replace(`${PAGE_ID}/page.tsx`, shape)), { kind: 'edit', targets: [PAGE_ID] }, shape);+ }+ for (const tail of ['.', ':', ')', '"', '**', '|', '<br>', '}', '\u201d', '\u00bb', '\u2014the page']) {+ assert.deepEqual(planTargets(`Edit ${PAGE_ID}/page.tsx${tail}\n`), { kind: 'edit', targets: [PAGE_ID] }, tail);+ }+ assert.deepEqual(planTargets(`Edit ${PAGE_ID}/page.tsx`), { kind: 'edit', targets: [PAGE_ID] }, 'at the very end of the text');+ assert.equal(planTargets(`Edit ${PAGE_ID}/page.tsx.bak\n`), null, 'but an extension after it is another file');+});++// The rule says what CONTINUES a file name, not what ends one: a path the folder fallback cannot end is+// skipped, and the next one wins. Listing closers instead skipped a written plan's real path when HTML or a+// curly quote followed it, and the page quoted in its original prompt became the target.+test('the folder fallback is not diverted to a later path by a mark it does not list', () => {+ const other = '11111111-2222-3333-4444-555555555555';+ const written = (line) => `# Genpage Edit Plan\n\n## File Being Edited\n- **Absolute path:** ${line}\n- **App ID:** 1\n\n## Original Page Context\nsee ${other}/page.tsx\n`;+ for (const line of [`D:/work/edit/${PAGE_ID}/page.tsx<br>`, `\u201cD:\\work\\edit\\${PAGE_ID}\\page.tsx\u201d`, `D:\\work\\edit\\${PAGE_ID}\\page.tsx}`]) {+ assert.deepEqual(planTargets(written(line)), { kind: 'edit', targets: [PAGE_ID] }, line);+ }+ // CONTROL: a path that does name another file is still skipped for the next one.+ assert.deepEqual(planTargets(written(`D:/work/edit/${PAGE_ID}/page.tsx.bak`)), { kind: 'edit', targets: [other] });+});++// A preview names its page in its Current State block's File line and nowhere else. A block whose File line is+// missing or names another file names NOTHING: reading on found a path or a label quoted from the page's prompt,+// and approved another page.+test('a preview whose Current State block has no valid File line names nothing', () => {+ const other = '11111111-2222-3333-4444-555555555555';+ const preview = (fileLine) => `## Genpage Edit Plan\n\n### Current State\n${fileLine}- **Original prompt:** like ${other}/page.tsx\n- **Page ID:** ${other}\n`;+ assert.equal(planTargets(preview(`- **File:** ${PAGE_ID}/page.tsx.bak\n`)), null, 'a File line naming another file');+ assert.equal(planTargets(preview('')), null, 'no File line at all');+ assert.deepEqual(planTargets(preview(`- **File:** ${PAGE_ID}/page.tsx\n`)), { kind: 'edit', targets: [PAGE_ID] }, 'CONTROL: a valid File line');+ // …which may carry a path in front of the page folder, as the written plan's absolute path does.+ for (const at of ['D:\\work\\edit\\', 'D:/work/edit/', './', '`D:\\My Files\\edit\\']) {+ const tail = at.startsWith('`') ? `${PAGE_ID}\\page.tsx\`` : `${PAGE_ID}/page.tsx`;+ assert.deepEqual(planTargets(preview(`- **File:** ${at}${tail}\n`)), { kind: 'edit', targets: [PAGE_ID] }, at);+ assert.equal(planTargets(preview(`- **File:** ${at}${PAGE_ID}/page.tsx.bak\n`)), null, `${at}: still only page.tsx`);+ assert.equal(planTargets(preview(`- **File:** ${at}deadbeef${PAGE_ID}/page.tsx\n`)), null, `${at}: still a whole id`);+ }+ assert.equal(verifyPlanProvenance({ planPath: tmpPlan(EDIT_WRITTEN.replace(/6e0c28a2/g, '7f1d39b3'), EDIT), approvedPlan: preview('') }).ok, false, 'and verify halts');+});++// The preview's File line is read from its own `### Current State` block: a `- **File:**` bullet quoted from the+// page's prompt ahead of that block decided the target.+test('the preview is read by the File line in its own Current State block', () => {+ const other = '11111111-2222-3333-4444-555555555555';+ const quotedFirst = `## Genpage Edit Plan\n\n> The maker asked:\n- **File:** ${other}/page.tsx\n\n${EDIT_PREVIEW.replace('## Genpage Edit Plan\n\n', '')}`;+ assert.deepEqual(planTargets(quotedFirst), { kind: 'edit', targets: [PAGE_ID] });+ assert.equal(verifyPlanProvenance({ planPath: tmpPlan(EDIT_WRITTEN, EDIT), approvedPlan: quotedFirst }).ok, true);+});++// A hard link at the plan path is a plain file to lstat, yet quarantining it renamed only this name — the+// plan stayed reachable through the other — and the planner's write in place rewrites every name.+test('prepare and verify refuse a hard-linked plan', (t) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-plan-hardlink-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const planPath = path.join(dir, 'genpage-edit-plan.md');+ const outside = path.join(dir, 'elsewhere.md');+ fs.writeFileSync(outside, EDIT_WRITTEN);+ fs.linkSync(outside, planPath);+ const prepared = preparePlanProvenance({ planPath });+ assert.equal(prepared.ok, false);+ assert.match(prepared.error, /is a hard link \(2 names for one file\) — remove it and re-run$/);+ assert.ok(fs.existsSync(planPath), 'nothing is quarantined');+ const verified = verifyPlanProvenance({ planPath, approvedPlan: EDIT_PREVIEW });+ assert.equal(verified.ok, false);+ assert.match(verified.error, /is not a plain file \(a link, junction, hard link or folder\)/);+});diff --git a/plugins/model-apps/scripts/tests/genpage-upload.test.js b/plugins/model-apps/scripts/tests/genpage-upload.test.jsindex 8237c9772..c91e61b4b 100644--- a/plugins/model-apps/scripts/tests/genpage-upload.test.js+++ b/plugins/model-apps/scripts/tests/genpage-upload.test.js@@ -17,7 +17,7 @@ const os = require('node:os');const path = require('node:path');const fs = require('node:fs');-const { main } = require('../genpage-upload.js');+const { main, notPlainFile } = require('../genpage-upload.js');const { buildPacInvocation, makeGenpageCli } = require('../lib/genpage-cli.js');const dirs = [];@@ -153,6 +153,95 @@ test('a hostile multi-line prompt reaches upload() byte-identical when passed byassert.strictEqual(r.payload.pageId, '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8');});+// The page's display name travelled on the command line (`--name "<name>"`): PowerShell expanded `$(…)` in it before+// the script ran — a name could run a command — and `Revenue $100` arrived as `Revenue `. By file it keeps every+// character; the line break an editor adds at its end is not part of it.+test('a display name passed by file reaches upload() intact, and a blank or doubled one is refused', async () => {+ const d = tmp();+ const pf = path.join(d, 'prompt.txt');+ const af = path.join(d, 'agent.txt');+ const nf = path.join(d, 'page-name.txt');+ fs.writeFileSync(pf, 'Build the revenue page', 'utf8');+ fs.writeFileSync(af, 'Initial deploy', 'utf8');+ const NAME = 'Revenue $100 \u2014 "Q3" $(whoami) `x` 100% & more';+ fs.writeFileSync(nf, `\uFEFF${NAME}\r\n`, 'utf8');+ const base = ['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'a1', '--code-file', 'page.tsx', '--prompt-file', pf, '--agent-message-file', af];+ const cli = capturingCli();+ const r = await runMain([...base, '--name-file', nf], cli);+ assert.strictEqual(r.ok, true, JSON.stringify(r.payload));+ assert.strictEqual(cli.calls[0].name, NAME, 'every character, and no BOM or trailing line break');+ const both = capturingCli();+ const doubled = await runMain([...base, '--name', 'x', '--name-file', nf], both);+ assert.strictEqual(doubled.ok, false);+ assert.match(doubled.payload.error, /only one of --name or --name-file/);+ assert.strictEqual(both.calls.length, 0);+ fs.writeFileSync(nf, '\r\n', 'utf8');+ const empty = capturingCli();+ const blank = await runMain([...base, '--name-file', nf], empty);+ assert.strictEqual(blank.ok, false);+ assert.match(blank.payload.error, /the page name resolved to empty/);+ assert.strictEqual(empty.calls.length, 0, 'no generated name deployed in place of the one supplied');+});++// The skill writes these files into the working directory just before the upload, and a write through a link left at+// one of those names — a symbolic link or junction, or a hard link — rewrote the file it points to, outside the working+// directory included. An input that is not a plain file stops the upload, and says the other file may have changed.+test('a prompt, agent-message, name, connectors or actions file that is a link or a folder stops the upload', async (t) => {+ const d = tmp();+ const outside = tmp();+ const plain = (name, text) => { const p = path.join(d, name); fs.writeFileSync(p, text, 'utf8'); return p; };+ const pf = plain('prompt.txt', 'Build the revenue page');+ const af = plain('agent-message.txt', 'Initial deploy');+ const nf = plain('page-name.txt', 'Revenue');+ const cf = plain('connectors.json', '[]');+ const xf = plain('actions.json', '[]');+ const victim = path.join(outside, 'victim.txt');+ fs.writeFileSync(victim, 'not the skill\'s file', 'utf8');+ const argv = (over = {}) => {+ const files = { 'prompt-file': pf, 'agent-message-file': af, 'name-file': nf, connectors: cf, actions: xf, ...over };+ return ['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'a1', '--code-file', 'page.tsx',+ ...Object.entries(files).flatMap(([k, v]) => [`--${k}`, v])];+ };+ // CONTROL: every input a plain file — the upload runs.+ const ok = capturingCli();+ assert.strictEqual((await runMain(argv(), ok)).ok, true);+ assert.strictEqual(ok.calls.length, 1);+ for (const flag of ['prompt-file', 'agent-message-file', 'name-file', 'connectors', 'actions']) {+ const hard = path.join(d, `hard-${flag}`);+ fs.linkSync(victim, hard);+ const cli = capturingCli();+ const r = await runMain(argv({ [flag]: hard }), cli);+ assert.strictEqual(r.ok, false, flag);+ assert.match(r.payload.error, new RegExp(`^--${flag} .*hard-${flag} is a hard link \\(2 names for one file\\)`), flag);+ assert.match(r.payload.error, /changed its other names too/, flag);+ assert.strictEqual(cli.calls.length, 0, `${flag}: nothing uploaded`);+ fs.unlinkSync(hard);+ }+ const folder = path.join(d, 'folder.txt');+ fs.mkdirSync(folder);+ const inFolder = capturingCli();+ const r = await runMain(argv({ 'name-file': folder }), inFolder);+ assert.strictEqual(r.ok, false);+ assert.match(r.payload.error, /^--name-file .*folder\.txt is not a plain file \(a folder or a special file\)/);+ assert.strictEqual(inFolder.calls.length, 0);+ const sym = path.join(d, 'sym-prompt.txt');+ try { fs.symlinkSync(victim, sym, 'file'); } catch (e) { t.skip(`cannot create a file symlink here: ${e.message}`); return; }+ const viaLink = capturingCli();+ const s = await runMain(argv({ 'prompt-file': sym }), viaLink);+ assert.strictEqual(s.ok, false);+ assert.match(s.payload.error, /^--prompt-file .*sym-prompt\.txt is a symbolic link or junction, not a file written in place — writing it may have changed the file it points to/);+ assert.strictEqual(viaLink.calls.length, 0);+});++// Fail closed: an input that cannot be inspected is not one proven to be a plain file. A missing one is left to the+// read, which says it could not be read.+test('an input file that cannot be inspected is refused; a missing one is left to the read', (t) => {+ const d = tmp();+ assert.strictEqual(notPlainFile(path.join(d, 'absent.txt')), null);+ t.mock.method(fs, 'lstatSync', () => { throw Object.assign(new Error('operation not permitted'), { code: 'EPERM' }); });+ assert.match(notPlainFile(path.join(d, 'prompt.txt')), /prompt\.txt could not be inspected \(EPERM\)/);+});+test('a downloaded conversation transcript survives an update by file', async () => {const d = tmp();const pf = path.join(d, 'prompt.txt');@@ -163,8 +252,8 @@ test('a downloaded conversation transcript survives an update by file', async ()'--page-id', '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d', '--prompt-file', pf, '--agent-message', 'Re-upload after edit'], cli);assert.strictEqual(r.ok, true);- // \r\n is normalized by neither side: only a SINGLE trailing newline is stripped, so every- // interior line break — which is what makes a transcript a transcript — is preserved.+ // \r\n is normalized by neither side, and nothing is trimmed — not even a trailing newline — so every+ // line break, which is what makes a transcript a transcript, is preserved.assert.strictEqual(cli.calls[0].prompt, TRANSCRIPT, 'the transcript must not be flattened');assert.strictEqual(cli.calls[0].pageId, '9f1b2c3d-4e5f-4a6b-8c9d-0e1f2a3b4c5d');assert.strictEqual(r.payload.updated, true, 'an upload carrying --page-id is an update');@@ -220,7 +309,7 @@ test('a U+FEFF inside the prompt body is preserved', async () => {assert.strictEqual(cli.calls[0].prompt, body, 'only a LEADING BOM is an encoding marker');});-// Adversarial review (astra HIGH 3 / grok MEDIUM 4). The wrapper OMITS `--add-to-sitemap` on an+// The wrapper OMITS `--add-to-sitemap` on an// update as a backstop, but omission is not an answer to an explicit contradictory request: the// caller believes a placement happened and it never did. The docs claimed "refused"; now it is.test('--add-to-sitemap combined with --page-id is refused, not silently dropped', async () => {@@ -232,7 +321,7 @@ test('--add-to-sitemap combined with --page-id is refused, not silently dropped'assert.strictEqual(cli.calls.length, 0, 'nothing may be uploaded on a contradictory request');});-// grok MEDIUM 5 — `upload()` substitutes `Generative page <name>` for a blank prompt. That is fine+// `upload()` substitutes `Generative page <name>` for a blank prompt. That is fine// when no prompt was supplied, but a caller who passed --prompt-file asked for THAT text, and// deploying a generated placeholder instead is exactly the provenance break this path exists to// prevent. A blank, newline-only or BOM-only file is the realistic way it happens.@@ -257,7 +346,7 @@ test('a prompt file that resolves to empty is refused rather than silently defauassert.strictEqual(cli.calls[0].prompt, 'A real approved prompt');});-// astra HIGH 3b — the worse half. A CREATE that asked for placement, crashed mid-flight and was+// The worse half of the sitemap problem. A CREATE that asked for placement, crashed mid-flight and was// recovered as an UPDATE leaves the page deployed but absent from the app's navigation, and the old// code returned plain success. An unreachable page is an incomplete deployment, not a success.test('a page deployed but left out of the sitemap is reported as incomplete, with its id', async () => {@@ -369,9 +458,9 @@ test('the standalone flags are emitted, and --add-to-sitemap only on a create',assert.strictEqual(update[update.indexOf('--data-sources') + 1], 'account,contact');});-// astra MEDIUM 8 — the option tests above call the LIBRARY directly and mostly check flag presence.-// Astra mutated `main()` to drop forwarding of model/connectors/actions/addToSitemap, and replaced-// the library's model and file arguments with "WRONG", and every committed test stayed green. So the+// The option tests above call the LIBRARY directly and mostly check flag presence. A mutation run+// that made `main()` drop forwarding of model/connectors/actions/addToSitemap, and replaced+// the library's model and file arguments with "WRONG", left every committed test green. So the// wiring from CLI flag → wrapper → actual pac invocation was unprotected.//// This drives the REAL wrapper through `main()` and asserts exact flag/value pairs on the captured@@ -744,7 +833,7 @@ test('the current bindings are found even when --page-id casing differs from pacassert.deepStrictEqual(seen[0].dataSources, ['contoso_ticket'], 'the bindings must still be preserved');});-// --- Review follow-ups on the unbind guard --------------------------------------------------------+// --- The unbind guard: flag values that must NOT authorise clearing --------------------------------// `parseArgs` yields the STRING "false" for `--clear-data-sources=false`, which is truthy. Testing// the raw flag read an explicit refusal to clear as permission to clear — unbinding the page the@@ -844,7 +933,7 @@ test('a cleanup failure does not fail an update whose bindings were read', asyncassert.deepStrictEqual(cli.calls[0].dataSources, ['contoso_ticket']);});-// --- PR review: --prompt-file must deliver the file byte-for-byte -------------------------------+// --- --prompt-file must deliver the file byte-for-byte --------------------------------------------// A trailing newline used to be stripped here while the direct /app-builder wrapper path preserved// it, so the SAME text deployed differently depending on which path carried it. This transport// exists precisely so an arbitrary prompt survives verbatim.diff --git a/plugins/model-apps/scripts/tests/genpage-worker-output.test.js b/plugins/model-apps/scripts/tests/genpage-worker-output.test.jsnew file mode 100644index 000000000..0f9e8e09f--- /dev/null+++ b/plugins/model-apps/scripts/tests/genpage-worker-output.test.js@@ -0,0 +1,288 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');++const { validatePageOutput, stampPageTarget } = require('../genpage-worker-output.js');++function write(code) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-worker-output-'));+ const filePath = path.join(dir, 'page.tsx');+ fs.writeFileSync(filePath, code, 'utf8');+ return filePath;+}++test('validatePageOutput rejects a truncated worker file before dispatch is accepted', () => {+ const filePath = write('export default function GeneratedComponent() {\n return <div>truncated\n');++ const result = validatePageOutput({ filePath });++ assert.equal(result.ok, false);+ assert.match(result.problems.join('\n'), /unbalanced brackets|truncated/i);++ // Cut right after a complete statement: the file ends in plain code, so only the bracket count+ // sees that the function never closed.+ const balancedTail = validatePageOutput({ filePath: write('export default function GeneratedComponent() {\n const a = 1;\n return null;\n') });+ assert.equal(balancedTail.ok, false);+ assert.deepEqual(balancedTail.problems, ['unbalanced brackets — output looks truncated']);++ // Cut INSIDE the export statement, nothing is open yet, so the brackets balance — the export+ // itself has to be complete: a function reaches its body, a bare name is one the module has.+ for (const code of [+ 'import * as React from "react";\nexport default function GeneratedComponent(props: Props)',+ 'import * as React from "react";\nexport default func',+ 'const GeneratedComponent = () => <div/>;\nexport default GeneratedComp',+ ]) {+ const cut = validatePageOutput({ filePath: write(code) });+ assert.equal(cut.ok, false, code);+ assert.match(cut.problems.join('\n'), /default export/, code);+ }++ // A cut that leaves every bracket balanced and the export intact: inside the JSX of an arrow+ // export, or after an operator.+ for (const code of [+ 'export default (props) => <GeneratedComponent title="x',+ 'export default () => <div>Loading',+ 'const GeneratedComponent = () => <div/>;\nexport default GeneratedComponent;\nconst total = count *',+ ]) {+ const cut = validatePageOutput({ filePath: write(code) });+ assert.equal(cut.ok, false, code);+ assert.match(cut.problems.join('\n'), /stops mid-statement/, code);+ }+});++test('validatePageOutput rejects prose or fenced output that only mentions a default export', () => {+ for (const code of [+ 'The worker should write export default GeneratedComponent here.\n',+ '```tsx\nexport default function GeneratedComponent() { return <div/>; }\n```\n',+ ]) {+ const result = validatePageOutput({ filePath: write(code) });+ assert.equal(result.ok, false, code);+ }+});++test('validatePageOutput accepts a complete TSX module', () => {+ const filePath = write('export default function GeneratedComponent() {\n return <div>ok</div>;\n}\n');++ const result = validatePageOutput({ filePath });++ assert.equal(result.ok, true);+ assert.deepEqual(result.problems, []);+});++// The skill runs the CLI and acts on its exit code: 0 accepts the worker's file, 3 sends the page to+// the inline fallback. A missing or empty file is output that failed, never a pass.+test('the CLI accepts with exit 0 and sends a failed page to the fallback with exit 3', () => {+ const { spawnSync } = require('node:child_process');+ const script = path.join(__dirname, '..', 'genpage-worker-output.js');+ const run = (...args) => spawnSync(process.execPath, [script, ...args], { encoding: 'utf8' });+ const good = run('--file', write('export default function GeneratedComponent() {\n return <div>ok</div>;\n}\n'));+ assert.equal(good.status, 0, good.stdout);+ assert.equal(JSON.parse(good.stdout).ok, true);+ const truncated = run('--file', write('export default function GeneratedComponent() {\n return <div>truncated\n'));+ assert.equal(truncated.status, 3);+ assert.equal(JSON.parse(truncated.stdout).ok, false);+ const absent = run('--file', path.join(os.tmpdir(), `genpage-never-written-${process.pid}.tsx`));+ assert.equal(absent.status, 3);+ assert.deepEqual(JSON.parse(absent.stdout).problems, ['file was never written']);+ assert.deepEqual(JSON.parse(run('--file', write(' \n')).stdout).problems, ['file is empty']);+ assert.equal(run().status, 3, 'no --file is not a pass');+});++// A folder or an unreadable file at the page path threw out of readFileSync — an uncaught CLI failure+// instead of the ok:false that sends the page to its one inline rewrite. A link there is not a page+// written in place (the dispatch gate refuses one before any worker runs).+test('a folder, a link or an unreadable file at the page path is a failed validation, never a throw', (t) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-worker-output-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const folder = path.join(dir, 'folder.tsx');+ fs.mkdirSync(folder);+ assert.deepEqual(validatePageOutput({ filePath: folder }).problems, ['is not a regular file']);+ const real = path.join(dir, 'real.tsx');+ fs.writeFileSync(real, 'export default function GeneratedComponent() {\n return <div>ok</div>;\n}\n');+ const linked = path.join(dir, 'linked.tsx');+ let linkedOk = true;+ try { fs.symlinkSync(real, linked, 'file'); } catch { linkedOk = false; }+ if (linkedOk) {+ const r = validatePageOutput({ filePath: linked });+ assert.equal(r.ok, false, 'a complete page behind a link is still not the page written in place');+ assert.deepEqual(r.problems, ['is a symbolic link or junction, not a page file written in place']);+ }+ t.mock.method(fs, 'readFileSync', () => { const e = new Error('permission denied'); e.code = 'EACCES'; throw e; });+ assert.deepEqual(validatePageOutput({ filePath: real }).problems, ['file could not be read (EACCES)']);+ t.mock.method(fs, 'lstatSync', () => { const e = new Error('operation not permitted'); e.code = 'EPERM'; throw e; });+ assert.deepEqual(validatePageOutput({ filePath: real }).problems, ['file could not be inspected (EPERM)']);+});++// A worker that returns without writing leaves an earlier attempt's page in place, and that page passes+// every content check. Each target is stamped right before it is dispatched, and a page exactly as it was+// stamped is refused, so the inline fallback runs instead of the stale page being deployed.+const COMPLETE = 'export default function GeneratedComponent() {\n return <div>ok</div>;\n}\n';+test('a page unchanged since its dispatch stamp is refused, and any write is accepted', (t) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-worker-output-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const page = path.join(dir, 'overview.tsx');+ const sidecar = path.join(dir, '.overview.tsx.dispatch-stamp.json');+ fs.writeFileSync(page, COMPLETE);+ assert.deepEqual(stampPageTarget({ filePath: page }), { ok: true, action: 'stamp', filePath: page, existed: true });+ assert.ok(fs.existsSync(sidecar));+ assert.deepEqual(validatePageOutput({ filePath: page }).problems, ['file is unchanged since the page was dispatched — the worker did not write it']);+ // The stamp is KEPT while the page is unchanged: the retry the skill prescribes, or the same check run+ // again, is refused the same way. Consuming it on the failure let the next check pass the stale page.+ assert.ok(fs.existsSync(sidecar), 'an unchanged page keeps its stamp');+ assert.deepEqual(validatePageOutput({ filePath: page }).problems, ['file is unchanged since the page was dispatched — the worker did not write it']);+ // The same bytes written again still count: a write moves the modification time. And a page found+ // changed consumes its stamp.+ stampPageTarget({ filePath: page });+ const later = new Date(fs.statSync(page).mtimeMs + 5000);+ fs.writeFileSync(page, COMPLETE);+ fs.utimesSync(page, later, later);+ assert.equal(validatePageOutput({ filePath: page }).ok, true);+ assert.ok(!fs.existsSync(sidecar), 'a page found changed consumes its stamp');+ // …and so does new content with the old modification time.+ stampPageTarget({ filePath: page });+ const same = fs.statSync(page);+ fs.writeFileSync(page, COMPLETE.replace('ok', 'OK'));+ fs.utimesSync(page, same.atime, same.mtime);+ assert.equal(validatePageOutput({ filePath: page }).ok, true);+ // A target that did not exist at dispatch: never written stays "never written" (its stamp kept), and+ // written is accepted.+ const fresh = path.join(dir, 'details.tsx');+ const freshStamp = path.join(dir, '.details.tsx.dispatch-stamp.json');+ assert.equal(stampPageTarget({ filePath: fresh }).existed, false);+ assert.deepEqual(validatePageOutput({ filePath: fresh }).problems, ['file was never written']);+ assert.ok(fs.existsSync(freshStamp));+ fs.writeFileSync(fresh, COMPLETE);+ assert.equal(validatePageOutput({ filePath: fresh }).ok, true);+ assert.ok(!fs.existsSync(freshStamp));+ // Without a stamp, only the content is judged.+ assert.equal(validatePageOutput({ filePath: page }).ok, true);+ // A page whose folder does not exist yet cannot be stale: nothing to stamp, and no folder is created.+ const nested = path.join(dir, 'pages', 'new.tsx');+ assert.deepEqual(stampPageTarget({ filePath: nested }), { ok: true, action: 'stamp', filePath: nested, existed: false });+ assert.equal(fs.existsSync(path.join(dir, 'pages')), false);+ assert.deepEqual(validatePageOutput({ filePath: nested }).problems, ['file was never written']);+});++// A stamp that cannot be trusted fails closed: the check can no longer tell this run's write from what was+// there. The sidecar is written in place, so a link or a hard link at its path is refused, not written through.+test('a dispatch stamp that cannot be trusted fails closed, and a linked stamp path is refused', (t) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-worker-output-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const page = path.join(dir, 'overview.tsx');+ const sidecar = path.join(dir, '.overview.tsx.dispatch-stamp.json');+ fs.writeFileSync(page, COMPLETE);+ // A stamp is trusted only whole and only for this page: a truncated one compared nothing and let an unchanged+ // page through, and one copied from another page compared that page's state.+ const other = { filePath: path.join(dir, 'other.tsx'), existed: true, size: 1, mtimeMs: 1, sha256: 'a'.repeat(64) };+ for (const [what, content, why] of [+ ['unparseable', '{ not json', /could not be read/],+ ['not a stamp', '{"filePath":"x"}', /is not a dispatch stamp/],+ ['truncated', JSON.stringify({ filePath: page, existed: true }), /is not a dispatch stamp/],+ ['a bad digest', JSON.stringify({ filePath: page, existed: true, size: 1, mtimeMs: 1, sha256: 'nope' }), /is not a dispatch stamp/],+ ['another page\u2019s', JSON.stringify(other), /belongs to another page/],+ ]) {+ fs.writeFileSync(sidecar, content);+ const r = validatePageOutput({ filePath: page });+ assert.equal(r.ok, false, what);+ assert.match(r.problems[0], /^the dispatch stamp /, what);+ assert.match(r.problems[0], why, what);+ assert.ok(fs.existsSync(sidecar), `${what}: kept, so the check keeps failing until the page is stamped again`);+ }+ fs.rmSync(sidecar);+ const elsewhere = path.join(dir, 'elsewhere.json');+ fs.writeFileSync(elsewhere, '{}');+ fs.linkSync(elsewhere, sidecar);+ const refused = stampPageTarget({ filePath: page });+ assert.equal(refused.ok, false);+ assert.match(refused.problems[0], /is not a plain file/);+ assert.equal(fs.readFileSync(elsewhere, 'utf8'), '{}', 'nothing is written through the hard link');+ assert.match(validatePageOutput({ filePath: page }).problems[0], /^the dispatch stamp is not a plain file; remove it and re-run$/);+ assert.equal(fs.readFileSync(elsewhere, 'utf8'), '{}', 'and the check leaves the other name alone');+ fs.rmSync(sidecar);+ const { spawnSync } = require('node:child_process');+ const cli = spawnSync(process.execPath, [path.join(__dirname, '..', 'genpage-worker-output.js'), '--stamp', '--file', page], { encoding: 'utf8' });+ assert.equal(cli.status, 0, cli.stdout);+ assert.deepEqual(JSON.parse(cli.stdout), { ok: true, action: 'stamp', filePath: page, existed: true });+});++// Elision is judged where it can mean elision — a comment, or a bare line standing in for code. The+// same words as UI copy are fine, and rejecting them would throw away a good page and regenerate it.+test('elided code is rejected, but the same words as UI copy are not', () => {+ const page = (body) => `export default function GeneratedComponent() {\n${body}\n return <div>ok</div>;\n}\n`;+ for (const [what, body] of [+ ['a TODO comment', ' // TODO: wire the save handler'],+ ['a TODO opening a comment', ' // TODO wire paging'],+ ['a FIXME block comment', ' /* FIXME: real query */'],+ ['a lowercase todo: marker', ' // Todo: add paging'],+ ['a TODO: inside a comment', ' // load rows first — TODO: paging'],+ ['a lowercase fixme', ' // fixme before release'],+ ['a TODO opening a JSDoc block', ' /**\n * TODO implement save\n */'],+ ['a TODO comment inside a template expression', ' const s = `${/* TODO: format it */ total}`;'],+ ['an elision comment', ' // ... rest of the component'],+ ['an elision block comment', ' /* ... */'],+ ['an omitted-for-brevity comment', ' // Implementation omitted for brevity'],+ ['a bare ellipsis line', ' ...'],+ ['a bare ellipsis line before a statement in a block', ' ...\n renderRows();'],+ ['a bare ellipsis line inside executable template code', ' const title = `${(() => {\n ...\n })()}`;'],+ // Documented limit: without a full parser, a bare `...` line can be legal multiline spread or+ // elision. The gate fails closed; generators should write `...rows` on one line instead.+ ['a parser-valid multiline spread written with a bare ellipsis line', ' const rows = [1, 2];\n const copy = [\n ...\n rows\n ];'],+ ]) {+ const result = validatePageOutput({ filePath: write(page(body)) });+ assert.equal(result.ok, false, what);+ assert.match(result.problems.join('\n'), /TODO\/FIXME|elides code|bare `\.\.\.` line/, what);+ }+ for (const [what, body] of [+ ['an ellipsis in a label', ' const label = "Loading…";'],+ ['a TODO status value', " const STATUSES = ['TODO', 'DOING', 'DONE'];"],+ ['todo as prose in a comment', ' // Render the todo list, newest first'],+ ['todo as prose in a JSDoc block', ' /**\n * Renders the todo list.\n * @returns the page\n */'],+ ['layout prose about the rest of the page', ' // Sticky header; the rest of the page scrolls'],+ ['a file-handling comment', ' // Upload the rest of the file in 4 MB chunks'],+ ['board order naming TODO', ' // Status columns in board order: TODO -> IN_PROGRESS -> DONE'],+ ['a todo: in prose', ' // each todo: title, due date and owner'],+ ['an ellipsis in JSX text', ' const el = <Spinner label="Search documents…">Loading... please wait</Spinner>;'],+ ['a URL string', ' const docs = "https://contoso.example/...";'],+ ['a spread', ' const merged = { ...base, extra: 1 };'],+ ['a fence inside strings', ' const md = "```tsx";\n const help = `\n\\`\\`\\`\ncode\n\\`\\`\\`\n`;'],+ ['a fence inside a block comment', ' /* usage:\n```\n<Page />\n```\n */'],+ // Lexer shapes that once made a complete page read as truncated: a `}` in a nested template's+ // text ended the outer template early, a `//` comment right before JSX hid the element, and a+ // comment inside `${…}` made the division after it read as a regex.+ ['a nested template with braces in its text', ' const toJson = (rows) => `[${rows.map((r) => `{"id":"${r.id}"}`).join(",")}]`;'],+ ['a comment right before the root JSX', ' const el = (\n // Instructions\n <Text>1) Pick a record</Text>\n );'],+ ['a comment right before a regex', ' const endsWithBrace = (v) =>\n // drop a trailing brace\n /\\}$/.test(v);'],+ ['a comment before a division inside a template expression', ' const label = `${total // per row, then:\n / count} items`;'],+ // A template's `${…}` is code, JSX included; and a property named like a keyword, a non-null+ // assertion or a postfix increment is an operand, so the `/` after it divides.+ ['JSX inside a template expression', " const x = `${<p>it's {n}</p>}`;"],+ ['a keyword-named property divided', ' const pct = <Text>{counts.new / total}</Text>;'],+ ['a non-null assertion divided', ' const pct = <Text>{closed! / total}</Text>;'],+ ['a postfix increment divided', ' const half = <Text>{i++ / 2}</Text>;'],+ ['a prefix ! before a regex', ' const noParen = (s) => !/\\(/.test(s);'],+ ]) {+ const result = validatePageOutput({ filePath: write(page(body)) });+ assert.equal(result.ok, true, `${what}: ${result.problems.join('; ')}`);+ }+});++// Corpus: every committed sample and captured page is a complete page, so the gate must accept each+// one — six of them carry "Loading…"-style copy, and an earlier draft of this gate refused all six.+test('every committed sample and fixture page passes the worker-output gate', (t) => {+ const repoRoot = path.join(__dirname, '..', '..', '..', '..');+ const { spawnSync } = require('node:child_process');+ const ls = spawnSync('git', ['ls-files', '--', 'plugins/model-apps/samples/*.tsx', 'evals/model-apps/genpage/fixtures/*.tsx', 'evals/model-apps/genpage/fixtures/**/*.tsx'],+ { cwd: repoRoot, encoding: 'utf8' });+ if (ls.status !== 0) return t.skip('not a git checkout');+ const files = [...new Set(ls.stdout.split('\n').map((f) => f.trim()).filter(Boolean))];+ assert.ok(files.length >= 20, `the corpus is populated (${files.length})`);+ for (const rel of files) {+ const result = validatePageOutput({ filePath: path.join(repoRoot, rel) });+ assert.equal(result.ok, true, `${rel}: ${result.problems.join('; ')}`);+ }+ return undefined;+});diff --git a/plugins/model-apps/scripts/tests/list-connections.test.js b/plugins/model-apps/scripts/tests/list-connections.test.jsindex 993bae11e..0e81116ca 100644--- a/plugins/model-apps/scripts/tests/list-connections.test.js+++ b/plugins/model-apps/scripts/tests/list-connections.test.js@@ -169,6 +169,28 @@ test('parses current PAC Id/Name/API Id/Status output without a separator row',]);});+// A row that does not match the Id/Name/API Id shape is kept as a row with no ids: when every row fails to+// match (a changed column layout, say) the listing fails closed instead of reading as "no connections", and+// beside a usable row it is dropped — never offered as a connection.+test('an Id/Name/API Id listing with no row carrying both ids fails closed', () => {+ const header = 'Id Name API Id Status';+ // Connection rows read wrong: each carries a connector's API path but not the columns around it.+ assert.throws(() => parsePacConnectionList([header, '/providers/Microsoft.PowerApps/apis/shared_sharepointonline', 'Contoso /providers/Microsoft.PowerApps/apis/shared_office365'].join('\n')),+ /Id\/Name\/API Id table contained 2 row\(s\), but no usable connection rows/);+ // A line with no API path is no connection: a message under the header is still an empty listing.+ assert.deepEqual(parsePacConnectionList([header, 'No connections found.'].join('\n')), []);+ // A Status of several words, or none, still parses.+ const status = (s) => `00000000000000000000000000000001 Contoso Dataverse /providers/Microsoft.PowerApps/apis/shared_commondataservice${s}`;+ for (const s of [' Not connected', '']) {+ assert.deepEqual(parsePacConnectionList([header, status(s)].join('\n')).map((r) => r.connectionId), ['00000000000000000000000000000001'], JSON.stringify(s));+ }+ const mixed = [header,+ '00000000000000000000000000000001 Contoso Dataverse /providers/Microsoft.PowerApps/apis/shared_commondataservice Connected',+ '(wrapped name tail)'].join('\n');+ assert.deepEqual(parsePacConnectionList(mixed).map((r) => r.connectionId), ['00000000000000000000000000000001']);+ assert.deepEqual(parsePacConnectionList(header), [], 'a header with no rows is still an empty listing');+});+test('header matching is case- and punctuation-insensitive', () => {// normalizeHeader strips non-alphanumerics and lower-cases, so "Connection Id", "connectionId"// and "CONNECTION-ID" are the same column. Without that, a cosmetic CLI header change silently@@ -202,3 +224,32 @@ test('rows with no identifying field at all are dropped', () => {const raw = JSON.stringify([{ 'Connection Name': '', 'Connection Id': '' }, { 'Connection Name': 'Real', 'Connection Id': SP_CONN }]);assert.deepEqual(parsePacConnectionList(raw).map((r) => r.displayName), ['Real']);});++test('display-name-only JSON rows fail instead of becoming selectable connections', () => {+ assert.throws(+ () => parsePacConnectionList(JSON.stringify([{ Name: 'Looks Real But Has No IDs' }])),+ /no usable connection rows/i,+ );+});++// Beside real rows, an unidentified one is dropped rather than offered. Older PAC builds wrap a long+// friendly name onto a second table line, and that continuation line parses as a name with no ids —+// it used to be listed as a connection of its own that a maker could pick and never bind.+test('a row without both ids is dropped beside usable rows, never offered as a phantom connection', () => {+ const rows = parsePacConnectionList(JSON.stringify([+ { Name: 'Contoso SharePoint (wrapped name continues here)' },+ { Name: 'Contoso SharePoint', Id: SP_CONN },+ ]));+ assert.deepEqual(rows, [{ connectorId: SP_API, connectionId: SP_CONN, displayName: 'Contoso SharePoint' }]);+ // Connection Name Connector Id Connection Id+ // --------------------- ---------------------------------------------------------- ------------------------------+ // Contoso SharePoint /providers/Microsoft.PowerApps/apis/shared_sharepointonline <SP_CONN>+ // (wrapped name tail)+ const table = [+ 'Connection Name Connector Id Connection Id',+ '--------------------- ---------------------------------------------------------- ------------------------------',+ `Contoso SharePoint ${SP_API.padEnd(58)} ${SP_CONN}`,+ '(wrapped name tail)',+ ].join('\n');+ assert.deepEqual(parsePacConnectionList(table).map((r) => r.connectionId), [SP_CONN]);+});diff --git a/plugins/model-apps/scripts/tests/localization-reference.test.js b/plugins/model-apps/scripts/tests/localization-reference.test.jsnew file mode 100644index 000000000..23c014827--- /dev/null+++ b/plugins/model-apps/scripts/tests/localization-reference.test.js@@ -0,0 +1,47 @@+'use strict';+// #585 item 6: the localization reference must never decide text direction from a hand-kept LCID list.+// It named five Arabic LCIDs and Hebrew, so every other right-to-left culture — the remaining Arabic+// regions, Persian, Urdu, Pashto and more — rendered left-to-right. Direction now comes from PAC's RTL+// column, with a script-based fallback; these tests pin that fallback's data against culture metadata.+const test = require('node:test');+const assert = require('node:assert');+const fs = require('node:fs');+const path = require('node:path');++const DOC = fs.readFileSync(path.join(__dirname, '..', '..', 'references', 'localization.md'), 'utf8');++// Every SPECIFIC right-to-left culture in Windows culture metadata (CultureInfo.GetCultures filtered on+// TextInfo.IsRightToLeft). Neutral cultures are left out on purpose: Windows' neutral `ku` is Central+// Kurdish (Arabic script) while CLDR's `ku` is Kurmanji (Latin script), and PAC reports specific codes.+const RTL_CULTURES = [+ 'ar-SA', 'ar-IQ', 'ar-EG', 'ar-LY', 'ar-DZ', 'ar-MA', 'ar-TN', 'ar-OM', 'ar-YE', 'ar-SY', 'ar-JO',+ 'ar-LB', 'ar-KW', 'ar-AE', 'ar-BH', 'ar-QA', 'he-IL', 'yi-001', 'fa-IR', 'fa-AF', 'ur-PK', 'ur-IN',+ 'ps-AF', 'sd-Arab-PK', 'sd-Arab', 'ug-CN', 'dv-MV', 'syr-SY', 'ku-Arab-IQ', 'ku-Arab', 'ks-Arab',+ 'pa-Arab-PK', 'pa-Arab', 'tzm-Arab-MA',+];+const LTR_CULTURES = [+ 'en-US', 'fr-FR', 'de-DE', 'es-ES', 'ru-RU', 'el-GR', 'tr-TR', 'ku-TR', 'az-Latn-AZ', 'hi-IN',+ 'pa-IN', 'th-TH', 'zh-CN', 'zh-TW', 'ja-JP', 'ko-KR', 'vi-VN', 'id-ID', 'ms-MY', 'kk-KZ',+];++// The fallback's script set, read from the reference itself, so the test checks what page authors are told.+function docRtlScripts() {+ const m = DOC.match(/const RTL_SCRIPTS = new Set\(\[([^\]]*)\]\)/);+ assert.ok(m, 'the reference defines RTL_SCRIPTS');+ return new Set([...m[1].matchAll(/"([A-Z][a-z]{3})"/g)].map((x) => x[1]));+}++test('the localization reference takes text direction from PAC, not from a hand-kept LCID list', () => {+ const section = DOC.slice(DOC.indexOf('### RTL Layout Support'), DOC.indexOf('### User Settings for Formatting'));+ assert.ok(section.length > 0, 'the RTL section exists');+ assert.match(section, /\*\*RTL\*\* column of `pac model list-languages`/);+ assert.doesNotMatch(section, /\b(1025|1037|2049|3073|4097|5121)\b/, 'no LCIDs are given as the rule');+});++test('the script fallback in the reference classifies every right-to-left culture as RTL and the controls as LTR', () => {+ const scripts = docRtlScripts();+ // The same expression the reference gives page authors: the likely script from CLDR.+ const isRtl = (code) => scripts.has(new Intl.Locale(code).maximize().script || '');+ for (const code of RTL_CULTURES) assert.strictEqual(isRtl(code), true, `${code} is right-to-left`);+ for (const code of LTR_CULTURES) assert.strictEqual(isRtl(code), false, `${code} is left-to-right`);+});diff --git a/plugins/model-apps/scripts/tests/page-file-targets.test.js b/plugins/model-apps/scripts/tests/page-file-targets.test.jsnew file mode 100644index 000000000..2fa13501b--- /dev/null+++ b/plugins/model-apps/scripts/tests/page-file-targets.test.js@@ -0,0 +1,482 @@+'use strict';+// #588 item 4: page filenames come from a plan an AI planner wrote, and parallel workers write to them+// unattended. One rule (lib/page-file-targets.js) decides which names are safe, and /genpage runs it+// through check-page-files.js before it dispatches any worker.+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { spawnSync } = require('node:child_process');++const { pageFileProblems, pageFilesFromPlan, pagesTables } = require('../lib/page-file-targets.js');+const { checkPageFiles } = require('../check-page-files.js');++const SCRIPT = path.join(__dirname, '..', 'check-page-files.js');+const codes = (files, opts) => pageFileProblems(files, opts).map((p) => `${p.code}:${p.file}`);++test('unsafe page file names are refused, one problem code per shape', () => {+ assert.deepEqual(codes(['C:\\pages\\a.tsx', '/tmp/b.tsx', 'C:g.tsx', 'pages\\c.tsx', '../d.tsx', 'x/../f.tsx', '']), [+ 'absolute:C:\\pages\\a.tsx', 'absolute:/tmp/b.tsx', 'absolute:C:g.tsx', 'backslash:pages\\c.tsx',+ 'traversal:../d.tsx', 'traversal:x/../f.tsx', 'empty:',+ ]);+ // A lone "." cannot climb out: it is a harmless spelling, not a reason to force a re-plan. It still+ // collides with the plain name it normalizes to.+ assert.deepEqual(codes(['./e.tsx']), []);+ assert.deepEqual(codes(['e.tsx', './e.tsx']), ['collision:./e.tsx']);+});++test('two names one case-insensitive filesystem stores as the same file collide, including Unicode spellings', () => {+ assert.deepEqual(codes(['Page.tsx', 'page.tsx']), ['collision:page.tsx']);+ // "é" precomposed (U+00E9) and decomposed (e + U+0301) are one name on disk too.+ assert.deepEqual(codes(['caf\u00e9.tsx', 'cafe\u0301.tsx']), ['collision:cafe\u0301.tsx']);+ // CONTROL: distinct names, nested folders and a leading-dot-free name all pass.+ assert.deepEqual(codes(['overview.tsx', 'details/edit.tsx', 'details/view.tsx']), []);+});++test('a parent that resolves through a link or junction to outside the working directory is refused', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'page-files-root-'));+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'page-files-outside-'));+ t.after(() => {+ fs.rmSync(path.join(root, 'linked'), { recursive: true, force: true });+ fs.rmSync(root, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ });+ try {+ fs.symlinkSync(outside, path.join(root, 'linked'), 'junction');+ } catch (e) {+ t.skip(`cannot create a directory link here: ${e.message}`);+ return;+ }+ assert.deepEqual(codes(['linked/page.tsx', 'fine.tsx', 'nested/new.tsx'], { workingDir: root }), ['realpath-escape:linked/page.tsx']);+ // Without a working directory there is nothing to resolve against: the lexical rules still apply.+ assert.deepEqual(codes(['linked/page.tsx']), []);+});++// Every Pages File is a page `.tsx` (references/plan-schema.md). Any other name is some other file of the+// working directory — the manifest, the generated types, the plan itself — which a worker would then+// overwrite with a page.+test('a name that is not a .tsx page file is refused', () => {+ assert.deepEqual(codes(['package.json', 'genpage.d.ts', 'RuntimeTypes.ts', 'genpage-plan.md', '.tsx', 'pages/.tsx', 'page.tsx.bak']), [+ 'extension:package.json', 'extension:genpage.d.ts', 'extension:RuntimeTypes.ts', 'extension:genpage-plan.md',+ 'extension:.tsx', 'extension:pages/.tsx', 'extension:page.tsx.bak',+ ]);+ // CONTROLS: any case of the extension, dotted stems and nested folders are pages.+ assert.deepEqual(codes(['Upper.TSX', 'a.b.tsx', 'pages/home.tsx']), []);+});++// existsSync follows a link and calls a DANGLING one absent, so the walk stepped past a planted link to+// the in-directory folder above it, and the worker then wrote through the link. A link AT the target is+// refused wherever it points — `page.tsx → package.json` inside the directory would put a page into the+// manifest — and a parent link that cannot be resolved is refused rather than waved through.+test('a link at the page path, or a parent link that cannot be resolved, is refused', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'page-files-root-'));+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'page-files-outside-'));+ t.after(() => {+ // Unlink every link FIRST — `up` points at the temp folder itself — so the recursive removal below+ // only ever sees this test's own entries.+ for (const name of ['up', 'alias', 'dead', 'ghost.tsx', 'page.tsx', 'hard.tsx', 'inside.tsx']) {+ try { fs.unlinkSync(path.join(root, name)); } catch { fs.rmSync(path.join(root, name), { force: true, recursive: true }); }+ }+ fs.rmSync(root, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ });+ try {+ fs.symlinkSync(path.join(outside, 'gone'), path.join(root, 'dead'), 'junction');+ } catch (e) {+ t.skip(`cannot create a directory link here: ${e.message}`);+ return;+ }+ assert.deepEqual(codes(['dead/page.tsx', 'fine.tsx'], { workingDir: root }), ['unresolvable:dead/page.tsx']);+ // A link to the working directory's own PARENT is outside it too (the relative path is exactly "..").+ fs.symlinkSync(path.dirname(root), path.join(root, 'up'), 'junction');+ assert.deepEqual(codes(['up/page.tsx'], { workingDir: root }), ['realpath-escape:up/page.tsx']);+ let fileLinks = true;+ try {+ fs.symlinkSync(path.join(outside, 'target.tsx'), path.join(root, 'ghost.tsx'), 'file');+ fs.writeFileSync(path.join(root, 'package.json'), '{}');+ fs.symlinkSync(path.join(root, 'package.json'), path.join(root, 'page.tsx'), 'file');+ } catch { fileLinks = false; }+ if (fileLinks) {+ assert.deepEqual(codes(['ghost.tsx', 'page.tsx', 'fine.tsx'], { workingDir: root }), ['link:ghost.tsx', 'link:page.tsx']);+ assert.deepEqual(fs.readdirSync(outside), [], 'nothing was created through the dangling link');+ }+ // A HARD link has no link bit — lstat calls it a plain file and realpath leaves it where it is — yet a+ // worker writing it rewrites the other name too, outside the directory included. No privilege needed+ // on Windows, so it is the easier route.+ fs.writeFileSync(path.join(outside, 'precious.txt'), 'keep me');+ fs.linkSync(path.join(outside, 'precious.txt'), path.join(root, 'hard.tsx'));+ const hard = pageFileProblems(['hard.tsx'], { workingDir: root });+ assert.deepEqual(hard.map((p) => `${p.code}:${p.file}`), ['link:hard.tsx']);+ assert.match(hard[0].message, /hard link \(2 names for one file\)/);+ // Two names that reach ONE file through a link inside the directory are two workers on one file.+ fs.mkdirSync(path.join(root, 'sub'));+ fs.symlinkSync(path.join(root, 'sub'), path.join(root, 'alias'), 'junction');+ const alias = pageFileProblems(['alias/a.tsx', 'sub/a.tsx', 'sub/b.tsx'], { workingDir: root });+ assert.deepEqual(alias.map((p) => `${p.code}:${p.file}`), ['collision:sub/a.tsx']);+ assert.match(alias[0].message, /"alias\/a\.tsx" and "sub\/a\.tsx" are the same file, reached through a link or junction/);+ // Two spellings of one name still read as a case collision with a working directory, not as a link.+ const cased = pageFileProblems(['Other.tsx', 'other.tsx'], { workingDir: root });+ assert.deepEqual(cased.map((p) => `${p.code}:${p.file}`), ['collision:other.tsx']);+ assert.match(cased[0].message, /"Other\.tsx" and "other\.tsx" collide on a case-insensitive filesystem/);+});++// /app-builder's implemented pages are in the plan for the navigation graph only — no worker writes+// them — so they are held to the lexical rules and to collisions, never to the write-target rules.+test('built pages keep the lexical rules and collisions, but not the write-target rules', () => {+ assert.deepEqual(codes(['next.tsx'], { built: ['pages/home.jsx', 'report.ts'] }), [], 'no extension rule for a built page');+ assert.deepEqual(codes(['next.tsx'], { built: ['x/../y.tsx', 'C:\\a.tsx'] }), ['traversal:x/../y.tsx', 'absolute:C:\\a.tsx']);+ assert.deepEqual(codes(['home.tsx'], { built: ['Home.tsx'] }), ['collision:home.tsx'], 'a new page is never written over a built one');+ assert.deepEqual(codes([], { built: ['Home.tsx', 'home.tsx'] }), ['collision:home.tsx'], 'two built pages still collide');+});++// Windows cannot store these, whatever the planner's platform — and `page:alt.tsx` is worse than refused:+// it writes an NTFS alternate stream `alt.tsx` on a file `page`, so the page lands where no one looks.+// (A single letter before the colon, `a:b.tsx`, is already refused as a drive-relative path.)+test('a name Windows cannot store is refused on every platform', () => {+ const bad = ['CON.tsx', 'nul.tsx', 'con.page.tsx', 'COM1.tsx', 'lpt9.x.tsx', 'page:alt.tsx', 'q?.tsx', 'pipe|x.tsx', 'x./a.tsx', 'x /a.tsx', 'REPORT~1.TSX', 'pages~2/a.tsx'];+ assert.deepEqual(codes(bad), bad.map((f) => `unportable:${f}`));+ assert.match(pageFileProblems(['page:alt.tsx'])[0].message, /a character Windows reserves in "page:alt\.tsx", which Windows cannot store as a file name$/);+ // Windows stores a short-name form fine; the problem is that it can BE another file.+ assert.match(pageFileProblems(['REPORT~1.TSX'])[0].message, /a Windows short-name form \(`~1`\) in "REPORT~1\.TSX", which on Windows can be the short name of another file$/);+ // CONTROLS: names that only resemble a device, dotted stems, and a lone "." segment. An inner space and a tilde+ // without a digit are storable, and are refused by the shell rule instead (the next test).+ assert.deepEqual(codes(['console.tsx', 'con-page.tsx', 'a.b.tsx', './e.tsx', 'com10.tsx']), []);+ assert.deepEqual(codes(['my page.tsx', 'tilde~page.tsx']), ['shell:my page.tsx', 'shell:tilde~page.tsx']);+ // Built pages are not written, so the write-target rules — this one included — do not apply to them.+ assert.deepEqual(codes(['next.tsx'], { built: ['CON.tsx'] }), []);+});++test('a page path that exists but is not a regular file is refused before any worker runs', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'page-files-notfile-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.mkdirSync(path.join(root, 'folder.tsx'));+ assert.deepEqual(codes(['folder.tsx', 'fine.tsx'], { workingDir: root }), ['not-a-file:folder.tsx']);+});++// "Could not look" is not "nothing there". Every lstat and readdir error except ENOENT/ENOTDIR — and a+// working directory that exists but cannot be resolved — used to read as absence and wave the file through.+test('a disk error other than "not there" refuses the file instead of reading as absence', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'page-files-eacces-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.mkdirSync(path.join(root, 'locked'));+ const denied = (e) => Object.assign(new Error(`${e}: permission denied`), { code: e });+ const realLstat = fs.lstatSync;+ const lstat = t.mock.method(fs, 'lstatSync', (p, ...rest) => {+ if (String(p).includes(`${path.sep}locked${path.sep}`)) throw denied('EACCES');+ return realLstat(p, ...rest);+ });+ assert.deepEqual(codes(['locked/page.tsx', 'fine.tsx'], { workingDir: root }), ['unresolvable:locked/page.tsx']);+ lstat.mock.restore();+ const realReaddir = fs.readdirSync;+ const readdir = t.mock.method(fs, 'readdirSync', (p, ...rest) => {+ if (String(p).endsWith(`${path.sep}locked`)) throw denied('EPERM');+ return realReaddir(p, ...rest);+ });+ const listed = pageFileProblems(['locked/page.tsx'], { workingDir: root });+ assert.deepEqual(listed.map((p) => p.code), ['unresolvable']);+ assert.match(listed[0].message, /cannot be checked on disk \(EPERM\)/);+ readdir.mock.restore();+ t.mock.method(fs.realpathSync, 'native', (p) => { throw denied('EIO'); });+ const rootless = pageFileProblems(['a.tsx', 'b.tsx'], { workingDir: root });+ assert.deepEqual(rootless.map((p) => p.code), ['unresolvable', 'unresolvable']);+ assert.match(rootless[0].message, /the working directory cannot be resolved \(EIO\)/);+ // …and so does a working directory that cannot even be INSPECTED: its lstat is read before its realpath now.+ t.mock.restoreAll();+ t.mock.method(fs, 'lstatSync', (p, ...rest) => {+ if (path.resolve(String(p)) === path.resolve(root)) throw denied('EACCES');+ return realLstat(p, ...rest);+ });+ const uninspectable = pageFileProblems(['a.tsx'], { workingDir: root });+ assert.deepEqual(uninspectable.map((p) => p.code), ['unresolvable']);+ assert.match(uninspectable[0].message, /the working directory cannot be resolved \(EACCES\)/);+});++// A name one case-insensitive filesystem stores as a page ALREADY in its folder is that page: the worker+// would overwrite it. The plan's own names were compared with each other only.+test('a name that differs only in case from a page already in its folder collides with it', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'page-files-existing-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.writeFileSync(path.join(root, 'Page.tsx'), 'export default () => null;\n');+ fs.mkdirSync(path.join(root, 'pages'));+ fs.writeFileSync(path.join(root, 'pages', 'Home.tsx'), 'export default () => null;\n');+ const problems = pageFileProblems(['page.tsx', 'pages/home.tsx', 'Page.tsx', 'pages/Home.tsx', 'new/page.tsx', 'PAGES/extra.tsx'], { workingDir: root });+ assert.deepEqual(problems.map((p) => `${p.code}:${p.file}`), ['collision:page.tsx', 'collision:pages/home.tsx', 'collision:PAGES/extra.tsx']);+ assert.match(problems[0].message, /the existing "Page\.tsx"/);+ assert.match(problems[1].message, /the existing "pages\/Home\.tsx"/);+ // A FOLDER under another spelling is the same folder on a case-insensitive filesystem, and a second+ // tree beside it on a case-sensitive one — so the plan's path is refused at the folder already.+ assert.match(problems[2].message, /the existing "pages"/);+ // The identical spelling is that very page, rewritten — and with no working directory nothing is listed.+ assert.deepEqual(codes(['Page.tsx'], { workingDir: root }), []);+ assert.deepEqual(codes(['page.tsx']), []);+});++test('the File column is read from the plan\'s Pages table, and a plan without one is not "no pages"', () => {+ const plan = [+ '## Pages',+ '| Page | File | Purpose | Entities |',+ '|------|------|---------|----------|',+ '| Overview | overview.tsx | Totals \\| trends | account |',+ '| Details | details.tsx | One record | account |',+ '',+ '## Entity Creation Required',+ '| Not | A | Pages | Table |',+ ].join('\r\n');+ assert.deepEqual(pageFilesFromPlan(plan), ['overview.tsx', 'details.tsx']);+ assert.equal(pageFilesFromPlan('## Environment\n- URL: x\n'), null);+ assert.equal(pageFilesFromPlan('## Pages\n| Page | Purpose |\n|---|---|\n| A | b |\n'), null, 'no File column');+});++// The plan's `## User Requirements` is the maker's text, verbatim, ahead of `## Pages`: a Pages table quoted+// there decided the files the gate checked, while the workers wrote the real table's. A second Pages table with+// a File column is refused — a fenced one too, since a fence left open would swallow the real section — while+// a maker's own `## Pages` list, which names no file, is no second table.+test('a plan with more than one Pages table is refused, not read by its first', () => {+ const real = ['## Pages', '| Page | File | Purpose | Entities |', '|---|---|---|---|', '| A | approved.tsx | x | account |'];+ const quoted = ['## Pages', '| Page | File | Purpose | Entities |', '|---|---|---|---|', '| X | outside.tsx | y | account |'];+ const plan = (...requirements) => ['# Genpage Plan', '## User Requirements', 'Build one page.', ...requirements,+ '## Working Directory', 'D:/work', ...real, '## Entity Creation Required', 'No entity creation required.'].join('\n');+ for (const [what, block] of [+ ['fenced', ['```markdown', ...quoted, '```']],+ ['fenced, with the fence left open', ['```', ...quoted]],+ ['not fenced', quoted],+ ['quoted from an approval preview', ['### Pages (1 total)', ...quoted.slice(1)]],+ ['quoted with ">"', quoted.map((l) => `> ${l}`)],+ ['quoted, over an unquoted table', ['> ## Pages', ...quoted.slice(1)]],+ ['indented', quoted.map((l) => ` ${l}`)],+ ]) {+ assert.deepEqual(pagesTables(plan(...block)).tables, [['outside.tsx'], ['approved.tsx']], what);+ assert.equal(pageFilesFromPlan(plan(...block)), null, what);+ }+ // CONTROLS: a maker's own `## Pages` list, prose, or a table without a File column names no file, so the real+ // table is read; and a plan with one Pages table is read.+ for (const [what, block] of [+ ['a list of pages', ['## Pages', '- Overview: summary cards', '- Details: one record']],+ ['prose', ['## Pages', 'The pages are listed below.']],+ ['a table without a File column', ['## Pages', '| Page | Purpose |', '|---|---|', '| Overview | cards |']],+ ['a page named "Pages Admin" specified', ['### Pages Admin', '- **File:** admin.tsx', '- **Purpose:** settings']],+ ]) {+ assert.deepEqual(pagesTables(plan(...block)).tables, [['approved.tsx']], what);+ assert.deepEqual(pageFilesFromPlan(plan(...block)), ['approved.tsx'], what);+ }+ assert.deepEqual(pageFilesFromPlan(plan()), ['approved.tsx']);+ // The gate says why, and checks no file of either table.+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'page-files-two-'));+ try {+ const p = path.join(dir, 'genpage-plan.md');+ fs.writeFileSync(p, plan('```', ...quoted, '```'));+ const res = checkPageFiles({ planPath: p });+ assert.equal(res.exit, 1);+ assert.match(res.result.error, /has 2 Pages tables with a File column, so which one the pages come from is ambiguous/);+ assert.equal(res.result.files, undefined);+ // CONTROL: a maker's own `## Pages` list is no second table — the gate reads the real one.+ fs.writeFileSync(p, plan('## Pages', '- Overview: summary cards'));+ const listed = checkPageFiles({ planPath: p });+ assert.equal(listed.exit, 0, JSON.stringify(listed.result));+ assert.deepEqual(listed.result.files, ['approved.tsx']);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++// A section was judged by its first table: a `| Page | Purpose |` table ahead of the `| Page | File |` one hid it, and+// a Pages table quoted elsewhere then passed as the plan's only one. Every table under a Pages heading counts.+test('every table under a Pages heading counts on its own, and rows that are not its File table\'s make the plan unreadable', () => {+ const purpose = ['| Page | Purpose |', '|---|---|', '| Overview | cards |'];+ const files = ['| Page | File | Purpose | Entities |', '|---|---|---|---|', '| A | ../outside.tsx | x | account |'];+ const quoted = ['```', '## Pages', '| Page | File |', '|---|---|', '| A | approved.tsx |', '```'];+ const plan = (requirements, pages) => ['# Genpage Plan', '## User Requirements', 'Build one page.', ...requirements,+ '## Pages', ...pages, '## Entity Creation Required', 'None.'].join('\n');+ // The review's case: the real table after a Purpose table, and a quoted example — two File tables, refused.+ assert.deepEqual(pagesTables(plan(quoted, [...purpose, '', ...files])).tables, [['approved.tsx'], ['../outside.tsx']]);+ assert.equal(pageFilesFromPlan(plan(quoted, [...purpose, '', ...files])), null);+ // Alone, a Purpose table beside the File table still leaves rows no File column claims — rows a reader could take+ // for pages the gates never saw — so the plan is unreadable, not read by its File table alone.+ const beside = plan([], [...purpose, '', ...files]);+ assert.deepEqual(pagesTables(beside), { tables: [['../outside.tsx']], unreadable: true });+ assert.equal(pageFilesFromPlan(beside), null);+ // A blank line inside a table does not end it: its later rows are still its rows, and are checked.+ assert.deepEqual(pageFilesFromPlan(plan([], [...files, '', '| B | b.tsx | y | account |'])), ['../outside.tsx', 'b.tsx']);+ // Rows ahead of the first header belong to no table: the plan is unreadable, rather than those rows dropped.+ const stray = plan([], ['| X | stray.tsx |', '', ...files]);+ assert.equal(pagesTables(stray).unreadable, true);+ assert.equal(pageFilesFromPlan(stray), null);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'page-files-stray-'));+ try {+ const p = path.join(dir, 'genpage-plan.md');+ fs.writeFileSync(p, stray);+ const res = checkPageFiles({ planPath: p });+ assert.equal(res.exit, 1);+ assert.match(res.result.error, /has table rows in a Pages section that are not its File table's rows/);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ // CONTROL: stray rows in a section that names no file are no table, and change nothing.+ assert.deepEqual(pageFilesFromPlan(plan(['## Pages', '| just | a row |'], files)), ['../outside.tsx']);+});++// A delimiter row repeated under a page row made that row the header of a second table — one with no File column, so+// it was dropped, and its page with it: both gates passed a plan whose `../outside.tsx` neither ever saw.+test('a repeated delimiter row cannot turn a page row into a header and hide it', () => {+ const plan = (pages) => ['# Genpage Plan', '## User Requirements', 'Build two pages.', '## Pages', ...pages,+ '## Entity Creation Required', 'None.'].join('\n');+ const header = ['| Page | File | Purpose | Entities |', '|---|---|---|---|'];+ const a = '| A | approved.tsx | Overview | mock data |';+ const b = '| B | ../outside.tsx | Details | mock data |';+ const delimiter = '|---|---|---|---|';+ for (const [what, pages] of [+ ['a delimiter under the last row', [...header, a, b, delimiter]],+ ['a delimiter under a row after a blank line', [...header, a, '', b, delimiter, '| C | c.tsx | x | mock data |']],+ ['a second delimiter directly under the header', [...header, delimiter, a]],+ ['a row that names a File column over a delimiter', [...header, a, '| B | File | Details | mock data |', delimiter, b]],+ ]) {+ const got = pagesTables(plan(pages));+ assert.equal(pageFilesFromPlan(plan(pages)), null, what);+ assert.ok(got.unreadable || got.tables.length > 1, `${what}: ${JSON.stringify(got)}`);+ }+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'page-files-delimiter-'));+ try {+ const p = path.join(dir, 'genpage-plan.md');+ fs.writeFileSync(p, plan([...header, a, b, delimiter]));+ const res = checkPageFiles({ planPath: p });+ assert.equal(res.exit, 1, JSON.stringify(res.result));+ assert.match(res.result.error, /has table rows in a Pages section that are not its File table's rows/);+ assert.equal(res.result.files, undefined, 'no file of the plan is reported as checked');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ // CONTROL: the same rows under one header and one delimiter are read, the unsafe name included.+ assert.deepEqual(pageFilesFromPlan(plan([...header, a, b])), ['approved.tsx', '../outside.tsx']);+});++// Markdown makes a table's outer pipes optional: a row written without its leading pipe was skipped, and its page with+// it — both gates passed a plan whose `../outside.tsx` a reader would still take for a page. And a header with two File+// columns was read by its first.+test('a row without its outer pipes is read, and a table with two File columns is refused', () => {+ const plan = (pages) => ['# Genpage Plan', '## User Requirements', 'Build two pages.', '## Pages', ...pages,+ '## Entity Creation Required', 'None.'].join('\n');+ const header = ['| Page | File | Purpose | Entities |', '|---|---|---|---|'];+ const a = '| A | approved.tsx | Overview | mock data |';+ assert.deepEqual(pageFilesFromPlan(plan([...header, a, 'B | ../outside.tsx | Details | mock data |'])),+ ['approved.tsx', '../outside.tsx'], 'a row with no leading pipe is a row');+ assert.deepEqual(pageFilesFromPlan(plan([...header, a, 'B | b.tsx | Details | mock data'])), ['approved.tsx', 'b.tsx'],+ 'nor a trailing one');+ // A whole table written without outer pipes is a table.+ assert.deepEqual(pageFilesFromPlan(plan(['Page | File | Purpose', '--- | --- | ---', 'A | a.tsx | x'])), ['a.tsx']);+ // An escaped pipe is text, not a row: prose that shows one changes nothing.+ assert.deepEqual(pageFilesFromPlan(plan([...header, a, '', 'Pages are split with \\| in the nav.'])), ['approved.tsx']);+ const two = plan(['| Page | File | File |', '|---|---|---|', '| A | approved.tsx | ../outside.tsx |']);+ assert.deepEqual(pagesTables(two), { tables: [['approved.tsx']], unreadable: true });+ assert.equal(pageFilesFromPlan(two), null);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'page-files-pipes-'));+ try {+ const p = path.join(dir, 'genpage-plan.md');+ fs.writeFileSync(p, plan([...header, a, 'B | ../outside.tsx | Details | mock data |']));+ const res = checkPageFiles({ planPath: p });+ assert.equal(res.exit, 3, JSON.stringify(res.result));+ assert.deepEqual(res.result.files, ['approved.tsx', '../outside.tsx']);+ fs.writeFileSync(p, two);+ const dup = checkPageFiles({ planPath: p });+ assert.equal(dup.exit, 1);+ assert.match(dup.result.error, /or two File columns/);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++// The skill's commands put page paths in double quotes, and some in none, and the orchestrator substitutes the name+// as text: `$(Join-Path .. outside).tsx` passed every rule, and PowerShell expanded it inside the quotes — the+// dispatch stamp landed outside the working directory. A `;` or a space in an unquoted argument ends it.+test('a page name a shell would expand or split on is refused', () => {+ const bad = ['$(Join-Path .. outside).tsx', 'a`b.tsx', 'a;rm -rf ~ #.tsx', 'my page.tsx', 'pages/$HOME/x.tsx',+ "it's.tsx", 'a&b.tsx', 'a%PATH%.tsx', 'wow!.tsx', 'a,b.tsx', 'a(1).tsx', 'a+b.tsx', 'a\u201cb\u201d.tsx', 'a\u2013b.tsx'];+ assert.deepEqual(codes(bad), bad.map((f) => `shell:${f}`));+ const [dollar] = pageFileProblems(['$(Join-Path .. outside).tsx']);+ assert.match(dollar.message, /has "\$" in "\$\(Join-Path \.\. outside\)\.tsx", which a shell command line would expand or split on/);+ assert.match(pageFileProblems(['my page.tsx'])[0].message, /has a space in/);+ // CONTROLS: letters and digits of any script, with their combining marks, `.`, `-` and `_`, in folders too.+ assert.deepEqual(codes(['project-overview.tsx', 'under_score.tsx', 'a.b.tsx', 'pages/home.tsx', './x.tsx',+ '\u00dcbersicht.tsx', '\u6982\u8981.tsx', 'cafe\u0301.tsx', '\u0645\u0644\u062e\u0635.tsx']), []);+});++test('check-page-files.js gates dispatch: exit 0 when safe, 3 with the problems when not, 1 when unreadable', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'page-files-cli-'));+ try {+ const write = (rows) => {+ const p = path.join(dir, 'genpage-plan.md');+ fs.writeFileSync(p, ['## Pages', '| Page | File | Purpose | Entities |', '|---|---|---|---|', ...rows, ''].join('\n'));+ return p;+ };+ const run = (planPath) => spawnSync(process.execPath, [SCRIPT, '--plan', planPath], { encoding: 'utf8' });++ const ok = run(write(['| A | a.tsx | x | account |', '| B | b.tsx | y | account |']));+ assert.equal(ok.status, 0, ok.stdout);+ assert.deepEqual(JSON.parse(ok.stdout).files, ['a.tsx', 'b.tsx']);++ const bad = run(write(['| A | Page.tsx | x | account |', '| B | page.tsx | y | account |', '| C | ..\\out.tsx | z | account |']));+ assert.equal(bad.status, 3, bad.stdout);+ const out = JSON.parse(bad.stdout);+ assert.equal(out.ok, false);+ assert.deepEqual(out.problems.map((p) => p.code).sort(), ['backslash', 'collision']);++ const none = run(write([]));+ assert.equal(none.status, 1, 'a plan that lists no pages is not a pass');+ assert.equal(checkPageFiles({ planPath: path.join(dir, 'missing.md') }).exit, 1);+ assert.equal(checkPageFiles({}).exit, 1);+ // --working-dir overrides the plan's own directory as the root the names must stay inside.+ const plan = write(['| A | a.tsx | x | account |']);+ const other = fs.mkdtempSync(path.join(os.tmpdir(), 'page-files-other-'));+ try {+ const r = spawnSync(process.execPath, [SCRIPT, '--plan', plan, '--working-dir', other], { encoding: 'utf8' });+ assert.equal(r.status, 0, r.stdout);+ assert.equal(JSON.parse(r.stdout).workingDir, path.resolve(other));+ } finally {+ fs.rmSync(other, { recursive: true, force: true });+ }+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++// The working directory ITSELF must not be a link, the rule generate-page-manifest.js applies to the same+// directory: each target resolved inside the link's realpath and passed, and every page a worker wrote went+// wherever it points. A linked ANCESTOR is still followed — a normal setup.+test('a working directory that is itself a link or junction refuses every page written into it', (t) => {+ const parent = fs.mkdtempSync(path.join(os.tmpdir(), 'page-files-rootlink-'));+ t.after(() => fs.rmSync(parent, { recursive: true, force: true }));+ const real = path.join(parent, 'real');+ fs.mkdirSync(real);+ const linked = path.join(parent, 'linked');+ fs.symlinkSync(real, linked, 'junction');+ assert.deepEqual(codes(['overview.tsx', 'pages/details.tsx'], { workingDir: linked }), ['link:overview.tsx', 'link:pages/details.tsx']);+ assert.match(pageFileProblems(['overview.tsx'], { workingDir: linked })[0].message, /working directory, which is itself a symbolic link or junction; pass the directory it points to$/);+ // Built pages are not written, so they are not refused for it; the real directory, and one BELOW a+ // linked ancestor, are fine.+ assert.deepEqual(codes([], { workingDir: linked, built: ['home.tsx'] }), []);+ assert.deepEqual(codes(['overview.tsx'], { workingDir: real }), []);+ fs.mkdirSync(path.join(real, 'app'));+ assert.deepEqual(codes(['overview.tsx'], { workingDir: path.join(linked, 'app') }), []);+ // A DANGLING link has no realpath, and reading that as "not created yet" left only the lexical checks, so a+ // worker's `mkdir -p` created the directory through it. It is refused like any other link — while a working+ // directory that is simply not there yet still gets the lexical checks alone.+ const dangling = path.join(parent, 'dangling');+ fs.symlinkSync(path.join(parent, 'nowhere'), dangling, 'junction');+ assert.deepEqual(codes(['overview.tsx'], { workingDir: dangling }), ['link:overview.tsx']);+ assert.deepEqual(codes(['overview.tsx'], { workingDir: path.join(parent, 'not-yet') }), []);+});++// A built page is not refused for its disk state, but a new page must not reach it through a link: with+// `alias -> sub`, `alias/a.tsx` IS `sub/a.tsx`, and a worker writing the latter overwrote the built page.+test('a new page that is a built page reached through a junction collides with it', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'page-files-builtalias-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.mkdirSync(path.join(root, 'sub'));+ fs.writeFileSync(path.join(root, 'sub', 'a.tsx'), 'export default function A() { return null; }\n');+ fs.symlinkSync(path.join(root, 'sub'), path.join(root, 'alias'), 'junction');+ const problems = pageFileProblems(['sub/a.tsx'], { workingDir: root, built: ['alias/a.tsx'] });+ assert.deepEqual(problems.map((p) => `${p.code}:${p.file}`), ['collision:sub/a.tsx']);+ assert.match(problems[0].message, /"alias\/a\.tsx" and "sub\/a\.tsx" are the same file, reached through a link or junction/);+ // CONTROL: a different built page is no collision.+ assert.deepEqual(codes(['sub/b.tsx'], { workingDir: root, built: ['alias/a.tsx'] }), []);+});diff --git a/plugins/model-apps/scripts/tests/page-plan.test.js b/plugins/model-apps/scripts/tests/page-plan.test.jsindex bff57ae80..477c29304 100644--- a/plugins/model-apps/scripts/tests/page-plan.test.js+++ b/plugins/model-apps/scripts/tests/page-plan.test.js@@ -39,7 +39,7 @@ test('projects every required plan section, in schema order', () => {const required = ['# Genpage Plan', '## User Requirements', '## Working Directory', '## Plugin Root','## Environment', '## Pages', '## Entity Creation Required', '## Existing Entities',- '## Connector Bindings', '## Design Preferences', '## Relevant Samples',+ '## Connector Bindings', '## Custom API Bindings', '## Design Preferences', '## Relevant Samples','## Per-Page Specifications',];let cursor = -1;@@ -78,6 +78,12 @@ test('Connector Bindings uses the exact no-bindings sentinel (app-builder authorassert.match(buildPagePlan(spec(), { workingDir: '/wd' }), /## Connector Bindings\nNo connector bindings\./);});+test('Custom API Bindings uses the exact no-bindings sentinel (app-builder authors no actions)', () => {+ // The Custom API deploy phase must distinguish "none" from "planner forgot the section"; app-builder+ // never authors actions, so it emits the explicit sentinel required by the shared plan schema.+ assert.match(buildPagePlan(spec(), { workingDir: '/wd' }), /## Custom API Bindings\nNo custom API bindings\./);+});+test('every page carries every required per-page field', () => {const md = buildPagePlan(spec(), { workingDir: '/wd' });const blocks = md.split(/^### /m).slice(1);@@ -112,6 +118,68 @@ test('file name is derived from the stable key, but IDENTITY is the key (not theassert.match(md, /\| Detail \| detail \| pages\/9f2c\/page\.tsx \|/, 'Pages row carries Key and File separately');});+test('page targets reject escapes and case-insensitive collisions before projection', () => {+ assert.throws(+ () => buildPagePlan({ app: { name: 'A' }, pages: [{ key: 'p', name: 'P', source: { kind: 'tsx', codeFile: '../outside.tsx' } }] }, { workingDir: '/wd' }),+ /unsafe page file.*traversal|traversal.*unsafe page file/i,+ );+ assert.throws(+ () => buildPagePlan({+ app: { name: 'A' },+ pages: [+ { key: 'one', name: 'One', source: { kind: 'tsx', codeFile: 'Page.tsx' } },+ { key: 'two', name: 'Two', source: { kind: 'tsx', codeFile: 'page.tsx' } },+ ],+ }, { workingDir: '/wd' }),+ /case-insensitive.*collision|collision.*case-insensitive/i,+ );+ // A NEW page whose file is an implemented page's, ignoring case, would be written over it.+ assert.throws(+ () => buildPagePlan({+ app: { name: 'A' },+ pages: [+ { key: 'home', name: 'Home', source: { kind: 'intent', purpose: 'Landing page' } },+ { key: 'built', name: 'Built', source: { kind: 'tsx', codeFile: 'Home.tsx' } },+ ],+ }, { workingDir: '/wd' }),+ /collision[\s\S]*"Home\.tsx" and "home\.tsx"/i,+ );+});++// An implemented page is in the plan for the navigation graph only; its codeFile passed the spec+// gate, which accepts the Windows spelling. Refusing it here blocked the whole /app-builder page plan.+test('an implemented page keeps a path the spec gate accepted, Windows separators included', () => {+ const md = buildPagePlan({+ app: { name: 'A' },+ pages: [+ { key: 'home', name: 'Home', source: { kind: 'tsx', codeFile: 'pages\\home.tsx' } },+ { key: 'report', name: 'Report', source: { kind: 'tsx', codeFile: 'pages/../pages/report.tsx' } },+ { key: 'next', name: 'Next', source: { kind: 'intent', purpose: 'The next page' } },+ ],+ }, { workingDir: '/wd' });+ // Built pages are shown in the one spelling the shared page-file rule accepts, so the plan passes+ // the schema validator that polices it; no worker writes them, so the spelling moves nothing.+ assert.match(md, /\| Home \| home \| pages\/home\.tsx \|/);+ assert.match(md, /\| Report \| report \| pages\/report\.tsx \|/);+ assert.match(md, /- \*\*File:\*\* pages\/home\.tsx/);+ assert.match(md, /\| Next \| next \| next\.tsx \|/);+ const { validateGenpagePlanSchema } = require('../../../../evals/model-apps/genpage/lib/assertions-layer-1.js');+ assert.deepEqual(validateGenpagePlanSchema(md), []);+});++// The spec gate accepts an implemented codeFile that is not `.tsx`, and no worker writes a built page,+// so the write-target `.tsx` rule must not refuse the plan — as it did once that rule was added.+test('an implemented page with a codeFile the spec gate accepts is not refused as a write target', () => {+ const md = buildPagePlan({+ app: { name: 'A' },+ pages: [+ { key: 'home', name: 'Home', source: { kind: 'tsx', codeFile: 'pages/home.jsx' } },+ { key: 'next', name: 'Next', source: { kind: 'intent', purpose: 'The next page' } },+ ],+ }, { workingDir: '/wd' });+ assert.match(md, /\| Home \| home \| pages\/home\.jsx \|/);+});+test('the approved design contract reaches the worker', () => {// Regression: the adapter read `styling`/`theme`/`features`/`accessibility`, none of which are// valid `design` keys (app-spec.js rejects unknown keys), so every approved token was dropped and@@ -253,6 +321,222 @@ test('CLI fails with usage when a required flag has no value', () => {assert.match(res.stderr, /Usage:/);});+// buildPagePlan is pure, so the checks that need the disk run in the CLI — /app-builder's equivalent of+// /genpage's check-page-files.js, before any worker is dispatched. A folder squatting on a page path is+// one of them; nothing is written when it fires.+test('CLI refuses a page a worker could not write safely in the working directory, and writes no plan', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pageplan-disk-'));+ try {+ const specPath = path.join(dir, 'app-spec.json');+ fs.writeFileSync(specPath, JSON.stringify(spec()), 'utf8');+ fs.mkdirSync(path.join(dir, 'overview.tsx'));+ const cli = path.join(__dirname, '..', 'write-page-plan.js');+ const res = spawnSync(process.execPath, [cli, '--spec', '@' + specPath, '--working-dir', dir], { encoding: 'utf8' });+ assert.notEqual(res.status, 0, res.stdout);+ assert.match(res.stdout + res.stderr, /not safe to write in .*"overview\.tsx" already exists and is not a regular file/);+ assert.equal(fs.existsSync(path.join(dir, 'app-builder-page-plan.md')), false, 'no plan is written');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++// A built page is written by no worker, but a new page must not reach it through a link or junction: with+// `loop` pointing back at the working directory, the built `loop/overview.tsx` IS the new `overview.tsx`.+// Only the CLI knows the working directory, so it hands the built pages to the disk check as well.+test('CLI refuses a new page that is a built page reached through a junction', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pageplan-builtalias-'));+ try {+ fs.symlinkSync(dir, path.join(dir, 'loop'), 'junction');+ fs.writeFileSync(path.join(dir, 'overview.tsx'), 'export default function Overview() { return null; }\n');+ const s = spec();+ s.pages[2].source = { kind: 'tsx', codeFile: 'loop/overview.tsx' };+ const specPath = path.join(dir, 'app-spec.json');+ fs.writeFileSync(specPath, JSON.stringify(s), 'utf8');+ const cli = path.join(__dirname, '..', 'write-page-plan.js');+ const res = spawnSync(process.execPath, [cli, '--spec', '@' + specPath, '--working-dir', dir], { encoding: 'utf8' });+ assert.notEqual(res.status, 0, res.stdout);+ assert.match(res.stdout + res.stderr, /"loop\/overview\.tsx" and "overview\.tsx" are the same file, reached through a link or junction/);+ assert.equal(fs.existsSync(path.join(dir, 'app-builder-page-plan.md')), false, 'no plan is written');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++// CONTROL for the test above: the built pages go to the disk check only to be matched against, in the plan's+// own spelling — never held to the rules for a file about to be written. A Windows `pages\home.jsx`, which+// the spec gate accepts, does not stop the CLI.+test('CLI does not refuse a built page in a spelling the spec gate accepts', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pageplan-builtok-'));+ try {+ const s = spec();+ s.pages[2].source = { kind: 'tsx', codeFile: 'pages\\home.jsx' };+ const specPath = path.join(dir, 'app-spec.json');+ fs.writeFileSync(specPath, JSON.stringify(s), 'utf8');+ const cli = path.join(__dirname, '..', 'write-page-plan.js');+ const res = spawnSync(process.execPath, [cli, '--spec', '@' + specPath, '--working-dir', dir], { encoding: 'utf8' });+ assert.equal(res.status, 0, res.stdout + res.stderr);+ assert.equal(JSON.parse(res.stdout).ok, true);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++// The plan is written INTO the working directory, so one that is itself a link or junction is refused even+// when every page is already built, and the page-file rule has no page to refuse.+test('CLI refuses a working directory that is itself a link, even with no page left to write', () => {+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'pageplan-linkedwd-'));+ try {+ const real = path.join(base, 'real');+ fs.mkdirSync(real);+ const link = path.join(base, 'link');+ fs.symlinkSync(real, link, 'junction');+ const s = spec();+ s.pages.forEach((p, i) => { p.source = { kind: 'tsx', codeFile: `built-${i}.tsx` }; });+ const specPath = path.join(base, 'app-spec.json');+ fs.writeFileSync(specPath, JSON.stringify(s), 'utf8');+ const cli = path.join(__dirname, '..', 'write-page-plan.js');+ const res = spawnSync(process.execPath, [cli, '--spec', '@' + specPath, '--working-dir', link], { encoding: 'utf8' });+ assert.notEqual(res.status, 0, res.stdout);+ assert.match(res.stdout + res.stderr, /refusing to write the page plan into .* symbolic link or junction/);+ assert.equal(fs.existsSync(path.join(real, 'app-builder-page-plan.md')), false, 'nothing is written through the link');+ // CONTROL: the directory it points to is accepted.+ const ok = spawnSync(process.execPath, [cli, '--spec', '@' + specPath, '--working-dir', real], { encoding: 'utf8' });+ assert.equal(ok.status, 0, ok.stdout + ok.stderr);+ } finally {+ fs.rmSync(base, { recursive: true, force: true });+ }+});++// A working directory that cannot even be inspected is refused with a reason, not a stack trace.+// A FILE at the working-directory path cannot hold the plan: refused with a reason before anything is written,+// not left to throw EEXIST out of mkdir.+test('CLI refuses a working directory that exists and is not a directory', () => {+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'pageplan-wdfile-'));+ try {+ const wd = path.join(base, 'not-a-dir');+ fs.writeFileSync(wd, 'x');+ const specPath = path.join(base, 'app-spec.json');+ fs.writeFileSync(specPath, JSON.stringify(spec()), 'utf8');+ const cli = path.join(__dirname, '..', 'write-page-plan.js');+ const res = spawnSync(process.execPath, [cli, '--spec', '@' + specPath, '--working-dir', wd], { encoding: 'utf8' });+ assert.notEqual(res.status, 0, res.stdout);+ assert.match(res.stdout + res.stderr, /refusing to write the page plan into .* it exists and is not a directory/);+ assert.doesNotMatch(res.stdout + res.stderr, /EEXIST|\n\s+at /, 'a reason, not a stack trace');+ assert.equal(fs.readFileSync(wd, 'utf8'), 'x', 'the file is untouched');+ } finally {+ fs.rmSync(base, { recursive: true, force: true });+ }+});++// The plan file is checked like the working directory: a link or hard link at its path put the plan wherever+// it points. Its path is not configurable — an --out could name any file, the input spec included.+test('CLI refuses to write the plan through a link, a hard link or a folder, and takes no --out', (t) => {+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'pageplan-leaf-'));+ t.after(() => fs.rmSync(base, { recursive: true, force: true }));+ const wd = path.join(base, 'wd');+ const outside = path.join(base, 'outside');+ fs.mkdirSync(wd);+ fs.mkdirSync(outside);+ const specPath = path.join(base, 'app-spec.json');+ fs.writeFileSync(specPath, JSON.stringify(spec()), 'utf8');+ const cli = path.join(__dirname, '..', 'write-page-plan.js');+ const run = (...extra) => spawnSync(process.execPath, [cli, '--spec', '@' + specPath, '--working-dir', wd, ...extra], { encoding: 'utf8' });+ const planPath = path.join(wd, 'app-builder-page-plan.md');+ // A HARD link needs no privilege on Windows.+ const precious = path.join(outside, 'precious.md');+ fs.writeFileSync(precious, 'keep me');+ fs.linkSync(precious, planPath);+ let res = run();+ assert.notEqual(res.status, 0, res.stdout);+ assert.match(res.stdout + res.stderr, /refusing to write the page plan to .* not a plain file/);+ assert.equal(fs.readFileSync(precious, 'utf8'), 'keep me', 'the other name is untouched');+ fs.unlinkSync(planPath);+ // A folder at the plan path gets a reason, not EISDIR.+ fs.mkdirSync(planPath);+ res = run();+ assert.notEqual(res.status, 0, res.stdout);+ assert.match(res.stdout + res.stderr, /not a plain file/);+ assert.doesNotMatch(res.stdout + res.stderr, /EISDIR|\n\s+at /, 'a reason, not a stack trace');+ fs.rmdirSync(planPath);+ // A symbolic link, where one can be made (a file link needs a privilege on Windows).+ let linked = true;+ try { fs.symlinkSync(path.join(outside, 'target.md'), planPath, 'file'); } catch { linked = false; }+ if (linked) {+ res = run();+ assert.notEqual(res.status, 0, res.stdout);+ assert.match(res.stdout + res.stderr, /not a plain file/);+ assert.deepEqual(fs.readdirSync(outside), ['precious.md'], 'nothing is written through the dangling link');+ fs.unlinkSync(planPath);+ }+ // --out is no flag at all: it could name the input spec, which the plan would then overwrite.+ fs.writeFileSync(path.join(wd, 'app-spec.json'), '{"keep":true}');+ res = run('--out', path.join(wd, 'app-spec.json'));+ assert.notEqual(res.status, 0, res.stdout);+ assert.match(res.stdout + res.stderr, /--out/);+ assert.equal(fs.readFileSync(path.join(wd, 'app-spec.json'), 'utf8'), '{"keep":true}');+ assert.deepEqual(fs.readdirSync(outside), ['precious.md']);+ // CONTROL: a plain plan left by an earlier run is rewritten.+ fs.writeFileSync(planPath, 'stale');+ res = run();+ assert.equal(res.status, 0, res.stdout + res.stderr);+ assert.notEqual(fs.readFileSync(planPath, 'utf8'), 'stale');+});++test('CLI refuses a plan path it cannot inspect, and writes no plan', (t) => {+ const dir = fs.mkdtempSync(path.join(__dirname, '.tmp-pageplan-leafstat-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const specPath = path.join(dir, 'app-spec.json');+ fs.writeFileSync(specPath, JSON.stringify(spec()), 'utf8');+ const planPath = path.join(dir, 'app-builder-page-plan.md');+ const cliPath = path.join(__dirname, '..', 'write-page-plan.js');+ const { main } = require(cliPath);+ const saved = { argv: process.argv, exit: process.exit, err: process.stderr.write, lstat: fs.lstatSync };+ let stderr = '';+ try {+ process.argv = [process.execPath, cliPath, '--spec', '@' + specPath, '--working-dir', dir];+ process.stderr.write = (chunk) => { stderr += String(chunk); return true; };+ process.exit = (code) => { throw new Error(`process.exit(${code})`); };+ fs.lstatSync = (p, ...rest) => {+ if (path.resolve(String(p)) === path.resolve(planPath)) throw Object.assign(new Error('permission denied'), { code: 'EACCES' });+ return saved.lstat.call(fs, p, ...rest);+ };+ assert.throws(() => main(), /process\.exit\(1\)/);+ } finally {+ Object.assign(process, { argv: saved.argv, exit: saved.exit });+ process.stderr.write = saved.err;+ fs.lstatSync = saved.lstat;+ }+ assert.match(stderr, /cannot inspect .*app-builder-page-plan\.md \(EACCES\)/);+ assert.equal(fs.existsSync(planPath), false, 'no plan is written');+});++test('CLI refuses a working directory it cannot inspect, and writes no plan', (t) => {+ const dir = fs.mkdtempSync(path.join(__dirname, '.tmp-pageplan-lstat-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const specPath = path.join(dir, 'app-spec.json');+ fs.writeFileSync(specPath, JSON.stringify(spec()), 'utf8');+ const cliPath = path.join(__dirname, '..', 'write-page-plan.js');+ const { main } = require(cliPath);+ const saved = { argv: process.argv, exit: process.exit, err: process.stderr.write, lstat: fs.lstatSync };+ let stderr = '';+ try {+ process.argv = [process.execPath, cliPath, '--spec', '@' + specPath, '--working-dir', dir];+ process.stderr.write = (chunk) => { stderr += String(chunk); return true; };+ process.exit = (code) => { throw new Error(`process.exit(${code})`); };+ fs.lstatSync = (p, ...rest) => {+ if (path.resolve(String(p)) === path.resolve(dir)) throw Object.assign(new Error('permission denied'), { code: 'EACCES' });+ return saved.lstat.call(fs, p, ...rest);+ };+ assert.throws(() => main(), /process\.exit\(1\)/);+ } finally {+ Object.assign(process, { argv: saved.argv, exit: saved.exit });+ process.stderr.write = saved.err;+ fs.lstatSync = saved.lstat;+ }+ assert.match(stderr, /cannot inspect the working directory .* \(EACCES\)/);+ assert.equal(fs.existsSync(path.join(dir, 'app-builder-page-plan.md')), false, 'no plan is written');+});+test('CLI refuses to write a plan when a referenced sample is absent', (t) => {const dir = fs.mkdtempSync(path.join(__dirname, '.tmp-pageplan-'));t.after(() => fs.rmSync(dir, { recursive: true, force: true }));@@ -269,7 +553,7 @@ test('CLI refuses to write a plan when a referenced sample is absent', (t) => {let stderr = '';try {- process.argv = [process.execPath, cliPath, '--spec', '@' + specPath, '--working-dir', dir, '--out', outPath];+ process.argv = [process.execPath, cliPath, '--spec', '@' + specPath, '--working-dir', dir];process.stderr.write = (chunk) => { stderr += String(chunk); return true; };process.exit = (code) => { throw new Error(`process.exit(${code})`); };fs.existsSync = (p) => (diff --git a/plugins/model-apps/scripts/tests/pageref-resolver.test.js b/plugins/model-apps/scripts/tests/pageref-resolver.test.jsindex 00aa2dffb..9d6a92328 100644--- a/plugins/model-apps/scripts/tests/pageref-resolver.test.js+++ b/plugins/model-apps/scripts/tests/pageref-resolver.test.js@@ -26,7 +26,7 @@ test('extractNavTargets classifies a canonical PAGEREF nav pageId (structuralassert.strictEqual(t[0].key, 'detail');});-test('extractNavTargets IGNORES a decoy "PAGEREF_" string that is NOT a nav pageId (C1 oracle)', () => {+test('extractNavTargets IGNORES a decoy "PAGEREF_" string that is NOT a nav pageId', () => {const code = `const label = "PAGEREF_detail"; // decoy, not navigation\n${NAV('"PAGEREF_gallery"')}`;const t = extractNavTargets(code);assert.strictEqual(t.length, 1, 'only the real nav call site counts');@@ -52,14 +52,14 @@ test('extractNavTargets handles pageId BEFORE pageType and a nested data:{} objeassert.strictEqual(t[0].key, 'detail', 'the top-level pageId is the target — a PAGEREF-looking string inside data:{} is NOT');});-// ─── Comment and template-literal stripping (addendum Crit 1) ────────────────+// ─── Comment and template-literal stripping ──────────────────────────────────//// A navigateTo inside a comment or template literal is NOT a real call site. The// stripping pass blanks those regions (same-length space substitution) before the// NAV_CALL regex runs, so an in-comment or in-template navigateTo is invisible to-// the oracle. These three tests are REQUIRED by the Plan-3 implementer addendum.+// the oracle.-test('extractNavTargets IGNORES a navigateTo inside a // line comment (addendum Crit 1)', () => {+test('extractNavTargets IGNORES a navigateTo inside a // line comment', () => {const real = NAV('"PAGEREF_real"');const code = `// ${NAV('"PAGEREF_commented"')}\n${real}`;const t = extractNavTargets(code);@@ -68,7 +68,7 @@ test('extractNavTargets IGNORES a navigateTo inside a // line comment (addendumassert.deepStrictEqual(navReferencedKeys(code), ['real'], 'the commented navigateTo is not a referenced key');});-test('extractNavTargets IGNORES a navigateTo inside a /* */ block comment (addendum Crit 1)', () => {+test('extractNavTargets IGNORES a navigateTo inside a /* */ block comment', () => {const real = NAV('"PAGEREF_real"');const code = `/* ${NAV('"PAGEREF_block"')} */\n${real}`;const t = extractNavTargets(code);@@ -77,7 +77,7 @@ test('extractNavTargets IGNORES a navigateTo inside a /* */ block comment (addenassert.deepStrictEqual(navReferencedKeys(code), ['real'], 'the block-commented navigateTo is not a referenced key');});-test('extractNavTargets IGNORES a navigateTo inside a backtick template literal (addendum Crit 1)', () => {+test('extractNavTargets IGNORES a navigateTo inside a backtick template literal', () => {const real = NAV('"PAGEREF_real"');// The backtick string contains the navigateTo as template-literal TEXT, not a real call.// eslint-disable-next-line no-template-curly-in-string@@ -88,15 +88,118 @@ test('extractNavTargets IGNORES a navigateTo inside a backtick template literalassert.deepStrictEqual(navReferencedKeys(code), ['real'], 'the template-literal navigateTo is not a referenced key');});+test('extractNavTargets IGNORES navigateTo prose inside ordinary quoted strings', () => {+ const code = [+ 'const help = \'navigateTo({ pageType: "generative", pageId: "PAGEREF_detail" })\';',+ 'const label = "Use Xrm.Navigation.navigateTo({ pageType: \\"generative\\", pageId: \\"PAGEREF_gallery\\" }) from a button.";'+ ].join('\n');+ assert.deepStrictEqual(extractNavTargets(code), [], 'ordinary string text is inert and must not satisfy navigation parity');+ assert.deepStrictEqual(navReferencedKeys(code), [], 'declared edges cannot be satisfied by help text');+});++test('extractNavTargets ignores navigateTo text inside regex literals after arrows', () => {+ const code = 'const pattern = count<limit ? () => /navigateTo({ pageType: "generative", pageId: "PAGEREF_detail" })/ : () => /none/;';+ assert.deepStrictEqual(navReferencedKeys(code), []);+ const { deployment, unresolved } = resolvePageRefs(new Map([['x', { code }]]), new Map([['detail', 'gp-detail']]));+ assert.deepStrictEqual(unresolved, []);+ assert.strictEqual(deployment.get('x'), code);+});++test('extractNavTargets does not join separate template substitutions into a fake navigateTo call', () => {+ const code = 'const hint = `${Xrm.Navigation.navigateTo} is a function; input: ${({ pageType: "generative", pageId: "PAGEREF_detail" })}`;';+ assert.deepStrictEqual(navReferencedKeys(code), []);+ const { deployment, unresolved } = resolvePageRefs(new Map([['x', { code }]]), new Map([['detail', 'gp-detail']]));+ assert.deepStrictEqual(unresolved, []);+ assert.strictEqual(deployment.get('x'), code);+});++test('extractNavTargets INSPECTS executable template expressions while ignoring template text', () => {+ const guid = '11111111-2222-3333-4444-555555555555';+ const code = [+ 'const textOnly = `navigateTo({ pageType: "generative", pageId: "PAGEREF_text" })`;',+ 'const rendered = `${Xrm.Navigation.navigateTo({',+ ' pageType: "generative",',+ ` pageId: "${guid}"`,+ '})}`;',+ ].join('\n');+ const t = extractNavTargets(code);+ assert.strictEqual(t.length, 1, 'template text is inert, but JavaScript inside ${...} is executable');+ assert.strictEqual(t[0].kind, 'literal');+ assert.strictEqual(t[0].pageId, guid);+ assert.deepStrictEqual(navReferencedKeys(code), [], 'hard-coded targets inside ${...} must still fail portability parity');+});++test('extractNavTargets finds real navigateTo calls in TSX-shaped executable positions', () => {+ const code = [+ 'const arrow = () => Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_arrow" });',+ 'export default function P(){',+ ' return <button onClick={() => Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_attr" })}>',+ ' {`${Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_template" })}`}',+ ' </button>;',+ '}',+ ].join('\n');+ assert.deepStrictEqual(navReferencedKeys(code), ['arrow', 'attr', 'template']);+});++// The shapes inside `${...}` the expression scanner must tell apart. Inert text in a string, a regex+// or a comment inside an expression must not count, and a `}` inside one must not end the expression+// early — that would expose the rest of the template TEXT as code. Nested templates recurse: their+// own text is inert, their own expressions are executable.+test('extractNavTargets handles strings, regexes, comments and nested templates inside ${...}', () => {+ const call = (key) => `Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_${key}" })`;+ const cases = [+ ['a string holding the call text', '`${"' + 'navigateTo({ pageType: \\"generative\\", pageId: \\"PAGEREF_str\\" })' + '"}`', []],+ ['a regex holding the call text', '`${/navigateTo\\({ pageId: "PAGEREF_re" }\\)/.source}`', []],+ ['a block comment holding the call', '`${/* ' + call('cmt') + ' */ label}`', []],+ ['a line comment, then a real call', '`${// ' + call('line') + '\n' + call('after') + '}`', ['after']],+ ['a "}" inside a string does not end the expression', '`${"}" + ' + call('brace') + '} tail navigateTo({ pageType: "generative", pageId: "PAGEREF_tail" })`', ['brace']],+ ['a "}" inside a comment does not end the expression', '`${/* first line\n } */ ' + call('cmtbrace') + '} tail navigateTo({ pageType: "generative", pageId: "PAGEREF_tail2" })`', ['cmtbrace']],+ ['a nested template: text inert, expression live', '`outer ${`inner ' + call('innertext').replace('Xrm.Navigation.', '') + ' ${' + call('nested') + '}`}`', ['nested']],+ ['an escaped backtick in template text', '`a \\` b ' + call('esc').replace('Xrm.Navigation.', '') + '`', []],+ // The everyday shape: an interpolated template (a className, a label) and then a real call. The+ // expression must end at its own `}` — run it to the end of the file and the template's closing+ // backtick opens a phantom template that hides every call after it.+ ['a real call after an interpolated template', 'const label = `Hello ${name}`;\n' + call('after'), ['after']],+ // Call sites and objects come from the lexer's mask, values from the source at the same offsets,+ // so the two must agree on every offset. An emoji is two UTF-16 units; split by code point, one+ // blanked in a comment shortened a copy by one and the next call was looked for one character off.+ ['a call after an emoji in a comment', call('first') + ';\n// 📌 pinned\n' + call('second'), ['first', 'second']],+ ['a call after an emoji in template text', call('first') + ';\nconst banner = `🔥 ${count} hot leads`;\n' + call('second'), ['first', 'second']],+ ['a call after a nested template with braces in its text', call('first') + ';\nconst j = `[${rows.map((r) => `{"id":"${r.id}"}`).join(",")}]`;\n' + call('second'), ['first', 'second']],+ // The `/` of `</span>` inside `${…}`, and the `/` after `counts.new` or `closed!`, divide or+ // close a tag; read as a regex opener, each hid every call after it.+ ['a call after JSX inside a template expression', call('first') + ';\nconst t = `${<span>Save</span>}`;\n' + call('second'), ['first', 'second']],+ ['a call after a keyword-named property divided', call('first') + ';\nconst el = <Text>{counts.new / total}</Text>;\n' + call('second'), ['first', 'second']],+ ['a call after a non-null assertion divided', call('first') + ';\nconst el = <Text>{closed! / total}</Text>;\n' + call('second'), ['first', 'second']],+ // A regex holding `/*`, `//` or a backtick is a regex. A copy that knew no regexes opened a+ // comment or a template there, blanked every later call, and left its PAGEREF unresolved.+ ['a call after a regex holding /*', call('first') + ';\nconst clean = (u: string) => u.replace(/\\/*$/, "");\n' + call('second'), ['first', 'second']],+ ['a call after a regex holding a backtick', call('first') + ';\nconst unquote = (s: string) => s.replace(/`/g, "");\n' + call('second'), ['first', 'second']],+ ['a call on the line of a regex holding //', call('first') + ';\nconst u = x.replace(/\\/\\//g, "/"); ' + call('second'), ['first', 'second']],+ ['a "}" in a regex inside the call object', 'Xrm.Navigation.navigateTo({ pageType: "generative", data: { re: /}/ }, pageId: "PAGEREF_inside" });', ['inside']],+ ];+ for (const [what, code, keys] of cases) {+ assert.deepStrictEqual(navReferencedKeys(code), keys, what);+ }+});++// Truncated worker output ends mid-template or mid-expression. That must not throw, and a real call+// before the truncation must still be found; nothing after it is code.+test('extractNavTargets survives a template or ${...} left open at end of file', () => {+ const call = 'Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_before" });';+ assert.deepStrictEqual(navReferencedKeys(`${call}\nconst t = \`unterminated navigateTo({ pageId: "PAGEREF_x" })`), ['before']);+ assert.deepStrictEqual(navReferencedKeys(`${call}\nconst t = \`\${foo(`), ['before']);+});+// ─── navMalformedRefs ─────────────────────────────────────────────────────────-test('navMalformedRefs flags a single-quoted PAGEREF_ used as a nav pageId (C4 grammar)', () => {+test('navMalformedRefs flags a single-quoted PAGEREF_ used as a nav pageId', () => {const code = "Xrm.Navigation.navigateTo({ pageType: 'generative', pageId: 'PAGEREF_detail' });";assert.deepStrictEqual(navMalformedRefs(code), ['PAGEREF_detail']);assert.deepStrictEqual(navReferencedKeys(code), [], 'a malformed ref is NOT a valid canonical reference');});-test('navMalformedRefs flags a backtick-quoted PAGEREF_ used as a nav pageId (C4 — backtick cannot be resolved)', () => {+test('navMalformedRefs flags a backtick-quoted PAGEREF_ used as a nav pageId (a backtick cannot be resolved)', () => {// A backtick-quoted PAGEREF cannot be substituted by the resolver (only the canonical// double-quoted token is substitutable), so it is malformed and must HALT.const code = 'Xrm.Navigation.navigateTo({ pageType: "generative", pageId: `PAGEREF_detail` });';@@ -106,7 +209,7 @@ test('navMalformedRefs flags a backtick-quoted PAGEREF_ used as a nav pageId (C4// ─── navReferencedKeys + navTargetParity ─────────────────────────────────────-test('navReferencedKeys returns [] for a literal GUID pageId; parity flags declared edge as unreferenced (M3)', () => {+test('navReferencedKeys returns [] for a literal GUID pageId; parity flags declared edge as unreferenced', () => {// A deployed/stale GUID in the source is not a canonical PAGEREF, so it is not a referenced// key and parity correctly reports the declared edge as unreferenced.const code = 'Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "5d29d8ce-1111-2222-3333-444455556666" });';@@ -118,7 +221,7 @@ test('navReferencedKeys returns [] for a literal GUID pageId; parity flags decla);});-test('extractNavTargets classifies a "a" + "b" concat pageId as dynamic, not literal (M4)', () => {+test('extractNavTargets classifies a "a" + "b" concat pageId as dynamic, not literal', () => {// A string concat is not a single literal — the tightened QUOTED regex excludes cross-quote spans// and topLevelValue detects the trailing '+' and widens the span to the full expression.const code = NAV('"a" + "b"');diff --git a/plugins/model-apps/scripts/tests/promote-intent-pages.test.js b/plugins/model-apps/scripts/tests/promote-intent-pages.test.jsindex f5c56d119..0175ccf19 100644--- a/plugins/model-apps/scripts/tests/promote-intent-pages.test.js+++ b/plugins/model-apps/scripts/tests/promote-intent-pages.test.js@@ -64,9 +64,9 @@ test('ONE failing page aborts the whole promotion and leaves the spec byte-identassert.equal(fs.readFileSync(path.join(dir, 'app-spec.json'), 'utf8'), before, 'spec untouched');});-test('rejects Sol-class prose that only LOOKS like a module', () => {- // A plain `export default` substring search — even over pageref-resolver's stripNonCode, which- // preserves ordinary string bodies — accepted every one of these, promoting prose as a page.+test('rejects prose that only LOOKS like a module', () => {+ // A plain `export default` substring search — even over a copy that keeps ordinary string+ // bodies — accepted every one of these, promoting prose as a page.for (const [name, code, expected] of [['empty', ' \n', /file is empty/],['no default export', 'export function P() {}\n', /no real `export default/],@@ -78,6 +78,17 @@ test('rejects Sol-class prose that only LOOKS like a module', () => {['line-commented export', '// export default function P(){}\nThis is prose\n', /no real `export default/],['empty default export', 'export default;\n', /no real `export default/],['truncated write', 'export default function P() {\n return <div>\n', /truncated/],+ // Cut right after a complete statement: it ends in plain code, so only the bracket count sees it.+ ['truncated after a complete statement', 'export default function P() {\n const a = 1;\n return null;\n', /unbalanced brackets/],+ // Cut inside the export statement itself: nothing is left open, so brackets balance.+ ['write cut after the export header', 'import * as React from "react";\nexport default function P(props: Props)', /no real `export default/],+ ['write cut mid-name', 'const GeneratedComponent = () => <div/>;\nexport default GeneratedComp', /no real `export default/],+ // Every bracket balances and the export is intact, but the write stopped mid-statement.+ ['write cut inside JSX', 'export default () => <div>Loading', /stops mid-statement/],+ // Elided code fails promotion as it fails the worker gate: the shared elision rule.+ ['a TODO elision', 'export default function P() {\n // TODO: render the rest\n return null;\n}\n', /incomplete/],+ ['an elided block', 'export default function P() {\n // ...\n return null;\n}\n', /incomplete/],+ ['omitted for brevity', 'export default function P() {\n /* omitted for brevity */\n return null;\n}\n', /incomplete/],]) {const dir = makeWorkspace({ app: { name: 'A' }, pages: [{ key: 'overview', name: 'Overview', source: { kind: 'intent' } }] },@@ -98,6 +109,16 @@ test('accepts the legitimate default-export forms a worker really emits', () =>['after a doc comment mentioning export default', '/**\n * export default is required\n */\nexport default function P(){ return <div/>; }\n'],['aliased default export', 'function P(){ return <div/>; }\nexport { P as default };\n'],['JSX text with an apostrophe', "export default function P(){ return <p>it's fine</p>; }\n"],+ // A `/` after a property named like a keyword, or after a non-null assertion, divides.+ ['a keyword-named property divided', 'export default function P(){ const c = { new: 3 }; return <p>{c.new / 8}</p>; }\n'],+ ['a non-null assertion divided', 'export default function P(){ const n: number | null = 3; return <p>{n! / 8}</p>; }\n'],+ ['JSX inside a template expression', 'const x = `${<span>Save</span>}`;\nexport default function P(){ return <div/>; }\n'],+ // …and data or prose that only resembles what the gate refuses: a fence inside a template literal, UI copy+ // that says "Loading…", and a comment ABOUT a todo list — the same reading the worker gate gives them.+ ['a markdown fence inside a template', 'const help = `\n\\`\\`\\`tsx\nconst a = 1;\n\\`\\`\\`\n`;\nexport default function P(){ return <pre>{help}</pre>; }\n'],+ ['a markdown fence inside a block comment', '/* usage:\n```\n<Page />\n```\n*/\nexport default function P(){ return null; }\n'],+ ['UI copy that says Loading…', 'export default function P(){ return <div>Loading\u2026</div>; }\n'],+ ['a comment about the todo list', '// Renders the todo list.\nexport default function P(){ return null; }\n'],]) {const dir = makeWorkspace({ app: { name: 'A' }, pages: [{ key: 'overview', name: 'Overview', source: { kind: 'intent' } }] },diff --git a/plugins/model-apps/scripts/tests/source-literals.test.js b/plugins/model-apps/scripts/tests/source-literals.test.jsindex eaa335e7f..9e593cab5 100644--- a/plugins/model-apps/scripts/tests/source-literals.test.js+++ b/plugins/model-apps/scripts/tests/source-literals.test.js@@ -8,8 +8,35 @@ const test = require('node:test');const assert = require('node:assert');const fs = require('node:fs');const path = require('node:path');-const { execFileSync } = require('node:child_process');-const { blankLiterals, hasDefaultExport, hasUnbalancedBrackets } = require('../lib/source-literals.js');+const { execFileSync, spawnSync } = require('node:child_process');+const { blankLiterals, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, scanTemplateExpressionEnd, expressionPosition } = require('../lib/source-literals.js');+const { navReferencedKeys } = require('../lib/pageref-resolver.js');++// The TypeScript parser the lexer's review snippets are checked against. The plugin ships dependency-free, so a+// checkout has none: point TYPESCRIPT_ORACLE_PATH at a `typescript` package to run that check, skipped otherwise.+function loadTypescriptOracle() {+ const at = process.env.TYPESCRIPT_ORACLE_PATH;+ if (!at) return null;+ try {+ return require(at);+ } catch {+ return null;+ }+}++function parseDiagnosticMessages(ts, code) {+ return ts.createSourceFile('snippet.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)+ .parseDiagnostics+ .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '\n'));+}++function assertTsParses(ts, code, label) {+ assert.deepEqual(parseDiagnosticMessages(ts, code), [], label);+}++function assertTsRejects(ts, code, pattern, label) {+ assert.match(parseDiagnosticMessages(ts, code).join('\n'), pattern, label);+}test('blanks comments, strings and template bodies while preserving offsets', () => {const src = 'const a = "hi"; // note\nconst b = `t${x}`; /* c */ const d = 1;';@@ -157,6 +184,717 @@ test('hasUnbalancedBrackets flags a truncated write but tolerates JSX and generiassert.equal(hasUnbalancedBrackets('export default function P() {\n return <C<`https://${string}`> value={(} />;\n}\n'), true);});+// A cut that leaves every bracket balanced: inside JSX, a string, a template or a comment, or right+// after a token that needs more. A complete module ends in plain code.+test('endsMidStatement catches a cut that leaves every bracket balanced', () => {+ const ok = 'import * as React from "react";\nconst Inner = () => null;\n';+ for (const [what, code] of [+ ['inside a tag name', 'export default (props) => <GeneratedCompo'],+ ['inside an attribute string', 'export default (props) => <GeneratedComponent title="x'],+ ['inside JSX text', 'export default () => <div>Loading'],+ ['inside a JSX expression', 'export default () => <div>{count'],+ ['inside a closing tag', 'export default () => <div>ok</div'],+ ['inside a self-closing tag', 'export default () => <Icon /'],+ ['inside a template', `${ok}export default Inner;\nconst note = \`unfinished`],+ ['inside a block comment', `${ok}export default Inner;\n/* trailing`],+ ['inside a string', `${ok}export default Inner;\nconst s = "abc`],+ ['inside a regex', `${ok}export default Inner;\nconst r = /ab`],+ ['after an operator', `${ok}export default Inner;\nconst total = count *`],+ ['after a dot', `${ok}export default React.`],+ ['after `new`', `${ok}export default Inner;\nconst x = new`],+ ['after `=>`', 'export default (props) =>'],+ // A statement keyword cannot end a module either: cut right after one, following a complete export.+ ['after a trailing `export`', `${ok}export default Inner;\nexport`],+ ['after a trailing `export const`', `${ok}export default Inner;\nexport const`],+ ['after a trailing `function`', `${ok}export default Inner;\nfunction`],+ ]) {+ assert.equal(endsMidStatement(code), true, what);+ }+ for (const [what, code] of [+ ['a normal page', `${ok}export default Inner;\n`],+ ['JSX as the last thing', 'export default () => <div>ok</div>'],+ ['a self-closing tag as the last thing', 'export default () => <Icon />'],+ ['a line comment as the last thing', `${ok}export default Inner; // done`],+ ['a postfix increment as the last thing', 'let x = 0;\nx++'],+ ['a non-null assertion as the last thing', 'const y = x!'],+ ['a regex as the last thing', 'const r = /a+/'],+ ['a complete template as the last thing', 'const t = `a ${b} c`'],+ // A keyword reached as a property, and `void` as a type, can end a statement.+ ['a type ending in void', `${ok}export default Inner;\ntype Handler = (e: Event) => void`],+ ['a declared function returning void', `${ok}export default Inner;\ndeclare function track(e: string): void`],+ ['a keyword-named property as the last thing', `${ok}export default Inner;\nexport const w = counts.new`],+ ['an optional keyword-named property as the last thing', `${ok}export default Inner;\nexport const w = counts?.new`],+ ['a property named delete as the last thing', `${ok}export default Inner;\nexport const d = api.delete`],+ ['a property named default as the last thing', `${ok}export default Inner;\nexport const e = mod.default`],+ ['a debugger statement as the last thing', `${ok}export default Inner;\ndebugger`],+ ]) {+ assert.equal(endsMidStatement(code), false, what);+ }+});++// Ground truth from a real parser: for each valid module, the gates accept the whole module, and any+// prefix they accept (a cut the gates cannot see) must itself parse — a syntactically complete module,+// such as `export default React` cut from `export default React.memo(Inner);`. The modules are plain+// JavaScript because Node's parser takes no JSX or TypeScript, and each ends with its default export:+// a cut inside code AFTER a complete export can stop at a point that balances and ends on a name+// (`…\nfunction helper() `), which only the build's compile step catches — a documented limit. A+// child process runs the scan, since vm.SourceTextModule needs --experimental-vm-modules.+test('every prefix the gates accept is a module a real parser accepts', () => {+ const modules = [+ 'function GeneratedComponent() { return 1; }\nexport default GeneratedComponent;\n',+ 'const GeneratedComponent = () => { const a = [1, 2]; return a.map((x) => x * 2); };\nexport default GeneratedComponent;\n',+ 'export default function GeneratedComponent(props) { const s = `a ${props.b} c`; return s.replace(/\\/*$/, ""); }\n',+ 'import * as React from "react";\nconst Inner = () => null;\nexport default React.memo(Inner);\n',+ 'export default async (x) => { await x; return x; };\n',+ 'export default class Page { render() { return null; } }\n',+ 'const Header = () => null, GeneratedComponent = () => Header;\nexport default GeneratedComponent;\n',+ 'export default (async (x) => x);\n',+ 'let count = 0;\nfor (const x of [1, 2]) if (x) /\\(/.test(String(x)) && count++;\nexport default function P() { return count; }\n',+ 'const counts = { new: 3 }, total = 8;\nconst pct = Math.round((counts.new / total) * 100);\nexport default function P() { return `${pct}% new`; }\n',+ 'import { a as b } from "./x";\nconst { c: GeneratedComponent } = b;\nexport default GeneratedComponent;\n',+ ];+ const script = `+ const vm = require('node:vm');+ const sl = require(${JSON.stringify(require.resolve('../lib/source-literals.js'))});+ const parses = (code) => { try { new vm.SourceTextModule(code); return true; } catch { return false; } };+ const accepts = (code) => sl.hasDefaultExport(code) && !sl.hasUnbalancedBrackets(code) && !sl.endsMidStatement(code);+ const out = { unparsable: [], rejected: [], brokenCuts: [] };+ for (const m of ${JSON.stringify(modules)}) {+ if (!parses(m)) { out.unparsable.push(m); continue; }+ if (!accepts(m)) out.rejected.push(m);+ for (let L = 1; L < m.length; L += 1) {+ const p = m.slice(0, L);+ if (accepts(p) && !parses(p)) out.brokenCuts.push(p);+ }+ }+ process.stdout.write(JSON.stringify(out));`;+ const r = spawnSync(process.execPath, ['--experimental-vm-modules', '-e', script], { encoding: 'utf8' });+ assert.equal(r.status, 0, r.stderr);+ const out = JSON.parse(r.stdout);+ assert.deepEqual(out.unparsable, [], 'every sample module is valid JavaScript');+ assert.deepEqual(out.rejected, [], 'no complete module is refused');+ assert.deepEqual(out.brokenCuts, [], 'no prefix that fails to parse is accepted');+});++// Inside `${…}` a `/` is a regex or a division depending on the CODE before it. A comment's last word+// is not that code, in either direction.+test('a closed TypeScript type assertion inside a template expression is an operand before division', () => {+ const code = [+ 'import React from "react";',+ 'const total = 12, count = 2;',+ 'const label = `${total as NonNullable<number> / count}/month`;',+ 'const GeneratedComponent = () => React.createElement("span", null, label);',+ 'export default GeneratedComponent;',+ ].join('\n');+ assert.equal(hasDefaultExport(code), true);+ assert.equal(hasUnbalancedBrackets(code), false);+ assert.equal(endsMidStatement(code), false);+});++test('an arrow before a regex is not mistaken for a generic close', () => {+ const code = 'const pattern = count<limit ? () => /\\(/ : () => /none/;\nexport default function P(){ return null; }';+ assert.equal(hasDefaultExport(code), true);+ assert.equal(hasUnbalancedBrackets(code), false);+ assert.equal(endsMidStatement(code), false);+});++test('spaced type arguments after a type assertion are operands before division', () => {+ const code = [+ 'const total = 12, count = 2;',+ 'const label = `${total as NonNullable< number > / count}/month`;',+ 'const GeneratedComponent = () => label;',+ 'export default GeneratedComponent;',+ ].join('\n');+ assert.equal(hasDefaultExport(code), true);+ assert.equal(hasUnbalancedBrackets(code), false);+ assert.equal(endsMidStatement(code), false);+});++test('a complete multiline JSX self-closing tag at EOF is not mid-statement', () => {+ const code = 'export default () => <div\n title="Ready"\n/>';+ assert.equal(endsMidStatement(code), false);+});++test('a comment inside a template expression does not decide what a following slash is', () => {+ const exprEnd = (src) => scanTemplateExpressionEnd(src, src.indexOf('${') + 2);+ // The comment ends in `:`, which would read as a regex start — but `total / count` is a division.+ const division = 'const label = `${total // per row, then:\n / count} items`;';+ assert.equal(exprEnd(division), division.indexOf('} items'));+ // The comment ends in a plain word, which would read as division — but this is a regex, and the+ // `}` inside it must not close the expression.+ const regex = 'const s = `${\n // drop a trailing brace\n /\\}$/.test(v)\n}`;';+ assert.equal(exprEnd(regex), regex.lastIndexOf('}'));+ // Same with a block comment, and with no comment at all.+ const block = 'const s = `${ /* brace: */ /\\}$/.test(v) }`;';+ assert.equal(exprEnd(block), block.lastIndexOf('}'));+ assert.equal(exprEnd('`${a /* c */} tail`'), '`${a /* c */} tail`'.indexOf('} tail'), 'a `}` right after a comment still closes');+ assert.equal(exprEnd('`${a / b} tail`'), '`${a / b} tail`'.indexOf('} tail'));+ // ...and the page as a whole keeps its export.+ const page = `${division}\nexport default function Page() { return null; }\n`;+ assert.equal(hasDefaultExport(page), true);+ assert.equal(hasUnbalancedBrackets(page), false);+});++// A `${…}` body is code and is read by the full lexer, JSX included. A brace scanner that knew no JSX+// took the `/` of `</span>` for a regex that swallowed the closing `}`, and an apostrophe in JSX text+// for a string; either way the template never ended and the page's export was blanked with it.+test('JSX inside a template expression is read as JSX', () => {+ const exprEnd = (src) => scanTemplateExpressionEnd(src, src.indexOf('${') + 2);+ for (const expr of [+ '<span>Save</span>',+ "<p>it's here</p>",+ '<a href={u}>go</a>',+ 'items.map((i) => <li key={i}>{i}</li>)',+ '<Icon />',+ ]) {+ const line = `const x = \`\${${expr}}\`;`;+ assert.equal(exprEnd(line), line.lastIndexOf('}'), expr);+ const page = `${line}\nexport default function GeneratedComponent() { return 1; }\n`;+ assert.equal(hasDefaultExport(page), true, expr);+ assert.equal(hasUnbalancedBrackets(page), false, expr);+ }+ // Plain braces inside the expression nest; the expression ends at the brace that closes it.+ const obj = 'const s = `${fmt({ a: 1, b: { c: 2 } })} tail`;';+ assert.equal(exprEnd(obj), obj.indexOf('} tail'));+ // Output cut off inside the expression still terminates, without throwing.+ assert.equal(exprEnd('const x = `${<p>unfinished'), 'const x = `${<p>unfinished'.length);+});++// A keyword read back before a `/` or `<` means an expression starts — unless it is only a property+// NAME, or what precedes is a postfix operator ending an operand.+test('a keyword-named property or a postfix operator is an operand, not an expression start', () => {+ const at = (src) => expressionPosition(src, src.length);+ assert.equal(at('return '), true);+ assert.equal(at('x = typeof '), true);+ assert.equal(at('counts.new '), false, 'a property named `new`');+ assert.equal(at('counts?.in '), false, 'optional chaining reaches a property too');+ assert.equal(at('counts.\n new '), false, 'across a line break');+ assert.equal(at('[...new '), true, "a spread's `...new` is the keyword");+ assert.equal(at('closed! '), false, 'a non-null assertion ends the operand');+ assert.equal(at('return !'), true, 'a prefix `!` starts one');+ assert.equal(at('(!!'), true);+ assert.equal(at('i++ '), false);+ assert.equal(at('i-- '), false);+ assert.equal(at('a + '), true, 'a binary `+` does not end an operand');+ // A `)` ends an operand, unless it closes a statement head: then a statement starts after it.+ assert.equal(at('(a + b) '), false);+ assert.equal(at('counts.get(k)! '), false, 'a non-null assertion on a call result');+ assert.equal(at('if (bad) '), true);+ assert.equal(at('if (bad) !'), true, 'the `!` after an `if (…)` head is a prefix `!`');+ assert.equal(at('for (const x of xs) '), true);+ assert.equal(at('for await (const x of xs) '), true, 'the head keyword sits before `await`');+ assert.equal(at('while (next(a, (b))) '), true, 'nested parentheses in the head');+ assert.equal(at('obj.if(a) '), false, 'a method named `if` is not a statement head');+ assert.equal(at('"a" '), false, 'a string literal ends an operand: `"a" / 2` divides');+ assert.equal(at('x) '), false, 'a `)` with no `(` to match ends an operand');+ // End to end: each divides, so the page is complete; the prefix `!` still opens a regex.+ for (const body of [+ 'const pct = <Text>{counts.new / total}</Text>;',+ 'const pct = <Text>{closed! / total}</Text>;',+ 'const pct = `${Math.round((counts.new / total) * 100)}% new`;',+ 'const half = <Text>{i++ / 2}</Text>;',+ 'const noParen = (s) => !/\\(/.test(s);',+ 'if (bad) !/\\(/.test(s) || warn();',+ 'if (s) /\\(/.test(s) && warn();',+ 'async function run() { for await (const x of items) /\\(/.test(String(x)); }',+ 'const pct = counts.get("new")! / total;',+ ]) {+ const code = `export default function P() {\n ${body}\n return <div/>;\n}\n`;+ assert.equal(hasDefaultExport(code), true, body);+ assert.equal(hasUnbalancedBrackets(code), false, body);+ }+});++// A write cut off INSIDE its export statement matches the export pattern and balances, because the+// cut came before any bracket was opened. The export has to be complete.+test('hasDefaultExport requires the export itself to be complete', () => {+ const imp = 'import * as React from "react";\n';+ for (const [what, code] of [+ ['a function declaration', `${imp}export default function GeneratedComponent(props: P) {\n return <div/>;\n}\n`],+ ['a generator with generics, defaults and destructuring', `${imp}export default function* gen<T>(a = (1), { b }: { b: T }): Iterable<T> { yield b; }\n`],+ ['an anonymous function', 'export default function (props) { return null; }\n'],+ ['a class', 'export default class Page extends React.Component<P> { render() { return null; } }\n'],+ ['a declared name', 'const GeneratedComponent = () => null;\nexport default GeneratedComponent;\n'],+ ['a declared name at EOF, no semicolon', 'const GeneratedComponent = () => null;\nexport default GeneratedComponent'],+ ['a hoisted function declared after', 'export default Page;\nfunction Page() { return null; }\n'],+ ['an imported name', 'import Page from "./page";\nexport default Page;\n'],+ ['a destructured name', 'const { Page } = lib;\nexport default Page;\n'],+ ['a name with $', 'const $Page = () => null;\nexport default $Page;\n'],+ ['a name, then another statement', 'const A = 1;\nexport default A; const b = 2;\n'],+ ['an expression', 'const P = () => null;\nexport default React.memo(P);\n'],+ ['an async arrow', 'export default async (x) => { return x; };\n'],+ // A `{` where a TYPE is expected is not the body; the body comes after it.+ ['an object return type, then the body', 'export default function P(props): { id: string } {\n return { id: "x" };\n}\n'],+ ['a union of object types', 'export default function P(): { a: 1 } | { b: 2 } { return { a: 1 }; }\n'],+ ['a generic return type', 'export default async function P(): Promise<{ ok: boolean }> { return { ok: true }; }\n'],+ ['a function-type return', 'export default function P(): () => { c: 1 } { return () => ({ c: 1 }); }\n'],+ ['a type predicate', 'export default function isX(x: unknown): x is { d: 1 } { return !!x; }\n'],+ ['type parameters holding a function type', 'export default function P<T extends (a: string) => void>(cb: T) { cb("x"); }\n'],+ ['the body brace on its own line', 'export default function P(props)\n{\n return null;\n}\n'],+ ['a class with an object type argument', 'export default class Foo extends React.Component<{ id: string }> { render() { return null; } }\n'],+ ['a class extending a call', 'export default class Foo extends mixin({ a: 1 }) { }\n'],+ ['an abstract class', 'export default abstract class Foo { }\n'],+ ['an async arrow with a bare parameter', 'export default async x => x;\n'],+ ['a name that is also a modifier', 'const async = () => null;\nexport default async;\n'],+ ['a renamed import', 'import { X as Page } from "./x";\nexport default Page;\n'],+ ['a namespace import', 'import * as Page from "./x";\nexport default Page;\n'],+ ['a destructured key alias', 'const { a: Page } = lib;\nexport default Page;\n'],+ ['an array destructuring', 'const [Page] = list;\nexport default Page;\n'],+ ['a generator declared with the star on its name', 'function *Page() { yield 1; }\nexport default Page;\n'],+ // A later declarator of a list, even past a comma inside type arguments.+ ['a later declarator', 'const Header = () => null, GeneratedComponent = () => null;\nexport default GeneratedComponent;\n'],+ ['a later declarator with a type', 'let count = 0, GeneratedComponent: React.FC = () => null;\nexport default GeneratedComponent;\n'],+ ['a declarator after type arguments', 'const cache = new Map<string, number>(), Page = () => null;\nexport default Page;\n'],+ ['a bare let declarator', 'let count = 0, Page;\nPage = () => null;\nexport default Page;\n'],+ ['a definite-assignment declarator', 'let count = 0, Page!: React.FC;\nPage = () => null;\nexport default Page;\n'],+ ['a pattern as a later declarator', 'const a = 1, { Page } = lib;\nexport default Page;\n'],+ ['an expression ending in a type assertion', 'const P = () => null;\nexport default P as React.FC;\n'],+ ['a parenthesized function expression at the end', 'export default (function P() { return null; })'],+ ['a parenthesized typed function expression at the end', 'export default (function P(): void { })'],+ ['a parenthesized name at the end', 'function GeneratedComponent() { return 1; }\nexport default (GeneratedComponent)'],+ ['a parenthesized async arrow at the end', 'export default (async (x) => x)'],+ ['a parenthesized ternary at the end', 'const A = 1, B = 2;\nexport default (ok ? A : B)'],+ ['a parenthesized object at the end', 'export default ({ a: 1 })'],+ ['a parenthesized arrow with a return type at the end', 'export default ((props: P): JSX.Element => <Page {...props} />)'],+ ['a typed arrow export', 'export default (props: P): JSX.Element => <Page {...props} />;\n'],+ ['an untyped arrow export with a return type', 'export default (props): JSX.Element => <Page {...props} />;\n'],+ ['a ternary after a leading group', 'const a = 1, b = 2, c = 3;\nexport default (a) ? b : c'],+ ['a spread inside a call in the group', 'const f = (...x) => x, args = [];\nexport default (f(...args))'],+ ['an arrow with its body', 'export default (props) => null;\n'],+ ['an array pattern inside an object pattern', 'const { a: [Page] } = lib;\nexport default Page;\n'],+ // A member chain followed by a line break is a complete statement (a cut would have removed it).+ ['a member chain on its own line', 'import * as React from "react";\nexport default React.memo\n'],+ ['a syntactically complete member chain at EOF (documented cut limit)', 'import * as React from "react";\nconst Inner = () => null;\nexport default React.memo'],+ ['a syntactically complete partial member name at EOF (documented cut limit)', 'import * as React from "react";\nconst Inner = () => null;\nexport default React.mem'],+ ['a member chain at EOF', 'const pages = { Home: () => null };\nexport default pages.Home'],+ ['an imported namespace member chain at EOF', 'import * as UI from "@fluentui/react-components";\nexport default UI.Spinner'],+ ['a typed object member chain at EOF', 'const pages: Record<string, () => null> = { Home: () => null };\nexport default pages.Home'],+ ['a return type naming a property like a statement word', 'export default function P(): Schema.module { return null as any; }\n'],+ // Overload signatures come before the body; any complete `export default` will do.+ ['overloads', 'export default function f(x: string): string;\nexport default function f(x: any) { return x; }\n'],+ // Identifiers may be non-ASCII.+ ['a non-ASCII function name', 'export default function Página(props) { return null; }\n'],+ ['a non-ASCII exported name', 'const Página = () => null;\nexport default Página;\n'],+ ['an exported name starting non-ASCII', 'const Ñame = () => null;\nexport default Ñame;\n'],+ ]) {+ assert.equal(hasDefaultExport(code), true, what);+ }+ for (const [what, code] of [+ ['cut after the parameter list', `${imp}export default function GeneratedComponent(props: P)`],+ ['cut after a return type', `${imp}export default function GeneratedComponent(props: P): JSX.Element`],+ ['cut after an object return type', `${imp}export default function GeneratedComponent(props): { id: string }`],+ ['cut after a union return type', `${imp}export default function P(): { a: 1 } | { b: 2 }`],+ ['cut after the type parameters', `${imp}export default function P<T extends { id: string }>`],+ ['cut inside the type parameters', `${imp}export default function P<T`],+ ['cut after the name', `${imp}export default function GeneratedComponent`],+ ['cut inside the keyword', `${imp}export default func`],+ ['cut in a class header', `${imp}export default class Page extends React.Component<P>`],+ ['cut after a class type argument', `${imp}export default class Foo extends React.Component<{ id: string }>`],+ ['a header followed by another statement', `${imp}export default function GeneratedComponent()\nconst x = { a: 1 };`],+ ['a header followed by an if', `${imp}export default function GeneratedComponent()\nif (true) { return 1; }`],+ ['a header followed by a try', `${imp}export default function GeneratedComponent()\ntry { run(); } catch (e) { log(e); }`],+ ['a header followed by a with', `${imp}export default function GeneratedComponent()\nwith (obj) { return 1; }`],+ ['a header followed by an interface', `${imp}export default function GeneratedComponent()\ninterface Foo { a: number }`],+ ['a header followed by an enum', `${imp}export default function GeneratedComponent()\nenum Foo { A }`],+ ['a header followed by a namespace', `${imp}export default function GeneratedComponent()\nnamespace Foo { export const x = 1; }`],+ ['a header followed by a module', `${imp}export default function GeneratedComponent()\nmodule Foo { }`],+ ['a header followed by a declare', `${imp}export default function GeneratedComponent()\ndeclare const x: number;`],+ ['cut in an abstract class header', `${imp}export default abstract class Foo`],+ ['cut inside the keyword after abstract', `${imp}export default abstract clas`],+ ['cut right after async', `${imp}export default async`],+ ['cut inside the keyword after async', `${imp}export default async functi`],+ ['cut at an arrow', `${imp}export default (props) =>`],+ ['cut at an async arrow', `${imp}export default async (x) =>`],+ ['only an overload signature', 'export default function f(x: string): string;\nexport default function f(x: any)'],+ ['cut mid-name', 'const GeneratedComponent = () => null;\nexport default GeneratedComp'],+ ['a name the module never has', 'export default Page;\n'],+ ['a name only a string mentions', 'const s = "Page";\nexport default Page;\n'],+ // Mentioned, but never bound at module level.+ ['cut to the `as` of an import', 'import * as React from "react";\nexport default as'],+ ['a name only a parameter binds', 'const f = (a) => a.id;\nexport default a'],+ ['a name only a property carries', 'const o = { Page: 1 };\nexport default Page;\n'],+ ['a name that is only a destructuring key', 'const { Page: other } = lib;\nexport default Page;\n'],+ ['a name renamed away on import', 'import { Page as Other } from "./x";\nexport default Page;\n'],+ ['a name inside a destructuring that never closes', 'const { Page\nexport default Page;\n'],+ ['the `as` of a renamed import', 'import { Button as FluentButton } from "@fluentui/react-components";\nexport default as'],+ ['the `type` keyword of an import', 'import { type Foo } from "./x";\nexport default type'],+ ['a name only an array literal holds', 'const list = [a, Page];\nexport default Page;\n'],+ ['a const declarator with no initializer', 'const Header = 1, as\nexport default as'],+ ['a computed destructuring key', 'const { [GeneratedComponent]: x } = obj;\nexport default GeneratedComponent;\n'],+ // An expression that stops at a token needing more.+ ['cut after a dot', 'import * as React from "react";\nexport default React.'],+ ['cut after an optional dot', 'import * as React from "react";\nexport default React?.'],+ ['cut after a member dot at EOF', 'const pages = { Home: () => null };\nexport default pages.'],+ ['cut after an optional member dot at EOF', 'const pages = { Home: () => null };\nexport default pages?.'],+ ['cut after `as`', 'const P = () => null;\nexport default P as'],+ ['cut after `as` and a namespace', 'const P = () => null;\nexport default P as React.'],+ ['cut after `satisfies`', 'const P = () => null;\nexport default P satisfies'],+ ['cut after `?`', 'const P = () => null;\nexport default ok ?'],+ ['cut after `&&`', 'const P = () => null;\nexport default ok &&'],+ // An arrow cut off after parameters that cannot be an expression.+ ['cut after empty arrow parameters', 'export default ()'],+ ['cut after typed arrow parameters', 'export default (props: { a: string })'],+ ['cut after optional typed arrow parameters', 'export default (props?: P)'],+ ['cut after spread arrow parameters', 'export default (...args)'],+ ['cut before the arrow of a typed arrow', 'export default (props: P): JSX.Element'],+ ['cut before the arrow of an untyped arrow with a return type', 'export default (props): JSX.Element'],+ ['cut before the arrow of a destructuring arrow with a return type', 'export default ({ id }): JSX.Element'],+ ['cut after parameters with a later rest parameter', 'export default (a, ...rest)'],+ // Not a legal arrow: no line break may come between `async` and its parameters (a SyntaxError).+ ['async, a line break, then an arrow', 'export default async\n(x) => x;\n'],+ ]) {+ assert.equal(hasDefaultExport(code), false, what);+ }+});++test('endsMidStatement distinguishes dangling operators from postfix and JSX or regex closers', () => {+ for (const [what, code] of [+ ['relational greater-than needs a right operand', 'const count = 1;\nexport default () => count >'],+ ['division slash needs a right operand', 'const count = 1;\nexport default () => count /'],+ ['JSX followed by dangling division slash needs a right operand', 'export default () => <div>Hi</div> /'],+ ['prefix bang needs its operand', 'const count = 1;\nexport default () => !'],+ ]) {+ assert.equal(endsMidStatement(code), true, what);+ }+ for (const [what, code] of [+ ['a JSX tag can end with >', 'export default () => <div />'],+ ['a regex literal can end with /', 'const re = /a+/;\nexport default re'],+ ['a postfix non-null assertion can end with !', 'const count = 1;\nexport default count!'],+ ]) {+ assert.equal(endsMidStatement(code), false, what);+ }+});++test('findElisionMarker treats any bare ellipsis line as elision, even parser-valid multiline spread', () => {+ // Documented limit: without a full parser, a line containing only `...` can be either a legal+ // multiline spread/rest or an elided block. The gate fails closed; generators should write+ // `...rows` on one line instead.+ for (const [what, code] of [+ ['multiline array spread', [+ 'const rows = [1, 2];',+ 'const copy = [',+ ' ...',+ ' rows',+ '];',+ 'const GeneratedComponent = () => copy.length ? null : null;',+ 'export default GeneratedComponent;',+ ].join('\n')],+ ['multiline object spread', 'const base = { title: "Ready" };\nconst copy = {\n ...\n base\n};\nconst GeneratedComponent = () => null;\nexport default GeneratedComponent;'],+ ['multiline call spread', 'const rows = [1, 2];\ncollect<number>(\n ...\n rows\n);\nconst GeneratedComponent = () => null;\nexport default GeneratedComponent;'],+ ['multiline optional call spread', 'const rows = [1, 2];\ncollect?.(\n ...\n rows\n);\nconst GeneratedComponent = () => null;\nexport default GeneratedComponent;'],+ ['multiline non-null call spread', 'const rows = [1, 2];\ncollect!(\n ...\n rows\n);\nconst GeneratedComponent = () => null;\nexport default GeneratedComponent;'],+ ['rest-parameter arrow with return type', 'const f = (\n ...\n args\n): number => args.length;\nconst GeneratedComponent = () => null;\nexport default GeneratedComponent;'],+ ['ternary object spread', 'const copy = ready ? { a: 1,\n ...\n base\n} : {};\nconst GeneratedComponent = () => null;\nexport default GeneratedComponent;'],+ ['case block elision', 'switch (kind) {\n case 1: {\n ...\n renderRows();\n }\n}\nconst GeneratedComponent = () => null;\nexport default GeneratedComponent;'],+ ['array ternary elision', 'const rows = [ready ?\n ...\n rows : []];\nconst GeneratedComponent = () => null;\nexport default GeneratedComponent;'],+ ['executable template elision', [+ 'const GeneratedComponent = () => {',+ ' const title = `${(() => {',+ ' ...',+ ' })()}`;',+ ' return null;',+ '};',+ 'export default GeneratedComponent;',+ ].join('\n')],+ ]) {+ assert.match(findElisionMarker(code) || '', /bare `\.\.\.` line/, what);+ }+ assert.equal(findElisionMarker('const { a, ...rest } = o;\nexport default rest;'), null, 'same-line object rest remains ordinary code');+ assert.equal(findElisionMarker('const rows = [...items];\nexport default rows;'), null, 'same-line array spread remains ordinary code');+});++test('TypeScript parser oracle documents lexer review snippets and adversarial neighbours', (t) => {+ const oracle = loadTypescriptOracle();+ if (!oracle) {+ t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');+ return;+ }+ const valid = {+ 'multiline object spread after {': [+ 'const base = { title: "Ready" };',+ 'const copy = {',+ ' ...',+ ' base',+ '};',+ 'const GeneratedComponent = () => null;',+ 'export default GeneratedComponent;',+ ].join('\n'),+ 'generic instantiation default export at EOF': 'function Page<T>() { return null; }\nexport default Page<string>',+ 'type alias with nested type arguments at EOF': 'const GeneratedComponent = () => null;\nexport default GeneratedComponent;\ntype Rows = Record<string, Array<number>>',+ 'multiline cast type arguments before division in a template': [+ 'const total = 12, count = 2;',+ 'const label = `${total as NonNullable<',+ ' number',+ '> / count}/month`;',+ 'const GeneratedComponent = () => null;',+ 'export default GeneratedComponent;',+ ].join('\n'),+ 'function type inside type arguments before division in a template': 'const total = 12, count = 2;\nconst label = `${total as ReturnType<() => number> / count}/month`;\nconst GeneratedComponent = () => null;\nexport default GeneratedComponent;',+ 'self-closing JSX callback at EOF': 'import { Input } from "@fluentui/react-components";\nexport default () => <Input onChange={() => console.log("changed")} />',+ 'TSX generic arrow with comma': 'const f = <T,>(x: T) => x;\nexport default f;',+ 'relational chain a < b > c': 'const x = a < b > c;\nexport default x;',+ 'nested type arguments before division': 'const total = 12, count = 2;\nconst label = `${total as Record<string, Array<number>> / count}/month`;\nexport default label;',+ 'regex after statement-head paren': 'const value = 1;\nif (ready) /x/.test(value);\nexport default value;',+ 'regex after return keyword': 'function f(){ return /x/; }\nexport default f;',+ 'call spread split across lines': 'const y = fn(\n ...\n args\n);\nexport default y;',+ 'array spread split across lines': 'const y = [\n ...\n rows\n];\nexport default y;',+ 'arrow rest params': 'const f = (...args) => args.length;\nexport default f;',+ 'object rest destructuring': 'const { a, ...rest } = o;\nexport default rest;',+ 'non-null assertion at EOF': 'const x = y!;\nexport default x!',+ 'non-null assertion before division at EOF': 'const z = x! / y;\nexport default z',+ 'self-closing JSX with relational attribute at EOF': 'const x = 2;\nexport default () => <A b={x > 1} />',+ 'self-closing JSX with block callback at EOF': 'export default () => <A b={() => { console.log("x"); }} />',+ };+ for (const [label, code] of Object.entries(valid)) assertTsParses(oracle, code, label);+ assertTsRejects(oracle, 'const GeneratedComponent = () => (\n ...\n renderRows()\n);\nexport default GeneratedComponent;', /Expression expected|Declaration or statement expected/, 'grouping parens do not allow spread');+ assertTsRejects(oracle, 'export default function GeneratedComponent() {\n ...\n renderRows();\n return null;\n}', /Declaration or statement expected/, 'block elision is not TypeScript');+ assertTsRejects(oracle, 'const x = a >', /Expression expected/, 'dangling relational greater-than is not TypeScript');+});++test('navigation regex after relational greater-than remains visible', () => {+ const code = 'const marker = `${lo<hi && count > /}/.source.length ? Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_details" }) : ""}`;';+ assert.deepEqual(navReferencedKeys(code), ['details']);+});++// A cast's type may be one constituent of an intersection or union, so the check for "type arguments in a cast"+// walks back over the others to the `as`: missing it read `/ count}/` as a regex, and the page lost its default+// export. And angle brackets around an expression operator are comparisons even after a cast — pairing them as type+// arguments hid a navigation call. Every expectation matches TypeScript's parser.+test('a cast\'s type arguments reach its `as` or `satisfies` through unions, intersections and conditional types, and never span an expression operator', () => {+ const brand = 'type Brand<T> = { readonly __brand: T };\nconst total = 12, count = 2;\n';+ const complete = {+ 'intersection cast before division': `${brand}const label = \`\${total as number & Brand<"USD"> / count}/month\`;\nexport default () => <p>{label}</p>;`,+ 'union cast with a qualified name before division': 'namespace B { export type C<D> = D; }\nconst value = 4, n = 2;\nconst v = `${value as string | B.C<number> / n}/month`;\nexport default () => <p>{v}</p>;',+ 'a qualified constituent before the name': 'namespace B { export type C = number; }\ntype Z<Q> = Q;\nconst value = 4, n = 2;\nconst v = `${value as B.C | Z<number> / n}/month`;\nexport default () => <p>{v}</p>;',+ };+ for (const [label, code] of Object.entries(complete)) {+ assert.equal(hasDefaultExport(code), true, label);+ assert.equal(hasUnbalancedBrackets(code), false, label);+ assert.equal(endsMidStatement(code), false, label);+ }+ assert.equal(endsMidStatement(`${brand}export default () => total as number & Brand<"USD"> / count /`), true,+ 'a division cut after its slash is still dangling');+ const nav = 'const lo = 0, hi = 2, count = 3;\nconst marker = `${lo as number < hi && count > /}/.source.length ? Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_details" }) : ""}`;\nexport default function Page() { return null; }';+ assert.deepEqual(navReferencedKeys(nav), ['details'], 'a primitive takes no type arguments, and `&&` is no type operator');+ // Without the `&&`, only the primitive rule tells the comparison apart. TypeScript reads `lo as number` and two+ // comparisons around the regex `/}/`; inside a template substitution the `/` was read as a division, and its `}`+ // closed the substitution over the navigation call.+ const primitive = 'const lo = 0, hi = 2;\nconst marker = `${lo as number < hi > /}/.source.length ? Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_details" }) : ""}`;\nexport default function Page() { return null; }';+ assert.deepEqual(navReferencedKeys(primitive), ['details'], '`number` takes no type arguments');+ // A property's `:` reads like an annotation, so only the operator rule tells `lo < hi && count >` from type+ // arguments there. TypeScript reads two comparisons around the regex `/}/`.+ const property = 'const lo = 0, hi = 2, count = 3, s = "";\nconst o = { ok: lo < hi && count > /}/.test(s) };\nexport default function Page() { return null; }';+ assert.equal(hasDefaultExport(property), true);+ assert.equal(hasUnbalancedBrackets(property), false);+ assert.equal(endsMidStatement(property), false);+ const propertyNav = 'const lo = 0, hi = 2, count = 3;\nconst marker = `${({ ok: lo < hi && count > /}/.source.length }).ok ? Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_details" }) : ""}`;\nexport default function Page() { return null; }';+ assert.deepEqual(navReferencedKeys(propertyNav), ['details']);+ // `=` (a type parameter's default) and `+` (a mapped-type modifier) are type syntax too, so only `&&`, `||` and+ // `??` end a type-argument match; a string-literal constituent is stepped over; and the walk has no count limit.+ const d = 'const total = 12, count = 2;\n';+ const union = Array.from({ length: 17 }, (_, i) => `T${i}`);+ for (const [label, code] of Object.entries({+ 'a type parameter default in a cast': `${d}const label = \`\${total as ReturnType<<T = unknown>(x: T) => number> / count}/month\`;\nexport default () => <p>{label}</p>;`,+ 'a mapped-type modifier in a cast': `${d}const label = \`\${total as ReturnType<(x: { +readonly [K in "v"]: number }) => number> / count}/month\`;\nexport default () => <p>{label}</p>;`,+ 'eighteen union constituents': `${union.map((n) => `type ${n} = number;`).join('\n')}\ntype Z<Q> = Q;\n${d}const v = \`\${total as ${union.join(' | ')} | Z<number> / count}/month\`;\nexport default () => <p>{v}</p>;`,+ })) {+ assert.equal(hasDefaultExport(code), true, label);+ assert.equal(endsMidStatement(code), false, label);+ }+ assert.equal(endsMidStatement(`${d}export default () => total as ReturnType<<T = unknown>(x: T) => number> / count /`), true);+ assert.equal(endsMidStatement(`${d}export default () => total satisfies "n/a" | NonNullable<number> / count /`), true);+ assert.equal(findElisionMarker(`${d}export default function Page() {\n const avg = total satisfies "n/a" | NonNullable<number> / count; // TODO: render chart\n return null;\n}`),+ 'a TODO/FIXME comment', 'the comment after a division is a comment, not a regex');+ // `+`, `:` and the like are an expression's at the outer level of a would-be type-argument span. Taking them for type+ // syntax paired `start < anchor + padding` in one property with `end > /}/` in the next, across the `,` and the+ // `:` between, and the page read as unbalanced.+ const siblings = 'const start = 1, anchor = 4, padding = 1, end = 9;\nconst text = "value }";\nconst bounds = {\n startsBefore: start < anchor + padding,\n endsAfter: end > /}/.exec(text)!.index,\n};\nexport default () => <p>{String(bounds.endsAfter)}</p>;';+ assert.equal(hasUnbalancedBrackets(siblings), false);+ assert.equal(endsMidStatement(siblings), false);+ const siblingsNav = 'const start = 1, anchor = 4, end = 9;\nconst text = "value }";\nconst marker = `${({ a: start < anchor, b: end > /}/.exec(text)!.index }).b ? Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_details" }) : ""}`;\nexport default () => null;';+ assert.deepEqual(navReferencedKeys(siblingsNav), ['details']);+ // A `<` inside a group the `>` is outside of closes nothing there: `({ a: lo < hi }).a > /}/` compares twice,+ // although the `<` follows a property's `:`.+ const grouped = 'const lo = 0, hi = 2;\nconst marker = `${({ a: lo < hi }).a > /}/.source.length ? Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_details" }) : ""}`;\nexport default () => null;';+ assert.deepEqual(navReferencedKeys(grouped), ['details']);+ // Only a cast gives type-argument context. A `:` was taken for an annotation's, but a division never follows an+ // annotation's type, and each `:` matched was a ternary's, a property's or a case clause's.+ const ternary = 'const skipStart = false, start = 1, anchor = 4, padding = 1, end = 9;\nconst text = "value }";\nconst checks = [\n skipStart ? true : start < Math.max(anchor + padding, 0),\n end > /}/.exec(text)!.index,\n];\nexport default () => <p>{checks.every(Boolean) ? "match" : "no match"}</p>;';+ assert.equal(hasUnbalancedBrackets(ternary), false);+ assert.equal(endsMidStatement(ternary), false);+ const ternaryNav = 'const skip = false, start = 1, anchor = 4, end = 9;\nconst text = "value }";\nconst marker = `${[skip ? true : start < Math.max(anchor, 0), end > /}/.exec(text)!.index][1] ? Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_details" }) : ""}`;\nexport default () => null;';+ assert.deepEqual(navReferencedKeys(ternaryNav), ['details']);+ const callArgs = 'const f = (a: boolean, b: boolean) => a && b;\nconst start = 1, anchor = 4, end = 9, text = "v }";\nconst r = f(start < Math.max(anchor, 0), end > /}/.exec(text)!.index);\nexport default () => <p>{String(r)}</p>;';+ assert.equal(hasUnbalancedBrackets(callArgs), false);+ // A conditional type's `:` at the outer level of a cast's type arguments is type syntax.+ const conditional = `${d}const label = \`\${total as ReturnType<() => number extends number ? number : never> / count}\`;\nexport default () => null;`;+ assert.equal(hasDefaultExport(conditional), true);+ assert.equal(endsMidStatement(conditional), false);+ // TypeScript attaches type arguments only to a plain type name on the same line as the `<`. After an indexed type,+ // a literal, or a line break, the `<` is a comparison.+ const cmp = 'const low = 1, high = 4, count = 9, text = "value }";\n';+ for (const [label, code] of Object.entries({+ 'an indexed type before `<`': `type Row = { qty: number };\ntype Key = "qty";\n${cmp}const allowed = low as Row[Key] < high && count > /}/.exec(text)!.index;\nexport default () => <p>{String(allowed)}</p>;`,+ 'a literal type before `<`': `${cmp}const allowed = low as 0 | 1 < high && count > /}/.exec(text)!.index;\nexport default () => <p>{String(allowed)}</p>;`,+ 'a line break before `<`': `type Count = number;\n${cmp}const allowed = low as Count\n < high && count > /}/.exec(text)!.index;\nexport default () => <p>{String(allowed)}</p>;`,+ 'a CRLF line break before `<`': `type Count = number;\r\n${cmp.replace('\n', '\r\n')}const allowed = low as Count\r\n < high && count > /}/.exec(text)!.index;\r\nexport default () => <p>{String(allowed)}</p>;`,+ })) {+ assert.equal(hasUnbalancedBrackets(code), false, label);+ assert.equal(endsMidStatement(code), false, label);+ }+ assert.deepEqual(navReferencedKeys(`type Row = { qty: number };\ntype Key = "qty";\n${cmp}const m = \`\${low as Row[Key] < high && count > /}/.exec(text)!.index ? Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_details" }) : ""}\`;\nexport default () => null;`), ['details']);+ // An indexed type is still a constituent before the head: `Row[Key] & Brand<"x">` casts.+ const indexedEarlier = `type Row = { qty: number };\ntype Key = "qty";\ntype Brand<T> = { __b: T };\n${d}const label = \`\${total as Row[Key] & Brand<"x"> / count}/month\`;\nexport default () => <p>{label}</p>;`;+ assert.equal(endsMidStatement(indexedEarlier), false);+ assert.equal(hasDefaultExport(indexedEarlier), true);+ // A cast whose type is itself conditional: the walk steps back over `extends … ? … :` to the `as`.+ const direct = `type Value = number | undefined;\n${d}const label = \`\${total as Value extends undefined ? 0 : NonNullable<Value> / count}/month\`;\nexport default () => <p>{label}</p>;`;+ assert.equal(hasDefaultExport(direct), true);+ assert.equal(endsMidStatement(direct), false);+ assert.equal(endsMidStatement(`type Value = number | undefined;\n${d}export default () => total as Value extends undefined ? 0 : NonNullable<Value> / count /`), true);+ // Each part of the conditional may be a union: the true branch, the constraint, the checked type.+ const vd = `type Value = number | undefined;\n${d}`;+ for (const [label, code] of Object.entries({+ 'a union true branch': `${vd}const label = \`\${total as Value extends undefined ? 0 | 1 : NonNullable<Value> / count}/month\`;\nexport default () => <p>{label}</p>;`,+ 'a union constraint': `${vd}const label = \`\${total as Value extends string | undefined ? 0 : NonNullable<Value> / count}/month\`;\nexport default () => <p>{label}</p>;`,+ 'a union checked type': `${vd}const label = \`\${total as number | Value extends undefined ? 0 : NonNullable<Value> / count}/month\`;\nexport default () => <p>{label}</p>;`,+ })) {+ assert.equal(hasDefaultExport(code), true, label);+ assert.equal(endsMidStatement(code), false, label);+ }+ assert.equal(endsMidStatement(`${vd}export default () => total as Value extends undefined ? 0 | 1 : NonNullable<Value> / count /`), true);+ assert.deepEqual(navReferencedKeys(`${vd}const m = \`\${total as Value extends undefined ? 0 | 1 : NonNullable<Value> / count / 2 ? Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_details" }) : ""}\`;\nexport default () => null;`), ['details']);+ // A negative literal keeps its sign, and every part may lead with its operator: right after `as` or `satisfies`, the+ // checked type, the constraint after `extends`, and either branch. A false branch may chain another conditional.+ const parts = {+ 'a signed literal branch': 'Value extends undefined ? -1 | 0 : NonNullable<Value>',+ 'a leading-union true branch': 'Value extends undefined ? | 0 | 1 : NonNullable<Value>',+ 'a leading-union false branch': 'Value extends undefined ? 0 : | 1 | NonNullable<Value>',+ 'a leading-intersection false branch': 'Value extends undefined ? 0 : & NonNullable<Value>',+ 'a leading-union constraint': 'Value extends | undefined | null ? 0 : NonNullable<Value>',+ 'a leading-union checked type': '| Value extends undefined ? 0 : NonNullable<Value>',+ 'a conditional chained in the false branch': 'Value extends undefined ? 0 : Value extends null ? 1 : NonNullable<Value>',+ };+ for (const [label, type] of Object.entries(parts)) {+ const code = `${vd}const label = \`\${total as ${type} / count}/month\`;\nexport default () => <p>{label}</p>;`;+ assert.equal(hasDefaultExport(code), true, label);+ assert.equal(endsMidStatement(code), false, label);+ assert.equal(endsMidStatement(`${vd}export default () => total as ${type} / count /`), true, `${label}, cut`);+ }+ for (const keyword of ['as', 'satisfies']) {+ const code = `type Z<Q> = Q;\n${vd}const label = \`\${total ${keyword} | number | Z<number> / count}/month\`;\nexport default () => null;`;+ assert.equal(hasDefaultExport(code), true, `a leading union after \`${keyword}\``);+ assert.equal(endsMidStatement(code), false, `a leading union after \`${keyword}\``);+ }+ // `as` and `satisfies` are contextual keywords, so each may name a type. With type arguments of its own, or before+ // `?`, `:` or `extends`, such a name is a constituent, never the cast keyword; so is one within a longer name+ // (`E.as`), and one inside an index (`Row[as | Key]`) is never reached.+ for (const [label, [alias, type]] of Object.entries({+ 'a generic named `satisfies`': ['type satisfies<T> = T;\n', 'satisfies<number> & NonNullable<Value>'],+ 'a generic named `as`': ['type as<T> = T;\n', 'as<number> | NonNullable<Value>'],+ 'a constraint named `satisfies`': ['type satisfies = undefined;\n', 'Value extends satisfies ? 0 : NonNullable<Value>'],+ 'a checked type named `as`': ['type as = number | undefined;\n', 'as extends undefined ? 0 : NonNullable<Value>'],+ 'a true branch named `as`': ['type as = 0;\n', 'Value extends undefined ? as : NonNullable<Value>'],+ })) {+ const code = `${alias}${vd}const label = \`\${total as ${type} / count}/month\`;\nexport default () => <p>{label}</p>;`;+ assert.equal(hasDefaultExport(code), true, label);+ assert.equal(endsMidStatement(code), false, label);+ assert.equal(endsMidStatement(`${alias}${vd}export default () => total as ${type} / count /`), true, `${label}, cut`);+ }+ // An index is stepped over whole, its brackets matched, so nothing inside one is read as part of the cast's type:+ // a string key, a second index, a nested one, or a union key holding a type named `as` anywhere in it.+ const row = 'type as = "price";\ntype Key = "qty";\ntype Keys = ["price"];\ntype Row = { price: number; qty: number; tax: number };\n';+ for (const [label, type] of Object.entries({+ 'a string index': 'Row["qty"] & NonNullable<Value>',+ 'a double index': 'Row["tax"]["toFixed"] & NonNullable<Value>',+ 'a nested index': 'Row[Keys[0] | Key] & NonNullable<Value>',+ 'an index led by a type named `as`': 'Row[as | Key] & NonNullable<Value>',+ 'an index holding a type named `as` in the middle': 'Row["tax" | as | Key] & NonNullable<Value>',+ })) {+ const code = `${row}${vd}const label = \`\${total as ${type} / count}/month\`;\nexport default () => <p>{label}</p>;`;+ assert.equal(hasDefaultExport(code), true, label);+ assert.equal(endsMidStatement(code), false, label);+ assert.equal(endsMidStatement(`${row}${vd}export default () => total as ${type} / count /`), true, `${label}, cut`);+ }+ // No cast at all: a type alias whose type holds a keyword-named type keeps the regex on the next line a regex.+ for (const [label, code] of Object.entries({+ 'a member named `as`': 'enum E { as, b }\ntype Z<Q> = Q;\ntype T = E.as | Z<number>\n/}/.test("a}") && console.log(1);\nexport default () => null;',+ 'an index led by a type named `as`': `${row}type Z<T> = T;\ntype Price = Row[as | Key] & Z<number>\n/}/.test("}");\nexport default () => <p>Ready</p>;`,+ 'an index holding a type named `as` in the middle': `${row}type Price = Row["tax" | as | Key] & NonNullable<number>\n/}/.test("}");\nexport default () => <p>Ready</p>;`,+ 'an index with a comment before `as`': `${row}type Price = Row[/* selected columns */ as | Key] & NonNullable<number>\n/}/.test("}");\nexport default () => <p>Ready</p>;`,+ 'a tuple led by a type named `as`': `${row}type Z<T> = T;\ntype Pair = [as | Key] & Z<number>\n/}/.test("}");\nexport default () => <p>Ready</p>;`,+ })) {+ assert.equal(hasUnbalancedBrackets(code), false, label);+ assert.equal(endsMidStatement(code), false, label);+ }+ // A leading operator decides nothing by itself: after `)` it is an expression's `|`, and the `/` starts a regex.+ const notCast = `${vd}const bits = (count) | total < count || count > /}/.exec("a}")!.index;\nexport default () => null;`;+ assert.equal(hasUnbalancedBrackets(notCast), false);+ assert.equal(endsMidStatement(notCast), false);+});++test('endsMidStatement treats non-JSX final type argument lists as documented incomplete tails', () => {+ // Documented limit: without a full parser, a final `>` can be a type-argument close or the end+ // of a relational expression. Only recorded JSX tag closes finish a file; type-argument tails need+ // a semicolon.+ const incomplete = {+ 'generic instantiation default export at EOF': 'function Page<T>() { return null; }\nexport default Page<string>',+ 'generic instantiation with trivia before type arguments': 'function Page<T>() { return null; }\nexport default Page /* c */ <string>',+ 'type alias with nested type arguments at EOF': 'const GeneratedComponent = () => null;\nexport default GeneratedComponent;\ntype Rows = Record<string, Array<number>>',+ 'type alias with object type argument at EOF': 'const GeneratedComponent = () => null;\nexport default GeneratedComponent;\ntype Rows = Array<{ id: string; label: string }>',+ 'generic-looking arrow expression at EOF': 'export default () => a<b + c>',+ 'cast type arguments at EOF': 'const v = [1];\nexport default v as unknown as Array<number>',+ 'satisfies type arguments at EOF': 'const counts = { a: 1 };\nexport default counts satisfies Record<string, number>',+ };+ for (const [label, code] of Object.entries(incomplete)) assert.equal(endsMidStatement(code), true, label);+ assert.equal(endsMidStatement('function Page<T>() { return null; }\nexport default Page<string>;'), false, 'semicolon makes the documented limit explicit');+ assert.equal(endsMidStatement('const GeneratedComponent = () => null;\nexport default GeneratedComponent;\ntype Rows = Array<{ id: string; label: string }>;'), false, 'semicolon makes a type alias complete');+ assert.equal(endsMidStatement('const x = a >'), true, 'dangling relational greater-than still needs a right operand');+ assert.equal(endsMidStatement('const x = a < b > c'), false, 'a complete relational chain is an operand');+});++test('cast and annotation type arguments still make a following slash division', () => {+ const complete = {+ 'cast type arguments before division in a template': 'const total = 12, count = 2;\nconst label = `${total as Record<string, Array<number>> / count}/month`;\nexport default label;',+ 'annotation type arguments before division': 'const total: Record<string, Array<number>> = {};\nconst label = total / count;\nexport default label;',+ 'non-null assertion at EOF': 'const x = y!;\nexport default x!',+ 'non-null assertion before division at EOF': 'const z = x! / y;\nexport default z',+ };+ for (const [label, code] of Object.entries(complete)) assert.equal(endsMidStatement(code), false, label);+});++test('template expression slash classification handles multiline and nested type arguments', () => {+ for (const [label, code] of Object.entries({+ 'multiline type arguments before division': [+ 'const total = 12, count = 2;',+ 'const label = `${total as NonNullable<',+ ' number',+ '> / count}/month`;',+ 'const GeneratedComponent = () => null;',+ 'export default GeneratedComponent;',+ ].join('\n'),+ 'function type arrow inside type arguments before division': 'const total = 12, count = 2;\nconst label = `${total as ReturnType<() => number> / count}/month`;\nconst GeneratedComponent = () => null;\nexport default GeneratedComponent;',+ 'regex after statement-head paren': 'const value = 1;\nif (ready) /x/.test(value);\nexport default value;',+ 'regex after return keyword': 'function f(){ return /x/; }\nexport default f;',+ })) {+ assert.equal(hasDefaultExport(code), true, label);+ assert.equal(hasUnbalancedBrackets(code), false, label);+ assert.equal(endsMidStatement(code), false, label);+ }+});++test('endsMidStatement accepts self-closing JSX EOF tags using recorded tag closes', () => {+ for (const [label, code] of Object.entries({+ 'callback attribute': 'import { Input } from "@fluentui/react-components";\nexport default () => <Input onChange={() => console.log("changed")} />',+ 'relational expression attribute': 'const x = 2;\nexport default () => <A b={x > 1} />',+ 'block callback attribute containing a semicolon': 'export default () => <A b={() => { console.log("x"); }} />',+ })) {+ assert.equal(hasDefaultExport(code), true, label);+ assert.equal(hasUnbalancedBrackets(code), false, label);+ assert.equal(endsMidStatement(code), false, label);+ }+});+test('every committed .tsx the repo ships is accepted (false-positive corpus)', () => {// A false positive here would block a real user mid-build, so this is the load-bearing test:// the samples the worker is told to copy, and every eval fixture artifact.diff --git a/plugins/model-apps/scripts/tests/supported-dependencies-docs.test.js b/plugins/model-apps/scripts/tests/supported-dependencies-docs.test.jsnew file mode 100644index 000000000..cd69abbc9--- /dev/null+++ b/plugins/model-apps/scripts/tests/supported-dependencies-docs.test.js@@ -0,0 +1,109 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');++const {+ RUNTIME_DEPENDENCIES,+ DEV_DEPENDENCIES,+ FEATURE_RUNTIME_KEYS,+ FEATURE_DEV_KEYS,+ buildDependencyMap,+ buildDevDependencyMap,+} = require('../lib/supported-dependencies.js');++const ROOT = path.join(__dirname, '..', '..');++function read(relPath) {+ return fs.readFileSync(path.join(ROOT, relPath), 'utf8');+}++function extractJsonObjectAfter(content, marker) {+ const start = content.indexOf(marker);+ assert.notEqual(start, -1, `missing marker ${marker}`);+ const open = content.indexOf('{', start);+ assert.notEqual(open, -1, `missing JSON object after ${marker}`);+ let depth = 0;+ let inString = false;+ let escape = false;+ for (let i = open; i < content.length; i += 1) {+ const ch = content[i];+ if (escape) {+ escape = false;+ continue;+ }+ if (ch === '\\') {+ escape = true;+ continue;+ }+ if (ch === '"') {+ inString = !inString;+ continue;+ }+ if (inString) continue;+ if (ch === '{') depth += 1;+ if (ch === '}') {+ depth -= 1;+ if (depth === 0) return JSON.parse(content.slice(open, i + 1));+ }+ }+ throw new Error(`unterminated JSON object after ${marker}`);+}++function extractPackageRows(content, heading) {+ const headingIndex = content.indexOf(`## ${heading}`);+ assert.notEqual(headingIndex, -1, `missing heading ${heading}`);+ const nextHeading = content.indexOf('\n## ', headingIndex + 1);+ const section = content.slice(headingIndex, nextHeading === -1 ? content.length : nextHeading);+ const rows = new Map();+ for (const line of section.split(/\r?\n/)) {+ const m = line.match(/^\|\s*`([^`]+)`\s*\|\s*`([^`]+)`\s*\|\s*([^|]+)\|/);+ if (!m) continue;+ rows.set(m[1], { version: m[2], confidence: m[3].trim() });+ }+ return rows;+}++function assertRowsMatchMap(rows, dependencyMap) {+ assert.deepEqual([...rows.keys()].sort(), Object.keys(dependencyMap).sort());+ for (const [name, meta] of Object.entries(dependencyMap)) {+ assert.equal(rows.get(name).version, meta.version, `${name} version`);+ assert.equal(rows.get(name).confidence, meta.confidence, `${name} confidence`);+ }+}++test('supported-dependencies.md exactly matches the dependency source of truth', () => {+ const doc = read('references/supported-dependencies.md');++ assertRowsMatchMap(extractPackageRows(doc, 'Runtime dependencies'), RUNTIME_DEPENDENCIES);+ assertRowsMatchMap(extractPackageRows(doc, 'Dev dependencies'), DEV_DEPENDENCIES);++ for (const [feature, runtimeKeys] of Object.entries(FEATURE_RUNTIME_KEYS)) {+ for (const dep of runtimeKeys) {+ assert.match(doc, new RegExp(String.raw`\|\s*\`${feature}\`\s*\|\s*\`${dep}\``), `${feature} runtime dependency`);+ }+ }+ for (const [feature, devKeys] of Object.entries(FEATURE_DEV_KEYS)) {+ for (const dep of devKeys) {+ assert.match(doc, new RegExp(String.raw`\|\s*\`${feature}\`[^\n]*\`${dep}\``), `${feature} dev dependency`);+ }+ }+});++test('rules.md generated package example matches the dependency source of truth', () => {+ const rules = read('references/rules.md');+ const dependencies = extractJsonObjectAfter(rules, '"dependencies"');+ const devDependencies = extractJsonObjectAfter(rules, '"devDependencies"');++ assert.deepEqual(dependencies, buildDependencyMap(['charts', 'datepicker', 'timepicker']));+ assert.deepEqual(devDependencies, buildDevDependencyMap(['charts', 'datepicker', 'timepicker']));+});++test('agent-facing dependency guidance points to the source of truth instead of listing versions', () => {+ const agent = read('agents/genpage-page-builder.md');+ assert.match(agent, /supported-dependencies\.md/);+ assert.doesNotMatch(agent, /"@fluentui\/react-icons"\s*:/);+ assert.doesNotMatch(agent, /"d3"\s*:/);+});diff --git a/plugins/model-apps/scripts/tests/validate-icon-imports.test.js b/plugins/model-apps/scripts/tests/validate-icon-imports.test.jsindex fd952e1b5..980205ef1 100644--- a/plugins/model-apps/scripts/tests/validate-icon-imports.test.js+++ b/plugins/model-apps/scripts/tests/validate-icon-imports.test.js@@ -200,6 +200,162 @@ test('file with no @fluentui/react-icons imports passes (exit 0)', () => {assert.equal(status, 0);});+test('namespace icon imports are blocked because member access cannot be verified safely (exit 2)', () => {+ const content = `import * as Icons from '@fluentui/react-icons';\n${GENPAGE_HEADER}\nconst x = <Icons.TotallyMadeUpIconRegular />;\n`;+ const fp = writeTemp(tmp, 'page.tsx', content);+ const { status, stderr } = runHook(payloadFor(fp, content));+ assert.equal(status, 2);+ assert.match(stderr, /namespace/);+ assert.match(stderr, /@fluentui\/react-icons/);+});++test('unsupported static icon imports are blocked at code-token boundaries and in combined clauses (exit 2)', () => {+ for (const [kind, line, expected] of [+ ['namespace', 'import React from "react"; import * as Icons from "@fluentui/react-icons";', /namespace/],+ ['default plus namespace', 'import DefaultIcon, * as Icons from "@fluentui/react-icons";', /default|namespace/],+ ['default plus named', 'import DefaultIcon, { AddRegular } from "@fluentui/react-icons";', /default/],+ ]) {+ const content = `${line}\n${GENPAGE_HEADER}\nconst x = Icons && DefaultIcon;\n`;+ const fp = writeTemp(tmp, 'page.tsx', content);+ const { status, stderr } = runHook(payloadFor(fp, content));+ assert.equal(status, 2, kind);+ assert.match(stderr, expected, kind);+ }+});++test('default icon imports are blocked because the verified list contains named exports only (exit 2)', () => {+ const content = `import Icons from '@fluentui/react-icons';\n${GENPAGE_HEADER}\nconst x = <Icons.AddRegular />;\n`;+ const fp = writeTemp(tmp, 'page.tsx', content);+ const { status, stderr } = runHook(payloadFor(fp, content));+ assert.equal(status, 2);+ assert.match(stderr, /default/);+ assert.match(stderr, /@fluentui\/react-icons/);+});++test('CommonJS icon imports are blocked because they bypass named import validation (exit 2)', () => {+ const content = `const Icons = require('@fluentui/react-icons');\n${GENPAGE_HEADER}\nconst x = <Icons.AddRegular />;\n`;+ const fp = writeTemp(tmp, 'page.tsx', content);+ const { status, stderr } = runHook(payloadFor(fp, content));+ assert.equal(status, 2);+ assert.match(stderr, /CommonJS/);+ assert.match(stderr, /@fluentui\/react-icons/);+});++// Member access through an inline require or a dynamic import reaches an icon without any import+// declaration at all, so these are matched wherever they appear.+test('require and dynamic import allow expressions derived from the icon module string (exit 0)', () => {+ for (const line of [+ 'const Icons = require("@fluentui/react-icons".replace("icons", "components"));',+ 'const Icons = await import("@fluentui/react-icons".replace("icons", "components"));',+ ]) {+ const content = `${GENPAGE_HEADER}\n${line}\n`;+ const fp = writeTemp(tmp, 'page.tsx', content);+ const { status, stderr } = runHook(payloadFor(fp, content));+ assert.equal(status, 0, `${line}\n${stderr}`);+ }+});++test('require and dynamic import block on the icon module argument before trailing commas or options (exit 2)', () => {+ for (const [kind, line] of [+ ['CommonJS', 'const Icons = require("@fluentui/react-icons",);'],+ ['dynamic import', 'const Icons = await import("@fluentui/react-icons",);'],+ ['dynamic import', 'const Icons = await import("@fluentui/react-icons", {});'],+ ]) {+ const content = `${GENPAGE_HEADER}\n${line}\n`;+ const fp = writeTemp(tmp, 'page.tsx', content);+ const { status, stderr } = runHook(payloadFor(fp, content));+ assert.equal(status, 2, `${kind}: ${line}`);+ assert.match(stderr, new RegExp(kind), kind);+ }+});++test('inline require and dynamic import() of the icon module are blocked too (exit 2)', () => {+ for (const [kind, line] of [+ ['CommonJS', "const x = React.createElement(require('@fluentui/react-icons').TotallyMadeUpIconRegular);"],+ ['dynamic import', "const Icons = await import(\"@fluentui/react-icons\");\nconst y = <Icons.TotallyMadeUpIconRegular />;"],+ ['dynamic import', 'const Icons = await import(`@fluentui/react-icons`);'],+ ['CommonJS', 'const Icons = require(`@fluentui/react-icons`);'],+ ]) {+ const content = `${GENPAGE_HEADER}\n${line}\n`;+ const fp = writeTemp(tmp, 'page.tsx', content);+ const { status, stderr } = runHook(payloadFor(fp, content));+ assert.equal(status, 2, kind);+ assert.match(stderr, new RegExp(kind), kind);+ }+ // CONTROL: other modules may still be required or imported dynamically.+ const content = `${GENPAGE_HEADER}\nconst lib = await import('./helpers');\nconst other = require('some-lib');\n`;+ const fp = writeTemp(tmp, 'page.tsx', content);+ assert.equal(runHook(payloadFor(fp, content)).status, 0);+});++// Only a keyword in code is an import: one quoted in help text, a template or a comment is data.+test('an icon import merely quoted in a string, template or comment does not block the write (exit 0)', () => {+ for (const line of [+ 'const help = "Never write require(\'@fluentui/react-icons\') in a page";',+ 'const tip = `Use named imports, not import("@fluentui/react-icons")`;',+ '/* import * as Icons from "@fluentui/react-icons"; */',+ 'const snippet = `\nimport * as Icons from "@fluentui/react-icons";\n`;',+ // …a NAMED import line quoted in a help template too: its icon name is data, not an import to verify.+ 'const help = `\nimport { TotallyMadeUpIconRegular } from "@fluentui/react-icons";\n`;',+ ]) {+ const content = `${GENPAGE_HEADER}\n${line}\n`;+ const fp = writeTemp(tmp, 'page.tsx', content);+ const { status, stderr } = runHook(payloadFor(fp, content));+ assert.equal(status, 0, `${line}\n${stderr}`);+ }+ // CONTROL: the same call as code inside a template's ${…} is executable, and still blocked.+ const content = `${GENPAGE_HEADER}\nconst x = \`\${require('@fluentui/react-icons').FakeRegular}\`;\n`;+ const fp = writeTemp(tmp, 'page.tsx', content);+ assert.equal(runHook(payloadFor(fp, content)).status, 2);+});++// A comment BETWEEN an import's tokens is still an import. The patterns run on a copy with comments+// blanked to spaces, so they match across one, and a `//` inside a string is not taken for one.+test('a comment inside an unsupported icon import does not get it past the hook (exit 2)', () => {+ for (const [kind, line] of [+ ['namespace', 'import * as /* every icon */ Icons from "@fluentui/react-icons";'],+ ['default', 'import Icons // all of them\n from "@fluentui/react-icons";'],+ ['CommonJS', 'const Icons = require(/* icons */ "@fluentui/react-icons");'],+ // A comment inside `${…}` is a comment too: the lexer reports it like any other.+ ['dynamic import', 'const s = `${(await import(/* lazy */ "@fluentui/react-icons")).X}`;'],+ ]) {+ const content = `${line}\n${GENPAGE_HEADER}`;+ const fp = writeTemp(tmp, 'page.tsx', content);+ const { status, stderr } = runHook(payloadFor(fp, content));+ assert.equal(status, 2, `${kind}: ${line}`);+ assert.match(stderr, new RegExp(kind), kind);+ }+ // CONTROL: a URL in a string is not a comment, and an ordinary page still passes.+ const content = `${GENPAGE_HEADER}\nconst docs = "https://contoso.example/icons";\n`;+ const fp = writeTemp(tmp, 'page.tsx', content);+ assert.equal(runHook(payloadFor(fp, content)).status, 0);+});++// Defence in depth: should the lexer ever throw, the hook falls back to comment-stripped matching and+// still blocks — it must not fail open. A `-r` preload swaps in a lexer that throws.+test('if the lexer throws, the hook falls back and still blocks an unsupported import (exit 2)', () => {+ const lexer = require.resolve('../lib/source-literals.js');+ const stub = path.join(tmp, 'throwing-lexer.js');+ fs.writeFileSync(stub, [+ `const lexer = ${JSON.stringify(lexer)};`,+ 'require(lexer);',+ "require.cache[lexer].exports = { ...require.cache[lexer].exports, blankNonCodePreservingTemplateExpressions() { throw new Error('lexer failure'); } };",+ ].join('\n'));+ const runWithBrokenLexer = (content) => {+ const fp = writeTemp(tmp, 'page.tsx', content);+ return spawnSync(process.execPath, ['-r', stub, HOOK], { input: JSON.stringify(payloadFor(fp, content)), encoding: 'utf8' });+ };+ const blocked = runWithBrokenLexer(`import * as Icons from '@fluentui/react-icons';\n${GENPAGE_HEADER}`);+ assert.equal(blocked.status, 2, blocked.stderr);+ assert.match(blocked.stderr, /namespace/);+ // CONTROL: the fallback still ignores a commented-out import rather than blocking everything.+ const commented = runWithBrokenLexer(`/* import * as Icons from '@fluentui/react-icons'; */\n${GENPAGE_HEADER}`);+ assert.equal(commented.status, 0, commented.stderr);+ // …and still verifies a real NAMED import: an unverified icon is blocked without the lexer too.+ const named = runWithBrokenLexer(`import { TotallyMadeUpIconRegular } from '@fluentui/react-icons';\n${GENPAGE_HEADER}`);+ assert.equal(named.status, 2, named.stderr);+});+test('commented-out import (line comment) is not treated as a real import (exit 0)', () => {const content = `// import { TotallyMadeUpIconRegular } from '@fluentui/react-icons';\n${GENPAGE_HEADER}`;const fp = writeTemp(tmp, 'page.tsx', content);@@ -225,3 +381,20 @@ test('unparseable stdin does not block (exit 0)', () => {const res = spawnSync(process.execPath, [HOOK], { input: 'not json', encoding: 'utf8' });assert.equal(res.status, 0);});++// Corpus: every committed sample the page builder is pointed at must pass this hook. A sample is a+// pattern agents copy, so one importing an icon the hook rejects (a sized variant such as+// `CheckmarkCircle20Filled` once shipped) teaches the exact write the hook then blocks. A plain+// directory listing, not `git ls-files`: nothing transient is ever written to samples/, and the test+// must not skip itself outside a git checkout.+test('every committed sample page passes the icon hook', () => {+ const samples = path.join(__dirname, '..', '..', 'samples');+ const files = fs.readdirSync(samples).filter((f) => f.endsWith('.tsx'));+ assert.ok(files.length > 0, 'the corpus is not empty');+ for (const name of files) {+ const fp = path.join(samples, name);+ const content = fs.readFileSync(fp, 'utf8');+ const { status, stderr } = runHook(payloadFor(fp, content));+ assert.equal(status, 0, `samples/${name} is blocked by the hook:\n${stderr}`);+ }+});diff --git a/plugins/model-apps/scripts/write-page-plan.js b/plugins/model-apps/scripts/write-page-plan.jsindex de8451df8..bec512a3f 100644--- a/plugins/model-apps/scripts/write-page-plan.js+++ b/plugins/model-apps/scripts/write-page-plan.js@@ -8,14 +8,16 @@//// Usage:// node write-page-plan.js --spec @<working-dir>/app-spec.json --working-dir <dir>-// [--env <orgUrl>] [--app <label>] [--languages "English (1033) only"] [--out <path>]+// [--env <orgUrl>] [--app <label>] [--languages "English (1033) only"]//// The default output is `app-builder-page-plan.md`, NOT `genpage-plan.md`. Both skills derive their// working directory from a slug off the user's request, so the two can land on the same folder — and// `genpage-plan.md` is the filename standalone `/genpage` treats as its authoritative state. Writing// there would let a later `/genpage` run silently consume an app-builder plan, whose dialect differs// (`Mode: app-builder` + stable keys vs. no Mode + filename stems), producing wrong PAGEREF tokens.-// The worker is handed the plan PATH explicitly in its dispatch, so the name is free to differ.+// The worker is handed the plan PATH explicitly in its dispatch, so the name is free to differ. It is not+// configurable: an `--out` could name any file — the input `app-spec.json`, the page manifest, /genpage's+// own `genpage-plan.md` — and the plan would overwrite it, so the working directory alone decides the path.//// Output: { "ok": true, "planPath": "...", "pages": [{ "key", "file", "dataMode" }, ...] }// The `pages[]` echo is what Phase 1.5 iterates to dispatch one worker per page, so the CLI is the@@ -25,19 +27,20 @@ const fs = require('node:fs');const path = require('node:path');const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');const { migrateAppSpec } = require('./lib/app-spec.js');-const { buildPagePlan, pageKey, pageFile, pageDataMode, mdText } = require('./lib/page-plan.js');+const { buildPagePlan, pageKey, pageFile, planFile, pageDataMode, mdText } = require('./lib/page-plan.js');+const { pageFileProblems } = require('./lib/page-file-targets.js');function main() {const argv = process.argv.slice(2);const { positional, flags } = parseArgs(argv);const USAGE ='Usage: node scripts/write-page-plan.js --spec @<app-folder>/app-spec.json --working-dir <dir> '- + '[--env <orgUrl>] [--app <label>] [--languages <text>] [--out <path>]';+ + '[--env <orgUrl>] [--app <label>] [--languages <text>]';// Every flag here carries a value, so all of them go in needValue; a bare one would otherwise// reach path.resolve/readFile as a boolean.const flagError = validateFlags(argv, {- known: ['spec', 'working-dir', 'env', 'app', 'languages', 'out'],- needValue: ['spec', 'working-dir', 'env', 'app', 'languages', 'out'],+ known: ['spec', 'working-dir', 'env', 'app', 'languages'],+ needValue: ['spec', 'working-dir', 'env', 'app', 'languages'],});if (flagError) {process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);@@ -67,7 +70,7 @@ function main() {pluginRoot: path.resolve(__dirname, '..').replace(/\\/g, '/'),});- const planPath = flags.out ? path.resolve(flags.out) : path.join(absWorkingDir, 'app-builder-page-plan.md');+ const planPath = path.join(absWorkingDir, 'app-builder-page-plan.md');// Fail BEFORE writing if the plan names a sample that does not exist — the worker's Step 3 reads// `${PLUGIN_ROOT}/samples/<name>` and a missing file derails generation with a confusing error.@@ -79,6 +82,65 @@ function main() {return;}+ // The checks that need the disk — a link at a page path, a folder that links outside the working+ // directory, a page already there under another spelling — run HERE, where the working directory is+ // known: buildPagePlan is pure, so it applies only the lexical rules and collisions. /genpage runs the+ // same checks through check-page-files.js before its workers; this is /app-builder's, before Phase 1.5+ // dispatches any. Only the pages a worker will write are held to the whole rule — a built page is+ // written by nobody — but the built pages go along as `built`, in the plan's own spelling: a new page+ // must not reach one through a link or junction (`loop/home.tsx`, with `loop` pointing back here, IS+ // `home.tsx`), and only here is the working directory known to resolve that.+ // The working directory ITSELF must not be a link — the rule generate-page-manifest.js and the page-file+ // rule apply to it. Phase 0's `mkdir -p` succeeds silently on a link already at that path, and the plan+ // is written INTO the directory, so a planted link redirected the plan write whether or not any page was+ // left for a worker (the page-file rule refuses only the pages it is given). A linked ancestor is still+ // followed. A directory that is not there yet is created below.+ let linkedWorkingDir = false;+ try {+ const at = fs.lstatSync(absWorkingDir);+ linkedWorkingDir = at.isSymbolicLink();+ // Anything else that is not a folder — a file there — cannot hold the plan: refused before the write,+ // not left to throw EEXIST out of mkdir. generate-page-manifest.js applies the same rule.+ if (!linkedWorkingDir && !at.isDirectory()) {+ emitResult(false, new Error(`refusing to write the page plan into ${absWorkingDir}: it exists and is not a directory`));+ return;+ }+ } catch (e) {+ if (!(e && e.code === 'ENOENT')) {+ emitResult(false, new Error(`cannot inspect the working directory ${absWorkingDir} (${(e && e.code) || e}); fix its permissions or pass another one`));+ return;+ }+ }+ if (linkedWorkingDir) {+ emitResult(false, new Error(`refusing to write the page plan into ${absWorkingDir}: it is a symbolic link or junction. Pass the directory it points to if that is intended.`));+ return;+ }+ // The plan file itself, directly in the working directory whose own checks are above. A link at its path —+ // or a hard link, whose other names the write rewrites too — put the plan wherever it points, outside the+ // working directory included. Nothing else is ever at that path, so refusing costs a legitimate run+ // nothing, and a plain plan left by an earlier run is still rewritten; a folder there gets a reason, not+ // EISDIR.+ let planEntry = null;+ try {+ planEntry = fs.lstatSync(planPath);+ } catch (e) {+ if (!(e && e.code === 'ENOENT')) {+ emitResult(false, new Error(`cannot inspect ${planPath} (${(e && e.code) || e}); fix its permissions or remove it`));+ return;+ }+ }+ if (planEntry && (!planEntry.isFile() || planEntry.nlink > 1)) {+ emitResult(false, new Error(`refusing to write the page plan to ${planPath}: it is not a plain file (a link, junction, hard link or folder). Remove it and re-run.`));+ return;+ }+ const intentFiles = (spec.pages || []).filter((p) => p && (!p.source || p.source.kind === 'intent')).map(pageFile);+ const builtFiles = (spec.pages || []).filter((p) => p && p.source && p.source.kind === 'tsx' && p.source.codeFile).map(planFile);+ const problems = pageFileProblems(intentFiles, { workingDir: absWorkingDir, built: builtFiles });+ if (problems.length) {+ emitResult(false, new Error(`page file(s) are not safe to write in ${absWorkingDir}: ${problems.map((p) => p.message).join('; ')}`));+ return;+ }+fs.mkdirSync(path.dirname(planPath), { recursive: true });fs.writeFileSync(planPath, markdown, 'utf8');diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex 9920e57a6..06fb39730 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -292,7 +292,10 @@ After plan-mode approval (before the full build):`{ ok, planPath, pages: [{ name, key, file, dataMode, intent }] }`. Pass `--languages` throughfrom the environment probe — omitting it silently defaults every plan to English-only and dropsthe localization pattern. The command fails (before writing) if the plan would name a sample that- doesn't exist.+ doesn't exist, or if a page a worker will write is not a safe target in the working directory — a+ link at its path, a folder that links outside the directory, or a page already there under another+ spelling — or if a link, a hard link or a folder is already at the plan's own path. Stop and fix+ what it names; do not dispatch any worker.4. **Generate** — for each page from step 3 with `intent: true`, dispatch the **headless**`genpage-page-builder` worker via `Task`. Use its documented input contract verbatim — a missingdiff --git a/plugins/model-apps/skills/genpage/SKILL.md b/plugins/model-apps/skills/genpage/SKILL.mdindex 570efcad3..866696ac7 100644--- a/plugins/model-apps/skills/genpage/SKILL.md+++ b/plugins/model-apps/skills/genpage/SKILL.md@@ -74,14 +74,25 @@ application of planned edits.Follow these phases in order for every `/genpage` invocation.+**Every `<…>` you fill into a command goes in single quotes** (`'<working-dir>/prompt.txt'`, `'<App Name>'`).+PowerShell and bash expand nothing inside them — not `$name`, not `$(…)`, not a backtick — and a space does not split+the value. Escape a single quote inside the value the shell's way: in PowerShell double it, the typographic `‘ ’`+included (`'Bob''s app'`); in bash close, escape and reopen (`'Bob'\''s app'`). Never use double quotes for a value+(`"Revenue $100"` arrived as `Revenue `) and never leave one bare (`D:\Work Projects\…` became two arguments). A value+holding a double quote `"` is not put on a command line at all — Windows PowerShell 5.1 drops it and can split the+argument there — so ask for an app or solution name without one. Free text (a prompt, an agent message, a page's+display name) never goes into a shell command at all, however it is quoted: even a single-quoted here-string ends at a+line that begins with `'@`, and the rest of that line runs. Write it with your file-writing tool and pass the path+(Phase 6).+### Phase 0: Create Working DirectoryDerive a short folder name from the user's requirements:1. Extract the page name or a 2-4 word summary from `$ARGUMENTS`2. Convert to kebab-case (e.g., "Candidate Tracker" → `candidate-tracker`)-3. Create the folder: `mkdir -p <folder-name>` (bash/PowerShell; on cmd use `mkdir <folder-name>`,- which has no `-p` and errors if the folder exists)+3. Create the folder: `mkdir -p '<folder-name>'` (PowerShell or bash, the shells every command in this skill is+ written for)4. Resolve its absolute path — this is the **working directory** for all subsequent phases### Phase 0.5: Initialize Local-Dev Manifest@@ -93,18 +104,30 @@ definition" in their editor. Versions come from`scripts/lib/supported-dependencies.js`).```bash-node "${PLUGIN_ROOT}/scripts/generate-page-manifest.js" <working-dir> <kebab-slug>+node "${PLUGIN_ROOT}/scripts/generate-page-manifest.js" '<working-dir>' '<kebab-slug>'```- `<kebab-slug>` is the same slug used for the working directory.- Add `--features charts,datepicker,timepicker` (comma-separated) only whenthe requirements clearly call for them; otherwise omit and keep themanifest lean.-- The script is **idempotent** — it skips files that already exist. Pass- `--force` to overwrite (used in regeneration flows when versions drift).-- Output is a JSON summary on stdout; pipe to stderr for visibility but do- not block the workflow if the script returns non-zero — the manifest is a- dev-ergonomics aid, not part of the deployed artifact.+- The script keeps an existing `package.json` (no `--force`) only when it+ already lists every package the requested features need. A package present+ at a version the user changed is kept and listed as `versionDrift` in the+ JSON summary — mention it, since local type-checking then differs from the+ versions pages are written for. Pass `--force` to overwrite (used in+ regeneration flows when versions drift).+- Output is a JSON summary on stdout. **Continue only on exit 0.**+ - **Exit 2 — halt** and show the user the error line. When it names+ packages a requested feature needs that the existing `package.json`+ lacks, ask whether they will merge them into it or want a rerun with+ `--force` (which replaces the file), and rerun until it exits 0 before+ Phase 1 — continuing would leave a `--features charts` run on a manifest+ without `d3`, the stale state this check exists to stop. Exit 2 also+ reports a working directory that is a link or not a directory: never+ write through it.+ - Any other non-zero exit is a usage error in the command above: fix it and+ rerun.### Phase 1: Plan@@ -239,6 +262,26 @@ missing and stop, so the run can be re-driven with the decision supplied.section headings are a machine-readable contract that every downstream phaseparses by name.+ Before that approval writeback dispatch, quarantine any previous authoritative+ plan so a stale file cannot satisfy the post-dispatch existence check:++ ```powershell+ node "${PLUGIN_ROOT}/scripts/genpage-plan-provenance.js" prepare --plan '<working-dir>/genpage-plan.md'+ ```++ Continue only on `"ok":true`. It refuses a plan path, approval sidecar+ (`.approved-genpage-plan.md`) or `.genpage-provenance` folder that is a link or+ junction (a dangling one included) or the wrong kind of entry, since the approved+ plan would be written through it: on `"ok":false`, halt and tell the user to remove+ what the error names.++ Also save the plan body the planner returned for approval — the one presented+ with `EnterPlanMode`, or approved by default when unattended — to a sidecar such+ as `<working-dir>/.approved-genpage-plan.md` (not `genpage-plan.md`), exactly as+ returned. The planner writes a different document from it (the schema file, with+ suffix-only names), so the verifier compares what both name as targets: the pages+ to build.+If `genpage-planner` reports that the file tools needed to write the approved`genpage-plan.md` are unavailable, do not retry it and do not write the planinline. **Halt** with the approved plan body and failure recorded. Planner@@ -248,10 +291,21 @@ missing and stop, so the run can be re-driven with the decision supplied.Phase 2 reads that file as its first action.**If it is missing, do not proceed and do not write it yourself.** Re-invoke- the planner once more with the approval outcome and the plan body. If it is- still missing, stop and tell the user what was approved and what failed to be- written — a hand-written substitute is a plan with no provenance, and every- later phase will treat it as approved.+ the planner once more with the approval outcome and the plan body after running+ the `prepare` command above again. If it is still missing, stop and tell the+ user what was approved and what failed to be written — a hand-written substitute+ is a plan with no provenance, and every later phase will treat it as approved.++ If it exists, verify its provenance before Phase 2:++ ```powershell+ node "${PLUGIN_ROOT}/scripts/genpage-plan-provenance.js" verify --plan '<working-dir>/genpage-plan.md' --approved '@<working-dir>/.approved-genpage-plan.md'+ ```++ Continue only when the JSON result has `"ok":true`, and record its `writtenHash`+ in `workflow-log.md`. If the written plan targets other pages than the approved+ plan named — an extra, missing or renamed page file — halt: downstream phases+ would build pages the user did not approve.#### 1a. Connector discovery is orchestrator-owned and never speculative@@ -473,7 +527,7 @@ Read `genpage-plan.md` for the app decision and the `Solution` line in**If "create new":**```powershell-pac model create --name "App Name" --solution "<Solution unique name>" --publish+pac model create --name '<App Name>' --solution '<Solution unique name>' --publish```**`--solution` is mandatory.** `pac model create` errors out with@@ -498,7 +552,7 @@ the `Solution` line is informational only for this phase.If any page uses Dataverse entities, generate the TypeScript schema:```powershell-pac model genpage generate-types --data-sources "entity1,entity2,..." --output-file <working-dir>/RuntimeTypes.ts+pac model genpage generate-types --data-sources 'entity1,entity2,...' --output-file '<working-dir>/RuntimeTypes.ts'```> **Windows + Bash**: Always use forward slashes in file paths (e.g., `D:/temp/RuntimeTypes.ts`).@@ -572,15 +626,22 @@ authored while the flag was ON must not deploy Custom API bindings after it is tnode "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" custom-api```-**If it prints `disabled`:** Custom API support is OFF. Skip this phase entirely — do not-create or pass `actions.json`, and never add `--actions` on upload — **regardless of what the-plan's `## Custom API Bindings` section says**. (Backstop: `list-custom-apis.js` also fails-closed with exit 3 if invoked while OFF.)--**If it prints `enabled`:** read the plan's `## Custom API Bindings` section and treat it as-bindings **only when it contains an actual binding table** (a `| Name | Kind | …` header with-at least one data row). If the section is `No custom API bindings.`, empty, missing, or-malformed, treat the page as having no Custom APIs and skip this phase.+**If it prints `disabled`:** Custom API support is OFF. Do not create or pass `actions.json`,+and never add `--actions` on upload. The plan's `## Custom API Bindings` section still decides+whether the run may go on: only a body of exactly `No custom API bindings.` continues, with no+Custom APIs. For an **actual binding table** (a `| Name | Kind | …` header with at least one data+row), **halt before page generation**. That plan was made while the flag was on, and page+generation takes the table as permission to emit `executeAction` / `executeFunction` calls —+deploying them with no bindings leaves pages calling Custom APIs that are not bound. Tell the user+to turn the flag back on, or re-run planning (the Custom API builder writes no bindings while the+flag is off). A missing, empty, or malformed section halts too, exactly as in the `enabled`+branch. (Backstop: `list-custom-apis.js` also fails closed with exit 3 if invoked while OFF.)++**If it prints `enabled`:** read the plan's `## Custom API Bindings` section. The section is+mandatory: continue with no actions only when its body is exactly `No custom API bindings.`.+Treat it as bindings only when it contains an actual binding table (a `| Name | Kind | …`+header with at least one data row). If the section is missing, empty, or malformed, **halt**+before page generation; do not interpret a planner/schema failure as "no Custom APIs".When there are real bindings, the `genpage-customapi-builder` agent already wrote`<working-dir>/actions.json` during planning — verify it exists and matches the plan table. If@@ -620,9 +681,27 @@ Read `genpage-plan.md` and extract the pages table.Before invoking any builders, verify:- At least one page exists in the `## Pages` table- Every page has a `### [Page Name]` subsection in `## Per-Page Specifications`-- **All filenames in the `## Pages` table are unique.** If any are duplicated,- rewrite the plan appending `-1`, `-2`, etc. before dispatch. Duplicate filenames- cause silent last-writer-wins data loss under parallel execution.+- **All filenames in the `## Pages` table are safe and unique.** Run the deterministic gate —+ it applies the same rule as the plan validator and `/app-builder`:++ ```powershell+ node "${PLUGIN_ROOT}/scripts/check-page-files.js" --plan '<working-dir>/genpage-plan.md'+ ```++ Continue only on `"ok":true`. It reads the plan's one `## Pages` table: a plan with a second+ Pages table that has a File column is refused, not read by its first — one quoted in the+ requirements, fenced, quoted or not, counts. It refuses absolute paths (drive-qualified ones included), `..`+ traversal, backslash separator aliases, a character a shell would expand or split on (a space,+ `$`, a backtick, `;` — page file names use letters, digits, `.`, `-` and `_`), a name Windows cannot store (a device name such as+ `CON.tsx`, a reserved character such as `:`, or a trailing dot or space), a name that is not a+ `.tsx` page file (such as `package.json` or `RuntimeTypes.ts`), a page path that is itself a link,+ junction or hard link or is not a regular file, a parent that resolves through a link or junction+ to outside the working directory or cannot be resolved at all (a dangling link, a folder it cannot+ read), and case-insensitive collisions — `Page.tsx` plus `page.tsx` in the plan, two names that+ reach one file through a link, or a name whose file or folder is already on disk under another+ spelling. On any problem, halt and re-plan instead of rewriting filenames here: a renamed+ file is a page the user did not approve, and the provenance check compares page files.+ Duplicate filenames cause silent last-writer-wins data loss under parallel execution.See `${PLUGIN_ROOT}/references/plan-schema.md` for the full contract.@@ -639,11 +718,14 @@ subagent. Inline the page-builder workflow directly in the orchestrator:`${PLUGIN_ROOT}/references/connectors.md`. Treat a `No connector bindings.`sentinel, an empty/missing/malformed section, **or a `disabled` probe** ashaving no connectors (same contract as Phase 4.5 and genpage-page-builder).-3b. Only when the plan's `## Custom API Bindings` section contains an **actual- binding table** (a `| Name | Kind | …` header with at least one data row),- also read `${PLUGIN_ROOT}/references/custom-api.md`. Treat a- `No custom API bindings.` sentinel, or an empty/missing/malformed section, as- having no Custom APIs (same contract as Phase 4.6 and genpage-page-builder).+3b. Only when the Phase 4.6 probe printed `enabled` **and** the plan's+ `## Custom API Bindings` section contains an **actual binding table** (a+ `| Name | Kind | …` header with at least one data row), also read+ `${PLUGIN_ROOT}/references/custom-api.md`. Treat a+ `No custom API bindings.` sentinel as no Custom APIs. If the section is+ missing, empty, or malformed, halt before inline generation (same contract as+ Phase 4.6); do not downgrade a planner/schema failure to "no Custom APIs."+ (A `disabled` probe with a binding table has already halted in Phase 4.6.)4. If the plan's Per-Page Specification has `Needs caching: true`, also read`${PLUGIN_ROOT}/references/data-caching.md`5. If the plan's `## Environment` indicates non-English languages, also read@@ -654,7 +736,15 @@ subagent. Inline the page-builder workflow directly in the orchestrator:contains no telemetry calls — do not read it.6. Read `genpage-plan.md` (already in working directory) and `RuntimeTypes.ts`if Data mode is dataverse-7. Write the `.tsx` file to `<working-dir>/<filename>.tsx` following all rules+7. Stamp the target, so the gate below can tell the page you write from one an earlier attempt left+ there. Here and below, `<filename>` is the page's `File` value from the plan without its `.tsx`+ extension (`candidate-tracker.tsx` gives `candidate-tracker`):++ ```powershell+ node "${PLUGIN_ROOT}/scripts/genpage-worker-output.js" --stamp --file '<working-dir>/<filename>.tsx'+ ```++ Then write the `.tsx` file to `<working-dir>/<filename>.tsx` following all rules8. After writing, Grep every named import from `@fluentui/react-icons` against`${PLUGIN_ROOT}/references/verified-icons.txt` (one Grep per name).Rewrite any unverified names with the closest verified alternative; do not@@ -663,14 +753,33 @@ subagent. Inline the page-builder workflow directly in the orchestrator:that shorthand only at runtime; the regex catches unquoted, quoted, andwhitespace-separated property syntax. Replace every match with the fourexplicit border-side widths before deployment.-10. Proceed to Phase 6+10. Run the completeness gate on the page you wrote — the same one 5c runs on a+ worker's page, and this is also the page a 5c fallback produces:++ ```powershell+ node "${PLUGIN_ROOT}/scripts/genpage-worker-output.js" --file '<working-dir>/<filename>.tsx'+ ```++ On `"ok":false`, rewrite the page once from the same plan inputs and run the+ gate again; if it still fails, halt with the reported problems rather than+ deploy an incomplete page.+11. Proceed to Phase 6This saves ~5-15s of Task overhead and ~3K tokens that would otherwise beduplicated in a subagent context.#### 5c. Multi-page: invoke page-builders in parallel-**If the plan's Pages table contains 2+ rows**, invoke a `genpage-page-builder`+**If the plan's Pages table contains 2+ rows**, first stamp every target, so the gate after the+workers can tell a page a worker wrote from one an earlier attempt left there (continue only on+`"ok":true`). Here and below, `<filename>` and `[filename]` are each page's `File` value from the+plan without its `.tsx` extension (`candidate-tracker.tsx` gives `candidate-tracker`):++```powershell+node "${PLUGIN_ROOT}/scripts/genpage-worker-output.js" --stamp --file '<working-dir>/<filename>.tsx'+```++Then invoke a `genpage-page-builder`agent via the `Task` tool per page. **Fire all invocations in a single message**for parallel execution.@@ -718,12 +827,26 @@ For each page, pass a prompt that includes:Wait for all page-builder tasks to complete before proceeding.-After the parallel workers return, confirm every target file exists. If a worker-reported missing declared file/process tools or produced no file, do not-re-dispatch that worker. Run the Phase 5b page-builder workflow inline for only-the failed page, preserving the same plan and dispatch inputs. Then Grep every-generated page with `['"]?borderWidth['"]?\s*:` and replace the unsupported-Griffel shorthand before Phase 6.+After the parallel workers return, validate every target file with the deterministic+completeness gate:++```powershell+node "${PLUGIN_ROOT}/scripts/genpage-worker-output.js" --file '<working-dir>/<filename>.tsx'+```++The script reuses the source-literals checks for a complete default export (a file+cut off inside its own export line fails), unbalanced brackets, and a file that+stops mid-statement (inside JSX, a string or a comment, or after an operator), and also rejects a markdown code fence around the code and+elided code — a `FIXME` comment, a `TODO` that opens a comment or takes a colon,+a comment opening with `...`, "omitted for brevity", or a bare `...` line. The+same words in strings or JSX text ("Loading…"), or as prose in a comment ("the+todo list"), are UI copy and pass. It also refuses a page that is exactly as its dispatch stamp+recorded it: the worker wrote nothing, and what is there is an earlier attempt's. If a worker reported missing declared file/process tools, produced no file,+or `genpage-worker-output.js` returns `"ok":false`, do not re-dispatch that worker.+Run the Phase 5b page-builder workflow inline for only the failed page, preserving+the same plan and dispatch inputs. This is the same inline fallback path for missing+and invalid worker output. Then Grep every generated page with+`['"]?borderWidth['"]?\s*:` and replace the unsupported Griffel shorthand before Phase 6.### Phase 6: Deploy@@ -742,11 +865,11 @@ The help output must contain `--connectors`. If it does not, stop and surface:not silently drop bindings.Connector deployment matrix:-- **Create (new page):** include `--connectors "<working-dir>/connectors.json"`+- **Create (new page):** include `--connectors '<working-dir>/connectors.json'`with the first `upload --add-to-sitemap`.- **Edit — connectors changed, added, or one removed:** write the full desiredbinding set to `connectors.json` and include `--connectors` with- `upload --page-id <id>` (full replace).+ `upload --page-id '<id>'` (full replace).- **Edit — no connector change:** omit `--connectors`; pac preserves existingbindings. Never pass a stale or empty file on an unrelated edit.- **Delete all connectors:** write `[]` to `connectors.json` and pass@@ -757,7 +880,7 @@ must contain `--actions`; if not, stop and surface "Custom API deploy requires a`pac model genpage upload --actions` (PowerPlatform-Scale-AdminTools)." Don't silently drop bindings.Custom API deployment follows the **identical matrix** as connectors, substituting-`--actions "<working-dir>/actions.json"` for `--connectors`: pass it on create; on an edit only+`--actions '<working-dir>/actions.json'` for `--connectors`: pass it on create; on an edit onlywhen bindings changed/added/removed (full replace); omit it on an unrelated edit (pac preservesexisting); write `[]` and pass it to clear all `actionBindings`.@@ -771,24 +894,41 @@ Was it quote wrapped? No, be sure to wrap values that contain spaces.…for a prompt containing an ASCII-quoted multiword page name. **Never "fix" that by editing the approved prompt** (for example swapping in typographic quotes): the page would then be built from text the user never approved.-**Write the prompt and agent-message to files first**, then pass the paths:+**Write the prompt, the agent-message and, on a create, the page's display name to files first**, then pass the+paths. The display name is the maker's text too: substituted into a double-quoted `--name` value, PowerShell expanded `$(…)` in+it before the script ran, and `Revenue $100` arrived as `Revenue `. Pass it with `--name-file`, never `--name`.++**Write these files with your file-writing tool (Write), never with a shell command.** No quoting makes the maker's+text safe inside a command: a single-quoted here-string ends at a line that begins with `'@` (or `‘@`, `’@`), and the+rest of that line runs. First check that none of the names is a link — a write through a link or hard link left at+one of them rewrites the file it points to, outside the working directory included — and clear the files an earlier+deploy left, so the tool writes each one fresh. This step carries no text:```powershell-Set-Content -Path "<working-dir>/prompt.txt" -Value $prompt -Encoding UTF8 -NoNewline-Set-Content -Path "<working-dir>/agent-message.txt" -Value $agentMessage -Encoding UTF8 -NoNewline+$wd = '<working-dir>'+foreach ($f in 'prompt.txt', 'agent-message.txt', 'page-name.txt') {+ $at = Get-Item -LiteralPath (Join-Path $wd $f) -Force -ErrorAction SilentlyContinue+ if ($at -and ($at.LinkType -or $at.PSIsContainer)) { throw "$f in $wd is a link or a folder, not a file this skill wrote: remove it and re-run" }+ if ($at) { Remove-Item -LiteralPath $at.FullName -Force }+}```+Then write, with the file tool, `<working-dir>/prompt.txt` holding the prompt, `<working-dir>/agent-message.txt` the+agent message and, on a create, `<working-dir>/page-name.txt` the page's display name — each exactly its text (a+trailing line break on the name is ignored). `genpage-upload.js` refuses any of them that is a link, a hard link or a+folder, but only after the write.+**Log the invocation into `workflow-log.md` under a `## Phase 6 — Deploy` section before running it.** Record the flags and the prompt-file path, plus the prompt's scope, so the approved text is preserved semantically without embedding arbitrary text as an executable command. Format:```markdown## Phase 6 — Deploy-- Command: `node "${PLUGIN_ROOT}/scripts/genpage-upload.js" --env <org-url> --app-id <id> --code-file "<path>" --data-sources '<entities>' --prompt-file "<working-dir>/prompt.txt" --model <model-id> --name "<page name>" --agent-message-file "<working-dir>/agent-message.txt" --add-to-sitemap`+- Command: `node "${PLUGIN_ROOT}/scripts/genpage-upload.js" --env '<org-url>' --app-id '<id>' --code-file '<path>' --data-sources '<entities>' --prompt-file '<working-dir>/prompt.txt' --model '<model-id>' --name-file '<working-dir>/page-name.txt' --agent-message-file '<working-dir>/agent-message.txt' --add-to-sitemap`- Prompt scope: full page description from plan's `## User Requirements` (create) — or the delta only (update)- Result: page-id = <returned-id>, status = success```-When present, the logged command must also include `--connectors "<working-dir>/connectors.json"`-and/or `--actions "<working-dir>/actions.json"`.+When present, the logged command must also include `--connectors '<working-dir>/connectors.json'`+and/or `--actions '<working-dir>/actions.json'`.#### Prompt semantics@@ -810,16 +950,16 @@ re-deploys, and the entire edit flow.```powershellnode "${PLUGIN_ROOT}/scripts/genpage-upload.js" `- --env <org-url> `- --app-id <app-id> `- --code-file <working-dir>/<file>.tsx `- --name "Page Display Name" `- --data-sources "entity1,entity2" `- --connectors "<working-dir>/connectors.json" `- --actions "<working-dir>/actions.json" `- --prompt-file "<working-dir>/prompt.txt" `- --model "<current-model-id>" `- --agent-message-file "<working-dir>/agent-message.txt" `+ --env '<org-url>' `+ --app-id '<app-id>' `+ --code-file '<working-dir>/<file>.tsx' `+ --name-file '<working-dir>/page-name.txt' `+ --data-sources 'entity1,entity2' `+ --connectors '<working-dir>/connectors.json' `+ --actions '<working-dir>/actions.json' `+ --prompt-file '<working-dir>/prompt.txt' `+ --model '<current-model-id>' `+ --agent-message-file '<working-dir>/agent-message.txt' `--add-to-sitemap```@@ -834,16 +974,16 @@ Use `--page-id`, omit `--add-to-sitemap`, and **scope the prompt to the delta on```powershellnode "${PLUGIN_ROOT}/scripts/genpage-upload.js" `- --env <org-url> `- --app-id <app-id> `- --page-id <page-id> `- --code-file <working-dir>/<file>.tsx `- --data-sources "entity1,entity2" `- --connectors "<working-dir>/connectors.json" `- --actions "<working-dir>/actions.json" `- --prompt-file "<working-dir>/prompt.txt" `- --model "<current-model-id>" `- --agent-message-file "<working-dir>/agent-message.txt"+ --env '<org-url>' `+ --app-id '<app-id>' `+ --page-id '<page-id>' `+ --code-file '<working-dir>/<file>.tsx' `+ --data-sources 'entity1,entity2' `+ --connectors '<working-dir>/connectors.json' `+ --actions '<working-dir>/actions.json' `+ --prompt-file '<working-dir>/prompt.txt' `+ --model '<current-model-id>' `+ --agent-message-file '<working-dir>/agent-message.txt'```For updates, include the `--connectors` line only when this upload intentionally@@ -873,21 +1013,20 @@ phase substitutes the real GUIDs."Prompt semantics" rule in Phase 6, this is an **update**, so the promptdescribes the delta only — not the original page description:- ```powershell- Set-Content -Path "<working-dir>/prompt.txt" -Encoding UTF8 -NoNewline `- -Value "Resolve cross-page navigation placeholders to real page GUIDs (post-deploy fix-up)"- Set-Content -Path "<working-dir>/agent-message.txt" -Encoding UTF8 -NoNewline `- -Value "Replaced PAGEREF_<name> tokens with actual page IDs returned by Phase 6"+ Check and clear the two names as in Phase 6, then write them with the file tool: `prompt.txt` holding+ `Resolve cross-page navigation placeholders to real page GUIDs (post-deploy fix-up)` and `agent-message.txt`+ holding `Replaced PAGEREF_<name> tokens with actual page IDs returned by Phase 6`. Then:+ ```powershellnode "${PLUGIN_ROOT}/scripts/genpage-upload.js" `- --env <org-url> `- --app-id <app-id> `- --page-id <page-id-from-Phase-6> `- --code-file <working-dir>/<file>.tsx `- --data-sources "entity1,entity2" `- --prompt-file "<working-dir>/prompt.txt" `- --model "<current-model-id>" `- --agent-message-file "<working-dir>/agent-message.txt"+ --env '<org-url>' `+ --app-id '<app-id>' `+ --page-id '<page-id-from-Phase-6>' `+ --code-file '<working-dir>/<file>.tsx' `+ --data-sources 'entity1,entity2' `+ --prompt-file '<working-dir>/prompt.txt' `+ --model '<current-model-id>' `+ --agent-message-file '<working-dir>/agent-message.txt'```Pages with no `PAGEREF_` strings need no second upload.@@ -899,14 +1038,14 @@ Adds the deployed app, the GenPage(s), and any connection references to thetarget solution so they travel cross-environment.1. Ensure the solution exists — create it only if it doesn't already exist:- `node ${PLUGIN_ROOT}/scripts/provision-solution.js <envUrl> <solutionUniqueName> "<Friendly Name>" [--publisher <uniqueName>]`+ `node "${PLUGIN_ROOT}/scripts/provision-solution.js" '<envUrl>' '<solutionUniqueName>' '<Friendly Name>' [--publisher '<uniqueName>']`It prints `{ "ok": true, "solutionId": …, "uniqueName": …, "publisherPrefix": … }`;`uniqueName` must start with a letter and contain only letters, digits, andunderscores. Without `--publisher` it resolves the environment's default publisher.2. Add the app + GenPage(s) + connection references (pass the page-id(s) returnedby Phase 6 as `--page-ids` — the GenPage is added explicitly, it does NOT travelwith the app on its own):- `node ${PLUGIN_ROOT}/scripts/add-page-to-solution.js <envUrl> <solutionUniqueName> <app-id> --page-ids "<page-id1,page-id2>" --connection-refs "<logicalName1,logicalName2>"`+ `node "${PLUGIN_ROOT}/scripts/add-page-to-solution.js" '<envUrl>' '<solutionUniqueName>' '<app-id>' --page-ids '<page-id1,page-id2>' --connection-refs '<logicalName1,logicalName2>'`3. Log the command + result to `workflow-log.md`.Cross-env note: the app (80) pulls the sitemap (62); the GenPagediff --git a/plugins/model-apps/skills/genpage/edit-flow.md b/plugins/model-apps/skills/genpage/edit-flow.mdindex c46e35d81..6a17950f5 100644--- a/plugins/model-apps/skills/genpage/edit-flow.md+++ b/plugins/model-apps/skills/genpage/edit-flow.md@@ -6,7 +6,7 @@ to `genpage-edit-planner`, then applies the edit inline.> **⚠️ CRITICAL — do NOT hallucinate app or page names.** App names and page> names are discovered by running `pac model list` and `pac model genpage list-> --app-id <id>`. Never guess them from the repo, the conversation context,+> --app-id '<id>'`. Never guess them from the repo, the conversation context,> sample app names, or anywhere else. Always run the commands first, then> present what the commands returned to the user.@@ -66,7 +66,7 @@ Record the selected `<app-id>`.### 1b. Discover existing pages in the selected app```powershell-pac model genpage list --app-id <app-id>+pac model genpage list --app-id '<app-id>'```This returns the list of generative pages already deployed in the selected app,@@ -93,9 +93,9 @@ No `AskUserQuestion` here — this is a status update before the next phase.```powershellpac model genpage download `- --app-id <app-id> `- --page-id <page-id> `- --output-directory <working-dir>+ --app-id '<app-id>' `+ --page-id '<page-id>' `+ --output-directory '<working-dir>'```The download creates a `<working-dir>/<page-id>/` folder with fixed filenames:@@ -111,8 +111,8 @@ page uses Dataverse entities — generate the schema:```powershellpac model genpage generate-types `- --data-sources "entity1,entity2" `- --output-file <working-dir>/RuntimeTypes.ts+ --data-sources 'entity1,entity2' `+ --output-file '<working-dir>/RuntimeTypes.ts'```Pass the exact entity list from `config.json.dataSources`. If `dataSources` is an@@ -280,7 +280,29 @@ cannot be replaced by an inline fallback that invents its approved contract.body it returned, every prior discovery (connector and Custom API contracts,entities), and every answer already gathered. On **approval**, re-invoke theplanner with that full state plus the approval outcome so it writes the approved- `<working-dir>/genpage-edit-plan.md` — not a plan it re-derives from scratch. On+ `<working-dir>/genpage-edit-plan.md` — not a plan it re-derives from scratch.+ Before that approval writeback dispatch, quarantine any prior edit plan:++ ```powershell+ node "${PLUGIN_ROOT}/scripts/genpage-plan-provenance.js" prepare --plan '<working-dir>/genpage-edit-plan.md'+ ```++ Continue only on `"ok":true` — on `"ok":false` (a link, junction or wrong kind of+ entry at the plan path, its `.approved-` sidecar or `.genpage-provenance`, which the+ approved plan would be written through), halt and tell the user to remove what the+ error names.++ Save the edit-plan body the planner returned for approval to a sidecar such as+ `<working-dir>/.approved-genpage-edit-plan.md`, exactly as returned, then after the+ planner returns, verify the file it wrote targets the page that plan named:++ ```powershell+ node "${PLUGIN_ROOT}/scripts/genpage-plan-provenance.js" verify --plan '<working-dir>/genpage-edit-plan.md' --approved '@<working-dir>/.approved-genpage-edit-plan.md'+ ```++ Continue only when the JSON result has `"ok":true`; if the written edit plan is for+ a different page, halt because Phase 5 would overwrite a page the user did not+ approve editing. On**changes requested**, re-invoke it with the same full state plus the requestedrevisions and present the revised plan again. Forwarding only the outcome lets itreconstruct a different plan or re-ask answered questions (same rule as the create@@ -332,7 +354,7 @@ Connector binding rules for edit deploy:agent (Mode: `edit`) has already gated on the flag and written the full desiredbinding set to `<working-dir>/connectors.json` (a removal writes the remainingbindings). Pre-flight that `pac model genpage upload --help` contains `--connectors`- and include `--connectors "<working-dir>/connectors.json"` in the upload — this is a+ and include `--connectors '<working-dir>/connectors.json'` in the upload — this is afull replace, so it also deletes any binding left out of the file.- **Code/visual-only edit (connectors unchanged):** omit `--connectors`; pacpreserves existing bindings.@@ -346,31 +368,31 @@ Custom API binding rules for edit deploy (identical matrix, `--actions` foragent (Mode: `edit`) has already gated on the flag and written the full desired bindingset to `<working-dir>/actions.json` (a removal writes the remaining bindings). Pre-flightthat `pac model genpage upload --help` contains `--actions` and include- `--actions "<working-dir>/actions.json"` in the upload — a full replace that also deletes+ `--actions '<working-dir>/actions.json'` in the upload — a full replace that also deletesany binding left out of the file.- **Code/visual-only edit (Custom APIs unchanged):** omit `--actions`; pac preservesexisting `actionBindings`.- **Remove every Custom API:** write `[]` to `actions.json` and pass `--actions` so pacclears `config.json.actionBindings`.-```powershell-# The edit request is arbitrary user text, and a downloaded prompt is a multi-line-# conversation transcript. Both go to pac BY FILE via scripts/genpage-upload.js, never on a-# command line, so quotes/newlines/metacharacters cannot be reinterpreted by the shell.-Set-Content -Path "<working-dir>/prompt.txt" -Value $editRequest -Encoding UTF8 -NoNewline-Set-Content -Path "<working-dir>/agent-message.txt" -Value $changeSummary -Encoding UTF8 -NoNewline+The edit request is arbitrary user text, and a downloaded prompt is a multi-line conversation+transcript. Both go to pac BY FILE via `scripts/genpage-upload.js`, never through a shell command:+check and clear `prompt.txt` and `agent-message.txt` as in SKILL.md Phase 6, then write them with+your file-writing tool — `prompt.txt` holding the edit request (only the changes) and+`agent-message.txt` the change summary. Then:+```powershellnode "${PLUGIN_ROOT}/scripts/genpage-upload.js" `- --env <org-url> `- --app-id <app-id> `- --page-id <page-id> `- --code-file <working-dir>/<page-id>/page.tsx `- --data-sources "entity1,entity2" `- --connectors "<working-dir>/connectors.json" `- --actions "<working-dir>/actions.json" `- --prompt-file "<working-dir>/prompt.txt" `- --model "<current-model-id>" `- --agent-message-file "<working-dir>/agent-message.txt"+ --env '<org-url>' `+ --app-id '<app-id>' `+ --page-id '<page-id>' `+ --code-file '<working-dir>/<page-id>/page.tsx' `+ --data-sources 'entity1,entity2' `+ --connectors '<working-dir>/connectors.json' `+ --actions '<working-dir>/actions.json' `+ --prompt-file '<working-dir>/prompt.txt' `+ --model '<current-model-id>' `+ --agent-message-file '<working-dir>/agent-message.txt'```The prompt file holds the user's edit request — **only the changes, not the full page**.diff --git a/plugins/model-apps/skills/genpage/verify-flow.md b/plugins/model-apps/skills/genpage/verify-flow.mdindex 9f508568a..4f60425d4 100644--- a/plugins/model-apps/skills/genpage/verify-flow.md+++ b/plugins/model-apps/skills/genpage/verify-flow.md@@ -106,20 +106,19 @@ Omitting `--data-sources` here is safe: the page's existing table bindings areread and re-sent, so a fix re-deploy does not unbind it. Pass `--data-sources`to change the bindings, or `--clear-data-sources` to remove them deliberately.-```powershell-Set-Content -Path "<working-dir>/prompt.txt" -Encoding UTF8 -NoNewline `- -Value "Fix sort handler on Name column; correct accidental DataGrid type prop"-Set-Content -Path "<working-dir>/agent-message.txt" -Encoding UTF8 -NoNewline `- -Value "Phase 7.5 fix re-deploy"+Check and clear `prompt.txt` and `agent-message.txt` as in SKILL.md Phase 6, then write them with your+file-writing tool — `prompt.txt` holding the fix delta and `agent-message.txt` holding+`Phase 7.5 fix re-deploy` — and deploy:+```powershellnode "${PLUGIN_ROOT}/scripts/genpage-upload.js" `- --env <org-url> `- --app-id <app-id> `- --page-id <page-id> `- --code-file "<working-dir>/<file>.tsx" `- --prompt-file "<working-dir>/prompt.txt" `- --model "<current-model-id>" `- --agent-message-file "<working-dir>/agent-message.txt"+ --env '<org-url>' `+ --app-id '<app-id>' `+ --page-id '<page-id>' `+ --code-file '<working-dir>/<file>.tsx' `+ --prompt-file '<working-dir>/prompt.txt' `+ --model '<current-model-id>' `+ --agent-message-file '<working-dir>/agent-message.txt'```**Common Playwright issues:**