A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
model-apps 2.20.2: Windows temp workspaces stay where cleanup finds them (#779)
Akshay Maloof39b3bb0d5a9
diff --git a/evals/model-apps/genpage/EVAL_GUIDE.md b/evals/model-apps/genpage/EVAL_GUIDE.mdindex 90505b5bb..8f657ec27 100644--- a/evals/model-apps/genpage/EVAL_GUIDE.md+++ b/evals/model-apps/genpage/EVAL_GUIDE.md@@ -117,7 +117,7 @@ Whether a page applies a style the maker asked for (a plan whose `Styling:` linePlus per-eval `expectations` for **Phase 5, 5a, 5b and 5c**. `Edit Phase 5` entries remain Layer-1 expectations. The column-name expectations (eval 1's Phase 5b, in both layers, and eval 7's) are graded by `lib/column-contract.js` against the RuntimeTypes.ts a fixture kept: every column a page names in its dataApi calls — a `select` list, an `orderBy` or `filter` expression, the keys of a `createRow`/`updateRow` payload, an options object or select list written as a name it declares, and each `<column>@OData.Community.Display.V1.FormattedValue` key it reads — must be one the schema declares on that table (or a system column every user-owned table has and the type generator does not write, such as `createdon`). A fixture that kept no RuntimeTypes.ts reports `column-name verification requires RuntimeTypes.ts fixture`. Lookup-identity use in page code is not graded yet: no check proves that a page reads, filters, retrieves, opens or writes a lookup only through its normalized table-and-id pair (`references/rules.md` Critical Rule 23) — eval 26 grades the question, the lookup metadata and the plan records behind its page, not the page's lookup code. Other unregistered expectations are reported as skips, not claimed as coverage. The API request scorer supports literal request objects in named helpers and scalar annotations; it is not a TypeScript compiler or a runtime execution oracle.-**Structural page checks:** several per-eval expectations are graded from how a page is BUILT rather than whether a word appears in it — eval 4's review step showing every entered field before the submit, and a label on every form field (its own `aria-label`/`aria-labelledby`, or a Fluent `<Field label>` around it); eval 5's components and utilities kept top level (a nested PascalCase component, or a nested function that reads nothing from the one around it, fails; a handler that closes over state does not); eval 12's search box beside a filter toolbar; eval 13's shown text through the `translate` (or `t`) helper; and eval 15's choice values named after the RuntimeTypes.ts member they are. `lib/tsx-structure.js` reads elements, attributes, JSX text and function scopes from the plugin's lexer view, where strings, comments and JSX text are blanked at their offsets, and `lib/page-checks.js` holds the checks; each states what it does not judge, which stays with the Layer 3 rubric. Eval 4's step navigation ("step state management … and Next/Back navigation") is deliberately not graded: whether Next and Back move the step is the value the step's setter receives — an updater can compute the next step and return the old one — which a scan of the page's text cannot prove; it needs data-flow analysis, and the coverage baseline records it as unscored with that reason.+**Structural page checks:** several per-eval expectations are graded from how a page is BUILT rather than whether a word appears in it — eval 4's review step showing every entered field before the submit, and a label on every form field (its own `aria-label`/`aria-labelledby`, or a Fluent `<Field label>` around it); eval 5's components and utilities kept top level (a nested PascalCase component, or a nested function that reads nothing from the one around it, fails; a handler that closes over state does not); eval 12's search box beside a filter toolbar; eval 13's shown text through the `translate` (or `t`) helper; and eval 15's choice values named after the RuntimeTypes.ts member they are. `lib/tsx-structure.js` reads elements, attributes, JSX text and function scopes from the plugin's lexer view, where strings, comments and JSX text are blanked at their offsets, and `lib/page-checks.js` holds the checks; each states what it does not judge, which stays with the Layer 3 rubric. JSX text and a JSX attribute's string are read as the page renders them: `lib/jsx-references.js` decodes their character references with the page compiler the plugin vendors, so to eval 13's checks `<Text>Hi</Text>` is the hardcoded text "Hi" and `<Text>€{total}</Text>` a hardcoded currency symbol, exactly as when written plainly, while a JavaScript string (`{'€'}`) shows its references as written. Eval 4's step navigation ("step state management … and Next/Back navigation") is deliberately not graded: whether Next and Back move the step is the value the step's setter receives — an updater can compute the next step and return the old one — which a scan of the page's text cannot prove; it needs data-flow analysis, and the coverage baseline records it as unscored with that reason.**Bounded Custom API declaration tracking (Layers 1 and 2):** Potential-write checksdistinguish a definite plain arrow parameter declaration, including a default, from andiff --git a/evals/model-apps/genpage/lib/assertions-layer-2.js b/evals/model-apps/genpage/lib/assertions-layer-2.jsindex a87f486b3..da0a60f34 100644--- a/evals/model-apps/genpage/lib/assertions-layer-2.js+++ b/evals/model-apps/genpage/lib/assertions-layer-2.js@@ -30,7 +30,7 @@ const {reviewSummaryProblems, formFieldLabelProblems, searchAndFilterProblems,translateCoverageProblems, choiceEnumProblems,} = require('./page-checks.js');-const { nestedDefinitionProblems } = require('./tsx-structure.js');+const { nestedDefinitionProblems, renderedSource } = require('./tsx-structure.js');const { columnProblems } = require('./column-contract.js');let _verifiedIcons = null;@@ -688,6 +688,10 @@ PHASE5_EXPECTATIONS.set(// Not currency: a bare `${x}` interpolation (its `$` is the template delimiter), an OData query// option such as '?$select=' + cols (`$` is followed by a name), and a `currency:` key outside a// `style: 'currency'` number format (e.g. a translation dictionary `{ currency: 'Devise' }`).+// JSX text and JSX attribute strings are read as the page renders them (renderedSource): the compiler+// decodes their character references, so `<Text>€{total}</Text>` shows "€", `<Text>${total}</Text>`+// a "$" before the amount and `MM/dd/yyyy` a date pattern, exactly as if written plainly. A+// JavaScript string or template is not decoded: `'€'` shows those characters as written.const DATE_PART = '(?:d{1,2}|D{1,2}|M{1,4}|y{2,4}|Y{2,4})';const DATE_PATTERN = new RegExp(`\\b${DATE_PART}([/.\\-])${DATE_PART}\\1${DATE_PART}\\b`);@@ -772,32 +776,38 @@ function hardcodedFormatProblem(content) {else if (!comment[i] && !/\s/.test(content[i])) opener = content[i];}const isText = (i) => isLiteral(i) && !inRegex[i];- const text = content.split('').map((ch, i) => (isText(i) ? ch : ' ')).join('');+ // The symbol and date reads below run over the page as it renders (renderedSource): `shown` has the character+ // references of its JSX text and JSX attribute strings decoded, and `shown[k]` comes from source offset `at[k]`, so+ // which characters are text is still the lexer's reading of the source. A page whose JSX holds no reference is its own+ // `shown`, at the same offsets.+ const { shown, at } = renderedSource(content);+ const isShownText = (k) => isText(at[k]);+ const text = shown.split('').map((ch, k) => (isShownText(k) ? ch : ' ')).join('');// The code character next to a string literal's delimiter, skipping whitespace, in direction dir.const codeNeighbour = (from, dir) => {let k = from;- while (k >= 0 && k < content.length && /\s/.test(content[k])) k += dir;- return k >= 0 && k < content.length && !isText(k) ? content[k] : '';+ while (k >= 0 && k < shown.length && /\s/.test(shown[k])) k += dir;+ return k >= 0 && k < shown.length && !isShownText(k) ? shown[k] : '';};for (const m of text.matchAll(/[$\u20ac\u00a3\u00a5\u20b9]/g)) {const i = m.index;if (m[0] !== '$') return `hardcoded currency symbol "${m[0]}"`;let j = i + 1;- while (j < content.length && /[ \t]/.test(content[j])) j += 1;- const amount = /\d/.test(content[j] || '');- const templateCurrency = content[i + 1] === '$' && content[i + 2] === '{';- const jsxCurrency = content[j] === '{' && !isText(j);+ while (j < shown.length && /[ \t]/.test(shown[j])) j += 1;+ const amount = /\d/.test(shown[j] || '');+ const templateCurrency = shown[i + 1] === '$' && shown[i + 2] === '{';+ const jsxCurrency = shown[j] === '{' && !isShownText(j);// String-boundary currency: the `$` is the last text character before a closing quote that is// followed by `+`, or the first text character after an opening quote that is preceded by `+`.// Whitespace is skipped unconditionally: the text view blanks string contents to spaces, so a// space inside the string is indistinguishable from code here. Quote DELIMITERS stay visible in- // the code view (a quote inside text is blanked), which is what `!isText` tests below.+ // the code view (a quote inside text is blanked), which is what `!isShownText` tests below.let end = i + 1;- while (end < content.length && /[ \t]/.test(content[end])) end += 1;+ while (end < shown.length && /[ \t]/.test(shown[end])) end += 1;let start = i - 1;- while (start >= 0 && /[ \t]/.test(content[start])) start -= 1;- const prefixConcat = /['"`]/.test(content[end] || '') && !isText(end) && codeNeighbour(end + 1, 1) === '+';- const suffixConcat = start >= 0 && /['"`]/.test(content[start]) && !isText(start) && codeNeighbour(start - 1, -1) === '+';+ while (start >= 0 && /[ \t]/.test(shown[start])) start -= 1;+ const prefixConcat = /['"`]/.test(shown[end] || '') && !isShownText(end) && codeNeighbour(end + 1, 1) === '+';+ const suffixConcat = start >= 0 && /['"`]/.test(shown[start]) && !isShownText(start) && codeNeighbour(start - 1, -1) === '+';if (amount || templateCurrency || jsxCurrency || prefixConcat || suffixConcat) return 'hardcoded "$" currency symbol';}const pattern = DATE_PATTERN.exec(text);diff --git a/evals/model-apps/genpage/lib/jsx-references.js b/evals/model-apps/genpage/lib/jsx-references.jsnew file mode 100644index 000000000..33f4f36ef--- /dev/null+++ b/evals/model-apps/genpage/lib/jsx-references.js@@ -0,0 +1,86 @@+'use strict';++// The text that JSX text or a JSX attribute's string renders: every HTML character reference in it read as the character+// the page compiler decodes it to. JSX decodes character references in both (https://react.github.io/jsx/#sec-jsx-string),+// so `<Text>Hi</Text>` and `placeholder="Hi"` show "Hi" exactly as `<Text>Hi</Text>` does. A JavaScript+// string or template keeps them as written (`{'&'}` shows "&"), so its text is never passed here.+//+// THE COMPILER DECIDES. The bundled SDK compiles a page with TypeScript's `transpileModule` and { target: ES5, module: ES2020,+// jsx: React }, with the compiler the plugin vendors (plugins/model-apps/scripts/lib/typescript-compiler.js: 5.8, the version+// the maker portal compiles with). Its JSX emit decodes, in JSX text and in a JSX attribute's string alike:+// &#<decimal>; &#x<hex>; the code point: `H` and `H` are "H". `H` (a capital X) is not decoded. Past+// U+10FFFF the compile itself fails ("Invalid code point"), so such a page never renders.+// &<name>; the code point its own table gives the name: the HTML 4 names and `apos`, case-sensitive+// (`&` is "&", `&` is not decoded).+// anything else stays as written: `&nosuch;`, `&#;`.+// No table is copied here, so none can drift from the compiler's: each distinct reference is compiled once, as the only+// child of an element and with the SDK's options, and the string the compiler emits for it is read back with the+// compiler's own parser:+// <i>©</i>; → React.createElement("i", null, "\u00A9"); → "©"+// A reference the compile fails on (past U+10FFFF) is left as written: a page that holds one does not compile at all, so+// there is no rendered text to read in its place.+//+// ONE REFERENCE AT A TIME. The compiler finds references with /&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g. REFERENCE matches+// everything that pattern matches, at the same offset and with the same length — an `&`, then only `#` and word+// characters up to the first `;` — and strings it does not (`H`, `&nosuch;`), which the compiler then leaves as+// written. A match of either holds no other `&`, so decoding a text one REFERENCE match at a time gives what compiling+// the whole text gives; tests/jsx-references.test.js holds the two to the same result.+//+// The compiler is loaded lazily, once per process (~200 ms, ~20 MB): only a page whose JSX holds a reference pays for it.+// It fails closed — a vendored compiler that does not match its provenance throws (typescript-compiler.js), and an emit+// of an unexpected shape throws here, rather than reading a reference as some guessed text.+const { loadVendoredTypeScript } = require('../../../../plugins/model-apps/scripts/lib/typescript-compiler.js');++const REFERENCE = /&[#\w]+;/g;+const decoded = new Map();++function decodeReference(reference) {+ const known = decoded.get(reference);+ if (known !== undefined) return known;+ const ts = loadVendoredTypeScript();+ let outputText;+ try {+ // The SDK's compile options, exactly (see the header): the reference is decoded as it is in a page.+ ({ outputText } = ts.transpileModule(`<i>${reference}</i>;`, {+ compilerOptions: { target: ts.ScriptTarget.ES5, module: ts.ModuleKind.ES2020, jsx: ts.JsxEmit.React },+ fileName: 'reference.tsx',+ }));+ } catch (error) {+ // `�` and `�`: String.fromCodePoint refuses the code point (RangeError: Invalid code point 1114112).+ if (!(error instanceof RangeError)) throw error;+ decoded.set(reference, reference);+ return reference;+ }+ const emitted = ts.createSourceFile('reference.js', outputText, ts.ScriptTarget.ES5, false, ts.ScriptKind.JS);+ const statement = emitted.statements[0];+ const call = statement && ts.isExpressionStatement(statement) ? statement.expression : null;+ const child = call && ts.isCallExpression(call) && call.arguments.length === 3 ? call.arguments[2] : null;+ if (!child || !ts.isStringLiteral(child)) throw new Error(`the page compiler emitted no string for the JSX text ${reference}: ${outputText.trim()}`);+ decoded.set(reference, child.text);+ return child.text;+}++/**+ * JSX text, or a JSX attribute's string, as the page renders it.+ * @param {string} text - the source text between the tags, or between the attribute's quotes+ * @returns {string} the text with each character reference decoded as the page compiler decodes it+ */+function renderedText(text) {+ return String(text).replace(REFERENCE, (reference) => decodeReference(reference));+}++/**+ * The character references in JSX text or a JSX attribute's string, in order: each one's offsets in `text` and what it+ * renders (as written where the compiler does not decode it). For a reader that must keep the source offsets.+ * @param {string} text+ * @returns {Array<{ start: number, end: number, shown: string }>}+ */+function characterReferences(text) {+ return [...String(text).matchAll(REFERENCE)].map((m) => ({ start: m.index, end: m.index + m[0].length, shown: decodeReference(m[0]) }));+}++// Whether `text` holds anything the compiler might decode (a page without one never loads the compiler).+const ANY_REFERENCE = new RegExp(REFERENCE.source);+const hasReference = (text) => ANY_REFERENCE.test(String(text));++module.exports = { renderedText, characterReferences, hasReference };diff --git a/evals/model-apps/genpage/lib/page-checks.js b/evals/model-apps/genpage/lib/page-checks.jsindex 3aa2f00cf..864482f85 100644--- a/evals/model-apps/genpage/lib/page-checks.js+++ b/evals/model-apps/genpage/lib/page-checks.js@@ -18,6 +18,7 @@// beside it; a person still judges the rest in the Layer 3 rubric.const { sourceView, jsxElements, jsxTextRuns, declarationSource, matchingClose, withoutComments } = require('./tsx-structure.js');+const { renderedText } = require('./jsx-references.js');const { runtimeEnums } = require('./expectation-evidence.js');const { escapeRe } = require('./source-evidence.js');@@ -367,8 +368,8 @@ function reviewSummaryProblems(content) {// A spread (`{...props}`) may carry a label the page does not show, so it is not reported. A hidden input// (`type="hidden"`) is no field. Returns null when the page has no form control.// A comment is no value, so `{/* hidden */ null}` and `label={/* none */ ''}` are no label either (staticallyEmpty);-// and a character reference is the character it stands for (shownText), so a label written `Title`-// or `&` names its control, while one of ` ` or ` ` alone does not.+// and a character reference is the character the page compiler decodes it to (renderedText), so a label written+// `Title` or `&` names its control, while one of ` ` or ` ` alone does not.const STATIC_EMPTY = /^\s*(?:(['"`])\s*\1|null|undefined|false)\s*$/;// Whether an expression can show nothing once its comments are left out: it is blank, or only '', "", ``, null,// undefined or false. The comments are the ones the plugin's lexer finds (withoutComments), so `'/* x */'` stays a string.@@ -376,24 +377,14 @@ const staticallyEmpty = (expression) => {const bare = withoutComments(expression);return bare.trim() === '' || STATIC_EMPTY.test(bare);};-// JSX text, or a JSX attribute's string, as it is shown, read only to ask whether it shows anything. JSX decodes the-// character references in both (https://react.github.io/jsx/#sec-jsx-string), as TypeScript and Babel do:-// `&#<decimal>;` and `&#x<hex>;` (a lower-case x) up to 0x10FFFF, and the HTML 4 names. A reference is text unless-// the character it stands for is white space: `T` and `T` are a "T" and `&` an "&", while ` ` shows-// nothing, nor do ` `, ` `, ` ` and ` `, the only HTML 4 names of white space. What JSX does not-// decode is shown as written (`&nosuch;`, `T`), so it is text. jsxTextRuns reads every reference as a space-// instead: the translate check counts no reference as a letter, but a label written in references would read as blank.-const SPACE_REFERENCES = new Set(['nbsp', 'ensp', 'emsp', 'thinsp']);-const shownText = (text) => String(text).replace(/&(?:#(\d+)|#x([\da-fA-F]+)|([A-Za-z][A-Za-z\d]*));/g, (reference, decimal, hex, name) => {- if (name !== undefined) return SPACE_REFERENCES.has(name) ? ' ' : reference;- const codePoint = decimal !== undefined ? Number(decimal) : Number.parseInt(hex, 16);- return codePoint <= 0x10ffff ? String.fromCodePoint(codePoint) : reference;-});-const names = (attr) => Boolean(attr) && ((attr.kind === 'string' && shownText(attr.value).trim() !== '')+// A JSX attribute's string shows something when it is not blank as it renders (jsx-references.js): `T` is a "T"+// and `&` an "&", while ` ` and ` ` are white space, which shows nothing; what the compiler does not decode+// (`&nosuch;`, `T`) is shown as written, so it is text.+const names = (attr) => Boolean(attr) && ((attr.kind === 'string' && renderedText(attr.value).trim() !== '')|| (attr.kind === 'expression' && !staticallyEmpty(attr.value)));-// Whether an element's children can show any text: a run of JSX text that is not blank once its character-// references are read (shownText), or an expression container that is not statically empty (staticallyEmpty), at+// Whether an element's children can show any text: a run of JSX text that is not blank as it renders (jsxTextRuns+// decodes its character references), or an expression container that is not statically empty (staticallyEmpty), at// any depth of the markup inside it. `{null}`, `{''}`, `{undefined}`, `{false}`, a container holding only a comment// (`{/* … */}`) and one of them beside a comment (`{/* hidden */ null}`) show nothing, and the tags and attributes// of nested elements are no text:@@ -405,7 +396,7 @@ function childrenShowText(content, element) {const { src, code } = sourceView(content);const from = element.childrenStart;const to = element.childrenEnd;- if (jsxTextRuns(content).some((run) => run.start >= from && run.end <= to && shownText(src.slice(run.start, run.end)).trim() !== '')) return true;+ if (jsxTextRuns(content).some((run) => run.start >= from && run.end <= to && run.text.trim() !== '')) return true;const nested = jsxElements(content).filter((e) => e.start >= from && e.start < to);const inTag = (i) => nested.some((e) => (i >= e.start && i < e.openEnd) || (!e.selfClosing && i >= e.childrenEnd && i < e.end));for (let i = from; i < to; i += 1) {@@ -469,8 +460,13 @@ function searchAndFilterProblems(content) {// shown attribute is a string with a letter (`placeholder="Search"`), or a JSX expression — a child// `{…}` or a shown attribute's value — can RESULT in a string or template with a letter// (displayedLiterals): `{'No contacts'}`, `{rows.length ? 'Contacts' : t('empty')}`, `{error || 'Failed'}`,-// `{`${n} contacts`}`. A string passed to a call (`t('empty')`) is a key, not a result. Character-// references are not letters (` `), nor are punctuation and digits (`({rows.length})`, `{`${n}`}`).+// `{`${n} contacts`}`. A string passed to a call (`t('empty')`) is a key, not a result. JSX text and a shown+// attribute's string are read as the page renders them (jsxTextRuns, renderedText): `<Text>Hi</Text>`,+// `<Text>é</Text>` and `placeholder="Search"` hold letters exactly as `Hi`, `é` and+// `Search` do, while a reference to white space, punctuation or a symbol (` `, `—`, `©`) holds none,+// nor do punctuation and digits (`({rows.length})`, `{`${n}`}`). A JavaScript string or template is not decoded:+// `{'Hi'}` shows those characters as written. A problem quotes the text as it renders, and as written too+// when references make the two differ.// NOT read: a string a function returns to JSX (`renderHeaderCell: () => 'Name'`) or a variable holding one.const SHOWN_ATTRIBUTES = new Set(['label', 'placeholder', 'title', 'aria-label', 'aria-description', 'alt', 'header', 'description', 'content', 'hint', 'validationMessage', 'text']);@@ -521,19 +517,23 @@ function displayedLiterals(text) {// Letters a literal shows: a template's `${…}` parts are values, not text.const shownLetters = ({ quote, text }) => hasLetter(quote === '`' ? text.replace(/\$\{[^}]*\}/g, ' ') : text);+// Text in a problem: as the page renders it, then as written when character references make the two differ,+// hardcoded JSX text "Hi" (written "Hi")+const quoted = (quote, shown, written = shown) => `${quote}${shown.slice(0, 40)}${quote}${written === shown ? '' : ` (written ${quote}${written.slice(0, 40)}${quote})`}`;+function translateCoverageProblems(content) {const { src, code } = sourceView(content);const helper = ['translate', 't'].find((name) => declarationSource(content, name) && new RegExp(`(?<![.\\w$])${name}\\s*\\(`).test(code.replace(new RegExp(`\\b(?:const|let|var|function)\\s+${name}\\b`, 'g'), '')));if (!helper) return ['no translate() helper is declared and called'];const problems = [];for (const run of jsxTextRuns(content)) {- if (hasLetter(run.text)) problems.push(`hardcoded JSX text "${run.text.trim().slice(0, 40)}"`);+ if (hasLetter(run.text)) problems.push(`hardcoded JSX text ${quoted('"', run.text.trim(), src.slice(run.start, run.end).trim())}`);}for (const element of jsxElements(content)) {for (const [name, attr] of element.attrs) {if (!SHOWN_ATTRIBUTES.has(name)) continue;- const literals = attr.kind === 'string' ? [{ quote: '"', text: attr.value }] : attr.kind === 'expression' ? displayedLiterals(attr.value) : [];- for (const literal of literals.filter(shownLetters)) problems.push(`hardcoded ${name} ${literal.quote}${literal.text.slice(0, 40)}${literal.quote} on <${element.name}>`);+ const literals = attr.kind === 'string' ? [{ quote: '"', text: renderedText(attr.value), written: attr.value }] : attr.kind === 'expression' ? displayedLiterals(attr.value) : [];+ for (const literal of literals.filter(shownLetters)) problems.push(`hardcoded ${name} ${quoted(literal.quote, literal.text, literal.written)} on <${element.name}>`);}}for (let i = code.indexOf('{'); i >= 0; i = code.indexOf('{', i + 1)) {@@ -544,7 +544,7 @@ function translateCoverageProblems(content) {const close = matchingClose(code, i);if (close < 0) continue;for (const literal of displayedLiterals(src.slice(i + 1, close)).filter(shownLetters)) {- problems.push(`hardcoded JSX string ${literal.quote}${literal.text.slice(0, 40)}${literal.quote}`);+ problems.push(`hardcoded JSX string ${quoted(literal.quote, literal.text)}`);}}return problems;diff --git a/evals/model-apps/genpage/lib/tsx-structure.js b/evals/model-apps/genpage/lib/tsx-structure.jsindex 904824143..09ba56f9f 100644--- a/evals/model-apps/genpage/lib/tsx-structure.js+++ b/evals/model-apps/genpage/lib/tsx-structure.js@@ -9,7 +9,9 @@// Everything is read from the plugin's lexer view (scripts/lib/source-literals.js `blankLiterals`),// where every comment, string, template, regex body and JSX text run is blanked to spaces and the// offsets stay 1:1 with the source, so a `>`, `{` or `=>` inside a label never moves a bracket count,-// and the original text at the same offsets gives the value back. For example+// and the original text at the same offsets gives the value back. The one question put to the page+// compiler is what a character reference in JSX text or a JSX attribute's string renders+// (jsx-references.js): that is the compiler's own table, not a structure to read. For example// source: <Field label="First name"><Input aria-label="First" value={form.x} /></Field>// view: <Field label="··········"><Input aria-label="·····" value={form.x} /></Field>// source: <Text>Hello {name} world</Text> view: <Text>······{name}······</Text>@@ -23,6 +25,7 @@// a declaration with no semicolon may run on into the next statement.const { blankLiterals, commentRanges } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');+const { renderedText, characterReferences, hasReference } = require('./jsx-references.js');const IDENT_CHAR = /[\w$]/;// Words after which an expression (so an element) may start, as in source-literals.js EXPR_START_WORDS.@@ -177,9 +180,10 @@ function closingTag(code, name, from) {return null;}-// The text a page's JSX shows as written: each run of JSX text, { start, end, text }. HTML character-// references (`&`, `—`) are decoded to a space so that `Review & submit` reads as words-// and ` ` alone reads as none.+// The text a page's JSX shows: each run of JSX text, { start, end, text }, where `text` is the run as it renders —+// every character reference decoded as the page compiler decodes it (jsx-references.js): `Review & submit` reads+// "Review & submit", `Hi` reads "Hi", and ` ` alone reads a no-break space, which is blank. A run that+// holds no reference is its source text.function jsxTextRuns(content) {const { src, code } = sourceView(content);const comment = new Uint8Array(src.length);@@ -200,7 +204,43 @@ function jsxTextRuns(content) {}}if (run) runs.push(run);- return runs.map((r) => ({ ...r, text: src.slice(r.start, r.end).replace(/&(?:#\d+|#x[0-9a-f]+|[a-z]+);/gi, ' ') }));+ return runs.map((r) => ({ ...r, text: renderedText(src.slice(r.start, r.end)) }));+}++// The page's source as it renders where JSX decodes character references — its JSX text and its JSX attributes' strings —+// as { shown, at }: `shown` is the source with each reference there decoded (jsx-references.js), and `shown[k]` comes from+// `content[at[k]]` (every character of a decoded reference from its `&`). JavaScript strings, templates, comments and code+// are copied as they are, since the compiler decodes nothing in them:+// source: <Text>€{total}</Text> {'€'}+// shown: <Text>€{total}</Text> {'€'}+// A page whose JSX holds no reference is shown as written, at the same offsets.+function renderedSource(content) {+ const src = String(content || '');+ const decodedAt = new Map();+ if (hasReference(src)) {+ const ranges = jsxTextRuns(src).map((run) => [run.start, run.end]);+ for (const element of jsxElements(src)) {+ for (const attr of element.attrs.values()) if (attr.kind === 'string') ranges.push([attr.start + 1, attr.start + 1 + attr.value.length]);+ }+ for (const [start, end] of ranges) {+ for (const reference of characterReferences(src.slice(start, end))) decodedAt.set(start + reference.start, { end: start + reference.end, shown: reference.shown });+ }+ }+ let shown = '';+ const at = [];+ for (let i = 0; i < src.length;) {+ const reference = decodedAt.get(i);+ if (reference) {+ shown += reference.shown;+ for (let k = 0; k < reference.shown.length; k += 1) at.push(i);+ i = reference.end;+ } else {+ shown += src[i];+ at.push(i);+ i += 1;+ }+ }+ return { shown, at };}// The source of a declaration named `name` — `const name = …`, `let`/`var`, or `function name(…) {…}` —@@ -471,7 +511,7 @@ function nestedDefinitionProblems(content) {}module.exports = {- sourceView, jsxElements, jsxTextRuns, declarationSource, matchingClose, patternNames,+ sourceView, jsxElements, jsxTextRuns, renderedSource, declarationSource, matchingClose, patternNames,namedFunctions, nestedDefinitionProblems, withoutComments,// Exported so that a check needing a page's function scopes reads them through this reader instead of a second one.functionScopes,diff --git a/evals/model-apps/genpage/tests/jsx-references.test.js b/evals/model-apps/genpage/tests/jsx-references.test.jsnew file mode 100644index 000000000..a13c5e94a--- /dev/null+++ b/evals/model-apps/genpage/tests/jsx-references.test.js@@ -0,0 +1,111 @@+'use strict';++// What a character reference in JSX renders (lib/jsx-references.js), as the evals read it: JSX text and a JSX attribute's+// string decode `H`, `H` and the compiler's named references (`&`, `é`, ` `), so a page shows+// `<Text>Hi</Text>` exactly as it shows `<Text>Hi</Text>`. The decoding is the vendored page compiler's own+// (plugins/model-apps/scripts/lib/typescript-compiler.js, with the SDK's { target: ES5, module: ES2020, jsx: React }): a+// table copied into the evals could drift from it, so these tests hold the reader to the compiler's emit instead.++const { test } = require('node:test');+const assert = require('node:assert/strict');++const { renderedText, characterReferences, hasReference } = require('../lib/jsx-references.js');+const { jsxTextRuns, renderedSource } = require('../lib/tsx-structure.js');+const { loadVendoredTypeScript } = require('../../../../plugins/model-apps/scripts/lib/typescript-compiler.js');++test('a character reference reads as what the page compiler decodes it to, and anything it does not decode as written', () => {+ const cases = [+ ['Hi', 'Hi'],+ ['Save & close', 'Save & close'],+ ['éÉ'²', 'éÉ\'²'],+ ['ال', 'ال'],+ ['😀', '\u{1F600}'],+ ['  ', '\u00a0 '],+ ['—©€', '—©€'],+ // Decoded once, left to right: the "&" that `&` gives does not start another reference.+ ['&amp;', '&'],+ ['&am&p;', '&am&p;'],+ // Not decoded: a capital X, a name the compiler's table lacks or spells differently, an empty or malformed one.+ ['H', 'H'],+ ['&', '&'],+ ['&nosuch;', '&nosuch;'],+ ['&#;&#x;&;& amp;', '&#;&#x;&;& amp;'],+ // Past U+10FFFF the compile itself fails, so no page holding it renders: it is left as written.+ ['�', '�'],+ ['�', '�'],+ ['no reference', 'no reference'],+ ];+ for (const [written, shown] of cases) assert.equal(renderedText(written), shown, written);+ assert.deepEqual(characterReferences('a&b&nosuch;'), [{ start: 1, end: 6, shown: '&' }, { start: 7, end: 15, shown: '&nosuch;' }]);+ assert.equal(hasReference('R&D, a=1&b=2'), false);+ assert.equal(hasReference(' '), true);+});++// The reader decodes one reference at a time; the compiler decodes a whole run of text with one pattern. The two agree on any+// text — a reference's `&` and `;` bound it, and no match of either holds another `&` — and here that is checked against the+// compiler itself, in both places JSX decodes: generated text is compiled as an element's child and as an attribute's string,+// and the strings the compiler emits are read back with its own parser. The samples put each reference inside every other+// one at every cut (`&am` + ` ` + `p;`), and join random runs of references and of the characters they are made of, so+// they hold references that are cut short, run into each other, overlap or are formed across pieces.+test('decoding one reference at a time gives what the page compiler gives for the whole text, in JSX text and in an attribute', () => {+ const ts = loadVendoredTypeScript();+ const REFERENCES = ['&', '&', 'H', 'H', 'H', '😀', '�', ' ', 'é', ''', '²',+ '&nosuch;', '&#;', '&#x;', '&;', '&_x;', '&1;', '&'];+ // No raw piece holds a digit or is made of hex digits alone, so every numeric reference in a sample is a whole one from+ // REFERENCES, within U+10FFFF: no sample fails the compile.+ const RAW = ['&', '&', '&', '#', '#', ';', ';', ';', 'x', 'X', ' ', '_', 'q', 'amp', 'amp', 'AMP', 'nbsp', 'copy', 'eacute'];+ const PIECES = [...RAW, ...REFERENCES];+ let seed = 20261026;+ const random = (n) => {+ seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;+ return (seed >>> 16) % n;+ };+ const samples = [];+ for (const outer of REFERENCES) {+ for (const inner of REFERENCES) {+ samples.push(outer + inner);+ for (let cut = 1; cut < outer.length; cut += 1) samples.push(outer.slice(0, cut) + inner + outer.slice(cut));+ }+ }+ for (let i = 0; i < 400; i += 1) samples.push(Array.from({ length: 1 + random(8) }, () => PIECES[random(PIECES.length)]).join(''));+ // A letter on each side keeps JSX's white-space rules from trimming a sample that starts or ends with a space.+ const source = `[${samples.map((s) => `<i>Z${s}Z</i>, <i a="Z${s}Z" />`).join(', ')}];`;+ const { outputText } = ts.transpileModule(source, {+ compilerOptions: { target: ts.ScriptTarget.ES5, module: ts.ModuleKind.ES2020, jsx: ts.JsxEmit.React },+ fileName: 'samples.tsx',+ });+ // [React.createElement("i", null, "Z&Z"), React.createElement("i", { a: "Z&Z" }), …];+ const emitted = ts.createSourceFile('samples.js', outputText, ts.ScriptTarget.ES5, false, ts.ScriptKind.JS);+ const calls = emitted.statements[0].expression.elements;+ assert.equal(calls.length, samples.length * 2);+ let decoded = 0;+ samples.forEach((sample, i) => {+ const asText = calls[2 * i].arguments[2];+ const asAttribute = calls[2 * i + 1].arguments[1].properties[0].initializer;+ assert.ok(ts.isStringLiteral(asText) && ts.isStringLiteral(asAttribute), sample);+ const shown = renderedText(`Z${sample}Z`);+ assert.equal(shown, asText.text, `JSX text ${sample}`);+ assert.equal(shown, asAttribute.text, `attribute string ${sample}`);+ if (shown !== `Z${sample}Z`) decoded += 1;+ });+ assert.ok(decoded > samples.length / 2, `most samples hold a reference the compiler decodes (${decoded} of ${samples.length})`);+});++test('JSX text and JSX attribute strings render decoded; JavaScript strings, templates and code are kept as written', () => {+ const page = `const P = () => <Text title="Hi">€{total} & {'€'} {\`&\`}</Text>;`;+ assert.deepEqual(jsxTextRuns(page).map((r) => r.text), ['€', '&']);+ const { shown, at } = renderedSource(page);+ assert.equal(shown, `const P = () => <Text title="Hi">€{total} & {'€'} {\`&\`}</Text>;`);+ assert.equal(at.length, shown.length);+ // A decoded reference's characters come from its `&`; every other character comes from where it was written.+ assert.equal(at[shown.indexOf('H')], page.indexOf('H'));+ assert.equal(at[shown.indexOf('€')], page.indexOf('€'));+ assert.equal(at[shown.indexOf(' & ') + 1], page.indexOf('&'));+ for (let k = 0; k < shown.length; k += 1) if (!'H€'.includes(shown[k])) assert.equal(page[at[k]], shown[k], `offset ${k}`);+ const plain = "const P = () => <Text>{'R&D'} a=1&b=2 ©</Text>;";+ const view = renderedSource(plain);+ assert.equal(view.shown, plain);+ assert.deepEqual(view.at, [...plain].map((_, k) => k));+ const scriptOnly = "const P = () => <Text title={'Hi'}>{'€'}{`&`}</Text>; // ©";+ assert.equal(renderedSource(scriptOnly).shown, scriptOnly, 'a reference in a JavaScript string, a template or a comment is not decoded');+});diff --git a/evals/model-apps/genpage/tests/page-expectations.test.js b/evals/model-apps/genpage/tests/page-expectations.test.jsindex 2da5ce365..f9d8fab35 100644--- a/evals/model-apps/genpage/tests/page-expectations.test.js+++ b/evals/model-apps/genpage/tests/page-expectations.test.js@@ -85,7 +85,7 @@ const n = useState<Row>(null);`;const field = jsxElements(page, /^Field$/)[0];assert.ok(field.childrenStart <= inputs[0].start && inputs[0].start < field.childrenEnd);assert.deepEqual(jsxElements(page, /^Row$/), [], 'a type argument is not an element');- assert.deepEqual(jsxTextRuns(page).map((r) => r.text.trim()), ['Hello', 'world more']);+ assert.deepEqual(jsxTextRuns(page).map((r) => r.text.trim()), ['Hello', 'world & more']);assert.deepEqual(patternNames('[{ tasks, loading, error }, setData]'), ['tasks', 'loading', 'error', 'setData']);assert.deepEqual(patternNames('(e: React.DragEvent<HTMLDivElement>, id: string)'), ['e', 'id']);assert.deepEqual(patternNames('{ dataApi, pageInput: input = null }'), ['dataApi', 'input']);@@ -435,3 +435,36 @@ test('eval 13: literal text in a conditional or a template child is hardcoded toassertPass(grade(TRANSLATED, child("rows.length ? t('title') : t('empty')")));assertPass(grade(TRANSLATED, child('error ? t(\'empty\') : `${rows.length}`')));});++// JSX decodes the character references in its text and in an attribute's string (lib/jsx-references.js, the page compiler's+// own decoding), so a page shows `No` as "No" and `é` as "é": text spelled with them is hardcoded exactly as+// its plain spelling is, and what the compiler does not decode (`&nosuch;`, `N`) is shown as written, letters and all.+// A reference to white space, punctuation, a symbol or a digit shows no letter, as the plain character shows none; a+// JavaScript string is not decoded; and a key or a value the page does not show (`t('…')`, `className`, `key`) is no text,+// however it is spelled.+test('eval 13: text spelled with character references is held to the rule as the text it renders', () => {+ const text = (written) => withPage(E13, 'page.tsx', ["<Text>{t('empty')}</Text>", `<Text>${written}</Text>`]);+ const label = (written) => withPage(E13, 'page.tsx', ["<Spinner label={t('title')} />", `<Spinner label="${written}" />`]);+ // A problem quotes at most 40 characters of each spelling, as it always has.+ assertFail(grade(TRANSLATED, text('No contacts.')),+ /hardcoded JSX text "No contacts\." \(written "No cont&"\)$/);+ assertFail(grade(TRANSLATED, text('No')), /hardcoded JSX text "No" \(written "No"\)$/);+ assertFail(grade(TRANSLATED, text('Éé')), /hardcoded JSX text "Éé" \(written "Éé"\)$/);+ assertFail(grade(TRANSLATED, text('ال')), /hardcoded JSX text "ال" \(written "ال"\)$/);+ assertFail(grade(TRANSLATED, text('&nosuch;')), /hardcoded JSX text "&nosuch;"$/);+ assertFail(grade(TRANSLATED, text('No')), /hardcoded JSX text "No"$/);+ assertFail(grade(TRANSLATED, label('Loading')),+ /hardcoded label "Loading" \(written "Loading"\) on <Spinner>$/);+ assertFail(grade(TRANSLATED, label('Loading')), /hardcoded label "Loading" \(written "Loading"\) on <Spinner>$/);+ // Plain letters were hardcoded before and still are, quoted as written when no reference changes them.+ assertFail(grade(TRANSLATED, text('No contacts.')), /hardcoded JSX text "No contacts\."$/);+ assertFail(grade(TRANSLATED, text('Save & close')), /hardcoded JSX text "Save & close" \(written "Save & close"\)$/);+ for (const written of [' ', ' ', '—', '—', '© 2026', '·', '…', '(3)']) {+ assertPass(grade(TRANSLATED, text(`{t('empty')} ${written}`)));+ assertPass(grade(TRANSLATED, label(written)));+ }+ assertPass(grade(TRANSLATED, text("{'No'}")));+ assertFail(grade(TRANSLATED, text("{'&'}")), /hardcoded JSX string '&'$/);+ assertPass(grade(TRANSLATED, text("{t('No')}")));+ assertPass(grade(TRANSLATED, text('<span className="No" key="No">{t(\'empty\')}</span>')));+});diff --git a/evals/model-apps/genpage/tests/phase-expectations.test.js b/evals/model-apps/genpage/tests/phase-expectations.test.jsindex 41f3792a8..957647727 100644--- a/evals/model-apps/genpage/tests/phase-expectations.test.js+++ b/evals/model-apps/genpage/tests/phase-expectations.test.js@@ -592,6 +592,27 @@ test('eval 13: generated text carries no hardcoded currency symbols or date formassertPass(gradeCode(text, page("const mode = isMoney ? 'currency' : 'decimal'; return null;")));});+// JSX decodes the character references in its text and in an attribute's string (lib/jsx-references.js, the page compiler's+// own decoding), so a page shows `€` as "€" and `$` as "$": a symbol or a date format spelled with them is hardcoded+// exactly as its plain spelling is. A JavaScript string is not decoded, so `'€'` shows those characters and no symbol.+test('eval 13: a currency symbol or a date format spelled with character references in JSX is hardcoded too', () => {+ const text = 'Phase 5 (Page Builder): Generated .tsx does NOT hardcode currency symbols or date formats';+ const page = (body) => [{ name: 'page.tsx', content: `export default function GeneratedComponent() {\n ${body}\n}\n` }];+ assertFail(gradeCode(text, page('return <Text>€{total}</Text>;')), /hardcoded currency symbol "\u20ac"/);+ assertFail(gradeCode(text, page('return <Text>{total} £</Text>;')), /hardcoded currency symbol "\u00a3"/);+ assertFail(gradeCode(text, page('return <Input placeholder="¥" />;')), /hardcoded currency symbol "\u00a5"/);+ assertFail(gradeCode(text, page('return <Text>${total}</Text>;')), /hardcoded "\$" currency symbol/);+ assertFail(gradeCode(text, page('return <Text>$100</Text>;')), /hardcoded "\$" currency symbol/);+ assertFail(gradeCode(text, page('return <Text>$100</Text>;')), /hardcoded "\$" currency symbol/);+ assertFail(gradeCode(text, page('return <Text>MM/dd/yyyy</Text>;')), /hardcoded date format "MM\/dd\/yyyy"/);+ // As when written plainly, a "$" with no amount after it is not currency, nor is a reference that is no symbol.+ assertPass(gradeCode(text, page('return <Text>$</Text>;')));+ assertPass(gradeCode(text, page('return <Text>$</Text>;')));+ assertPass(gradeCode(text, page('return <Text>{formatCurrency(total)} & {formatDate(due)} © </Text>;')));+ assertPass(gradeCode(text, page("return <Text>{'€'}{total}</Text>;")));+ assertPass(gradeCode(text, page("const label = '$' + total; return null;")));+});+// --- Eval 15 -----------------------------------------------------------------------------------const E15 = '15-support-tickets-real';diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex 639cd2494..e7f6a1142 100644--- a/plugins/model-apps/.claude-plugin/plugin.json+++ b/plugins/model-apps/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.20.1",+ "version": "2.20.2","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.jsonindex 639cd2494..e7f6a1142 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.20.1",+ "version": "2.20.2","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.mdindex 6a087d660..c2d02f693 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -2835,7 +2835,7 @@ scripts/genpage-plan-semantics.js ← the plan's semantic records, read with no I/O (references/plan-schema.md, "Assumptions, data semantics and lookup metadata"): the written plan (`## Assumptions` / `### A<n>`; per page `#### Data semantics` / `##### R<n>`, `F<n>` and `#### Lookup metadata`) and the approval preview at its own levels (`### Assumptions` first, `### Data Semantics` / `### Lookup Metadata` grouped by page file), every entry rule and cross-reference (an assumption that exists, a quote the requirements hold, the exact `Unattended default:` record), the field-by-field comparison `genpage-plan-provenance.js` gates on, and the check of observed lookups against `get-lookup-metadata.js` evidence. Proves structure and agreement, not entailmentlookup-metadata.js ← `readLookupMetadata(sdk, tables)`: composes the SDK's `fetchEntityMetadata` (complete lookup targets) with `relationship-metadata.js` `readRelationshipsOf(…, 'ManyToOne', cache, { lookupDetails: true })` (every page; `ReferencedAttribute` and `ReferencingEntityNavigationPropertyName`, which the SDK projection drops) into concrete and shared paths; owns no HTTP. Every incomplete read fails the whole read. A table the environment does not have is `LOOKUP_TABLE_NOT_FOUND`, not the SDK's `CONNECTION_ERROR`: the SDK's own read of the table is the first request made for it, and only a 404 of that read (`genpage-sdk.js` `missingTableOf`, as for `genpage.js types`) or of the lookup-details read says so; any other failure keeps the SDK's codecollection-answers.js ← `requireCollectionAnswers(client, { reads, unreadable })`: the HttpClient the SDK is given, with one addition — a 2xx answer to a read `reads(url)` selects must be a collection (`{ value: [...] }`), or the read throws what `unreadable` says; `unreadableAnswer(error)` finds that error, itself or under the SDK's `ConnectionError`. `guardTableLists(client, makeError)` is its policy for the one read of the environment's table list (`/EntityDefinitions?…`, which only `findTables()` makes), and `maker-sdk.js` applies it to every SDK a script makes: the SDK's `findTables()` is `body.value ?? []`, and the bundle is not edited- temp-workspace.js ← the one maker of the plugin's throwaway workspace folders, and the sweep of the ones a KILLED run left (`makeTempWorkspace(prefix)` in place of `fs.mkdtempSync(path.join(os.tmpdir(), prefix))`, at every entry point that makes an SDK workspace — the page backend, `withThrowawaySdk`, `sdkFirst`, build, download, teardown, verify, the `provision-*` scripts, `ai-preflight`, and `solution-settings`' pac scratch folder). A run killed outright (SIGKILL, "End task", a timeout) never reaches its `finally`, and what it left held the source of every page it read and the environment's address (`solution-settings`' pac scratch folder: a settings template, an exported package or a copy of the settings file, which can hold values; the sweep's note says which a folder held, by its prefix). The folders go together in one folder of the plugin's own, `<temp>/power-platform-skills-model-apps` (`-<uid>` after it on POSIX, where the temp folder is shared). That folder is a courtesy, never a reason for a run to fail: it must be a plain folder that only this user can change — POSIX: owned by the user and writable by no one else; Windows, which tells Node no owner and no permissions: a folder this process MAKES is given an explicit access list before anything is put in it — protected, with only this user, the system and the administrators on it, full control inherited by every workspace and record made inside — and read back, and one that cannot be made so is removed and not used; an EXISTING one is judged by its access list and its owner (`windows-folder-acl.js`) and used only if NO entry of the list, an inherit-only one too, lets anyone else add to it, write to it, delete it or take it over, and the user (or the administrators, who own what an elevated process makes) owns it) — and if it cannot be used, or will not take a new folder (mode 0500, an access list that denies this user; a Windows folder that is being removed refuses a new entry — and its access list cannot be got — for a moment, so the attempt is made again after short pauses, up to six in all, and a folder that is still refusing after the last is not asked again by that process), the workspace is made in the plain temp folder exactly as before, unrecorded and never swept, and an error is reported only when that fails too. Each folder is named for the process that made it (`genpage-4242-AbC123`: the prefix, the pid, `mkdtemp`'s six characters; a prefix that does not end in a hyphen is given one, so that the pid always follows the hyphen a sweep reads it from) and holds an owner record `.owner.json` (`process-owner.js`); the first workspace a process makes sweeps that folder (`sweepDeadWorkspaces`) — only a workspace whose owner is PROVABLY gone is removed (the name's pid must have no process — on Linux a pid that runs is looked into too, since the record's start time can show it was handed out again — and the record must agree with the name; the record is read again, and judged again, just before the removal; what is inside is removed first and the record last, and the record leaves the folder only for as long as the folder itself is being removed — it is renamed out to `<folder>.removing`, which Windows allows even while another process holds it open, and moved back if the folder will not go — and if even that is refused it stays beside the folder, whole, and is never WRITTEN into the folder instead, since a write can be cut off and a damaged record beside the whole one would strand the removal; a sweep that is killed between the move and the removal leaves that file and the empty folder, and the next sweep finishes the removal when the file is a record of the folder's own — its name, a record that names the pid in it, an owner that is gone — and the folder is empty or gone, and leaves anything that does not agree as it is — so a removal that fails, half way or at the very end, leaves a folder still known to be dead and found again by the next sweep (Windows with Node 20 keeps a file that was deleted while open, listed, until the holder lets go, and the folder cannot go meanwhile); at most 100 a run, out of 500 entries looked at: the entries are taken in name order and the next run starts after the last one looked at — a cursor, `.sweep-cursor.json`, one small file in the plugin's folder, written whole and there only while the folder holds more than a run looks at — so that a folder whose first 500 entries must be kept does not hide a dead run's workspace, or a removal a kill left half done, behind them for good), and a folder whose name names a pid that RUNS is not even opened (on Linux its record alone is read, for the start time that can show the pid was handed out again; Linux lets a file another process has open be removed) — on Windows a file that is deleted while another process has it open stays in its folder until that process lets go, so a sweep that read a live run's record could make that run's own removal fail — and the run says so on stderr (`⚠ removed 1 temporary workspace left in … by a run that is no longer running`). A run that may still be going, another machine's, a folder with no readable record (a release before this one's, a damaged record), a link, a file: left as they are. **A path inside a workspace that is given to a program of another make makes the workspace LENT, when it is made** (`makeTempWorkspace(prefix, { lent: true })`, as `solution-settings`' `templateThroughPac` does for pac): on POSIX such a program outlives a run that is killed, so the record — written ONCE, whole, to a file of its own and renamed into place, and never written again — says `lent: true`, and a sweep never takes a lent workspace because its maker is gone: only when its maker is gone AND it is old, neither the folder nor its record written to for seven days (`LENT_KEEP_MS`; pac gets an hour at most). Nothing follows the program or changes the record once it has started (a record that is changed later can be unreadable at that moment), and a record that is unreadable keeps the folder. Every caller that hands a path in a workspace to another program decides that when it makes the workspace. The plugin's folder is removed when the process ends with nothing in it, so a normal run leaves the temp folder as it found it — and so does a run that is cut short by `process.exit` or an error nothing catches (the `exit` event): it first removes the workspaces it made and did not lend that are still there, by the steps of a sweep (what is inside first, the record last), since it never reached the `finally` that would have; a LENT workspace is never taken at the end of the run that lent it, and what is not its own is never touched (`rmdir` takes the folder only when it is empty, and a run that loses the folder between making it and making its workspace in it makes it again); the one caller that removes a lent workspace itself, `solution-settings`, does it in a cleanup it registers with `lib/exit-cleanup.js`, which runs after the maker's listener has found the workspace still in the folder and left the folder, so that cleanup calls `pruneWorkspaceParents()` once its workspace is gone — the same `rmdir`, so a run that is cut short while pac runs leaves no empty plugin folder behind (a signal included: it ends a POSIX process with no `exit` event, and that cleanup is what runs). A POSIX signal is NOT one of these ends — its default action ends the process with no JavaScript run, and a listener, which would, replaces that default action in every script that makes a workspace (a process blocked in a synchronous `az` or `pac` call would no longer end when signalled, and the signal would have to be raised again to keep its status) — so a run that is signalled leaves its workspace for the next run's sweep, as a killed one does; a folder that cannot be used or a record that cannot be written costs the sweep, never the run. The sweep reads only the plugin's own folder, never the temp folder, which can hold hundreds of thousands of entries+ temp-workspace.js ← the one maker of the plugin's throwaway workspace folders, and the sweep of the ones a KILLED run left (`makeTempWorkspace(prefix)` in place of `fs.mkdtempSync(path.join(os.tmpdir(), prefix))`, at every entry point that makes an SDK workspace — the page backend, `withThrowawaySdk`, `sdkFirst`, build, download, teardown, verify, the `provision-*` scripts, `ai-preflight`, and `solution-settings`' pac scratch folder). A run killed outright (SIGKILL, "End task", a timeout) never reaches its `finally`, and what it left held the source of every page it read and the environment's address (`solution-settings`' pac scratch folder: a settings template, an exported package or a copy of the settings file, which can hold values; the sweep's note says which a folder held, by its prefix). The folders go together in one folder of the plugin's own, `<temp>/power-platform-skills-model-apps` (`-<uid>` after it on POSIX, where the temp folder is shared). That folder is a courtesy, never a reason for a run to fail: it must be a plain folder that only this user can change — POSIX: owned by the user and writable by no one else; Windows, which tells Node no owner and no permissions: a folder this process MAKES is given an explicit access list before anything is put in it — protected, with only this user, the system and the administrators on it, full control inherited by every workspace and record made inside — and read back, and one that cannot be made so is removed and not used; an EXISTING one is judged by its access list and its owner (`windows-folder-acl.js`) and used only if NO entry of the list, an inherit-only one too, lets anyone else add to it, write to it, delete it or take it over, and the user (or the administrators, who own what an elevated process makes) owns it) — and if it cannot be used, or will not take a new folder (mode 0500, an access list that denies this user; a Windows folder that is being removed refuses a new entry — and its access list cannot be got — for a moment, so the attempt is made again after short pauses, up to six in all, and a folder that is still refusing after the last is not asked again by that process), the workspace is made in the plain temp folder exactly as before, unrecorded and never swept, and an error is reported only when that fails too. On Windows a run HOLDS the folder while it judges it (three programs, about a second) — an empty file of its own, `.hold-<machine>-<pid>-<6 hex>`, put in once the access list of a folder it made is set and removed once its workspace is in it and recorded — because the end of every run that leaves nothing in the folder removes it (`rmdir`), and with several runs starting and ending at once the folder kept being removed and made again under each other's judgement until a run ran out of attempts and went to the plain temp folder; `rmdir` refuses a folder with a hold in it, and a sweep on Windows removes the hold of a run that is gone — only a hold carrying its own machine tag (`<machine>` is eight hex digits of a hash of the host name, as an owner record names its host), since a temp folder can be shared between machines and a pid says nothing on another (two host names can, rarely, share a tag; on a temp folder they share, the old fallback can then return); a POSIX sweep takes nothing for a hold. Each folder is named for the process that made it (`genpage-4242-AbC123`: the prefix, the pid, `mkdtemp`'s six characters; a prefix that does not end in a hyphen is given one, so that the pid always follows the hyphen a sweep reads it from) and holds an owner record `.owner.json` (`process-owner.js`); the first workspace a process makes sweeps that folder (`sweepDeadWorkspaces`) — only a workspace whose owner is PROVABLY gone is removed (the name's pid must have no process — on Linux a pid that runs is looked into too, since the record's start time can show it was handed out again — and the record must agree with the name; the record is read again, and judged again, just before the removal; what is inside is removed first and the record last, and the record leaves the folder only for as long as the folder itself is being removed — it is renamed out to `<folder>.removing`, which Windows allows even while another process holds it open, and moved back if the folder will not go — and if even that is refused it stays beside the folder, whole, and is never WRITTEN into the folder instead, since a write can be cut off and a damaged record beside the whole one would strand the removal; a sweep that is killed between the move and the removal leaves that file and the empty folder, and the next sweep finishes the removal when the file is a record of the folder's own — its name, a record that names the pid in it, an owner that is gone — and the folder is empty or gone, and leaves anything that does not agree as it is — so a removal that fails, half way or at the very end, leaves a folder still known to be dead and found again by the next sweep (Windows with Node 20 keeps a file that was deleted while open, listed, until the holder lets go, and the folder cannot go meanwhile); at most 100 a run, out of 500 entries looked at: the entries are taken in name order and the next run starts after the last one looked at — a cursor, `.sweep-cursor.json`, one small file in the plugin's folder, written whole and there only while the folder holds more than a run looks at — so that a folder whose first 500 entries must be kept does not hide a dead run's workspace, or a removal a kill left half done, behind them for good), and a folder whose name names a pid that RUNS is not even opened (on Linux its record alone is read, for the start time that can show the pid was handed out again; Linux lets a file another process has open be removed) — on Windows a file that is deleted while another process has it open stays in its folder until that process lets go, so a sweep that read a live run's record could make that run's own removal fail — and the run says so on stderr (`⚠ removed 1 temporary workspace left in … by a run that is no longer running`). A run that may still be going, another machine's, a folder with no readable record (a release before this one's, a damaged record), a link, a file: left as they are. **A path inside a workspace that is given to a program of another make makes the workspace LENT, when it is made** (`makeTempWorkspace(prefix, { lent: true })`, as `solution-settings`' `templateThroughPac` does for pac): on POSIX such a program outlives a run that is killed, so the record — written ONCE, whole, to a file of its own and renamed into place, and never written again — says `lent: true`, and a sweep never takes a lent workspace because its maker is gone: only when its maker is gone AND it is old, neither the folder nor its record written to for seven days (`LENT_KEEP_MS`; pac gets an hour at most). Nothing follows the program or changes the record once it has started (a record that is changed later can be unreadable at that moment), and a record that is unreadable keeps the folder. Every caller that hands a path in a workspace to another program decides that when it makes the workspace. The plugin's folder is removed when the process ends with nothing in it, so a normal run leaves the temp folder as it found it — and so does a run that is cut short by `process.exit` or an error nothing catches (the `exit` event): it first removes the workspaces it made and did not lend that are still there, by the steps of a sweep (what is inside first, the record last), since it never reached the `finally` that would have; a LENT workspace is never taken at the end of the run that lent it, and what is not its own is never touched (`rmdir` takes the folder only when it is empty, and a run that loses the folder between making it and making its workspace in it makes it again); the one caller that removes a lent workspace itself, `solution-settings`, does it in a cleanup it registers with `lib/exit-cleanup.js`, which runs after the maker's listener has found the workspace still in the folder and left the folder, so that cleanup calls `pruneWorkspaceParents()` once its workspace is gone — the same `rmdir`, so a run that is cut short while pac runs leaves no empty plugin folder behind (a signal included: it ends a POSIX process with no `exit` event, and that cleanup is what runs). A POSIX signal is NOT one of these ends — its default action ends the process with no JavaScript run, and a listener, which would, replaces that default action in every script that makes a workspace (a process blocked in a synchronous `az` or `pac` call would no longer end when signalled, and the signal would have to be raised again to keep its status) — so a run that is signalled leaves its workspace for the next run's sweep, as a killed one does; a folder that cannot be used or a record that cannot be written costs the sweep, never the run. The sweep reads only the plugin's own folder, never the temp folder, which can hold hundreds of thousands of entriesprocess-owner.js ← who made a lock or a workspace, and whether that process is gone — one place for the build lock and the pages lock (`app-operation-lease.js`), the recovery records' writer lease (`record-lease.js`), the temporary workspaces and the snapshot lease's liveness check (`processAlive`, as it always was). `ownerStamp()` is what a maker records (pid, time, host, platform, and on Linux the pid namespace and the process's start time from `/proc`); `ownerState(stamp)` answers `gone` only when the stamp was made on this machine, by this kind of system, in this pid namespace, and no process has the pid (ESRCH) — or, on Linux, a zombie or a process with another start time has it (the pid was handed out again) — `alive` for a process that runs (this one included) and `unknown` for anything else: another machine, a stamp that is missing, damaged or not understood. **On Linux a pid is only a name inside its pid namespace, so the stamp AND the reader must both name theirs (`pid:[…]`, readable and well formed) and name the same one: a side that cannot (a hidden `/proc`: a container, hidepid, a sandbox), or two that cannot, is `unknown`, never "the same pid space".** A recorded `start` that is not `<boot id>:<ticks>` — empty, cut short, damaged inside a record that is still valid JSON — makes the record untrusted (`isOwnerStamp`: kept), and a start read from `/proc` that is not well formed is not compared: only two well-formed starts that differ show a pid handed out again, in the self-pid branch too. `ownerState` is a fact about the maker and only that: a workspace that was handed to a program that outlives its maker is kept by its age instead (`temp-workspace.js`, `lent`). Every doubt keeps; where no start time is cheap to read (Windows, macOS) a pid given to another process makes a dead run look alive, which keeps its lock or folder (the state of things before this module)windows-folder-acl.js ← who can change a folder on Windows, where Node reports no owner and no permissions, and the making of a folder that only this user can: `windowsFolderIsPrivate(folder)` saves the folder's access list with `icacls <folder> /save` (SDDL: SIDs, in every language, not names) and reads the user's SID with `whoami /user /fo csv /nh`, both started through `process-runner.js` with System32 first on PATH, and answers `{ ok, reason, owner? }` — private only when NO entry that grants a right to add to the folder, remove from it, delete it, write its attributes or extended attributes, change who may or take it over names anyone but this user, the system or the administrators (an INHERIT-ONLY entry counts too: it does not apply to the folder, but it is what every workspace and every owner record made in it is given; denials and audits grant nothing; SDDL writes the machine's own Administrator and Guest accounts as the aliases `LA` and `LG`, which are the user's own only for the user whose account that is, as a CI runner's renamed built-in Administrator is; an audit list after the access list, as Windows' own folders carry, is read and ignored) AND the folder is owned by this user or the administrators — whoever owns a folder can rewrite its list, so a list that names only the user does not make a foreign folder the user's. The owner is the one thing `icacls` cannot print (`/save` stores the list and nothing else), so it is read with PowerShell (`[IO.Directory]::GetAccessControl(folder, Owner)`, a SID; the folder goes in through the environment and the script is passed encoded) — half a second, which is why it is the last thing asked (a folder the list has refused never starts it), and PowerShell that cannot run is "not private". The administrators are accepted as owner because a process that runs elevated (a CI runner is one) owns what it makes through that group by default, and the list trusts them anyway. A list that icacls ran and could not save — Windows is removing the folder, which cannot be opened meanwhile — is `unreadable`, a "no" that `temp-workspace.js` does not keep: it asks again after a pause, and drops an answer about a folder that was replaced while it was being judged; whatever else cannot be read, run or understood is not private, and `temp-workspace.js` then makes its workspace in the plain temp folder as before. `makeWindowsFolderPrivate(folder)` is for a folder this process has just made: `icacls <folder> /inheritance:r /grant:r *<user>:(OI)(CI)F *S-1-5-18:(OI)(CI)F *S-1-5-32-544:(OI)(CI)F` replaces its list, and the list is read back and must be exactly that — protected, nothing inherited, three grants, full control for the userpower-apps-service-client.js ← the HttpClient for the SDK's connection and connector reads: GET only, https only, a host allowlist that is exactly the hosts the SDK's connectivity code calls, redirects never followed, the Azure CLI token for the Power Apps service read only for a request that passed and never in a message, a body, a header or a key the service answers with (it is scrubbed, in whole and by part)@@ -2875,7 +2875,7 @@ scripts/pageref-resolver.js ← PAGEREF_<key> → GenPageId nav resolverpage-manifest.js ← durable <app>_pagemanifest read/writesitemap-pages.js ← pure GenPageId extractors (the TEXT readers `sitemapGenPages` / `sitemapGenPageIds`, which only refuse or report; `navigationGenPageIds`, which reads the navigation ELEMENTS through `strict-xml.js` and is what a page is deleted by) + fail-closed fetchSitemap MEMBERSHIP reader + navigationProof (page ownership proof, read as navigation, from either app layer — or from the saved layer alone, for an app that was never published and so has no published one) + cross-app scan (every other app's published AND saved navigation — the saved layer in one request — and the apps that were never published, listed in one more; a never-published app with no sitemap component is looked up by the name its sitemap carries); a read that fails is reported by value with the error itself as a non-enumerable `cause` (`withCause`), for the halt raised around it to decide from- strict-xml.js ← `readXmlElements(xml, wanted, { spans?, maxDepth?, elementOnly? })`: ONE strict reader of ONE XML document, in one pass, no dependency — comments, CDATA sections, processing instructions and attribute values are data, never elements; anything that is not exactly one well-formed document (or that the SDK's own xmldom would read differently) is `{ ok:false, detail }` with no element at all. `maxDepth` refuses a document nested deeper than the caller allows (each answered element carries its ancestors' names, so depth costs its square), `elementOnly(name)` refuses text, CDATA, comments and instructions directly inside the elements it names; without them nothing changes. With `spans`, each element also says where it is in the text (`start`, `end`), for `formxml-layers.js`. `tests/strict-xml-oracle.test.js` holds it to xmldom over a generated corpus+ strict-xml.js ← `readXmlElements(xml, wanted, { spans?, maxDepth?, elementOnly? })`: ONE strict reader of ONE XML document, in one pass, no dependency — comments, CDATA sections, processing instructions and attribute values are data, never elements; anything that is not exactly one well-formed document (or that the SDK's own xmldom would read differently) is `{ ok:false, detail }` with no element at all. `maxDepth` refuses a document nested deeper than the caller allows (each answered element carries its ancestors' names, so depth costs its square; the paths are built only once the document has been read to its end, so a document that is refused costs time in proportion to its length), `elementOnly(name)` refuses text, CDATA, comments and instructions directly inside the elements it names; without them nothing changes. With `spans`, each element also says where it is in the text (`start`, `end`), for `formxml-layers.js`. `tests/strict-xml-oracle.test.js` holds it to xmldom over a generated corpusformxml-layers.js ← `sameFormXmlAcrossLayers(published, saved, versions?)`: whether a systemform's saved FormXML (RetrieveUnpublished) is its published one in the languages the published read carries — a caption in another language is set aside, anything else that differs (and a FormXML that is not one well-formed document, read by `strict-xml.js`) is a change; and, for a published read that carries more than one language (the read of a user whose own language is the organization's second one, which orders and words the captions its own way) whose `versions` say the published row and the saved read answer the same `@odata.etag` (the saved layer has not been written since the publish), in everything but the captions, of any language; what verify's dashboard check decides "published" byzip-read.js ← `readZipEntry(archive, name, { maxArchiveBytes?, maxEntryBytes? })`: ONE strict reader of ONE entry of a ZIP archive held in memory, no dependency (`node:zlib`). The archive has to agree with itself — end record, central directory, local header, sizes, CRC-32 — and its entries have to lie end to end, from the first byte to the central directory (each the local header, the data, and the data descriptor its flags announce, with the central directory's numbers), the deflate stream filling its data exactly; ZIP64, an archive in parts, an encrypted entry, a name twice, data that inflates past the size the archive declares, bytes that belong to no entry: a `ZipReadError`. The data is found from the LOCAL header's own lengths (the platform's export has an extra field there that its central directory does not). What `translation-labels.js` opens a translation export withtranslation-labels.js ← the captions of a solution's forms in EVERY provisioned language, from ONE translation export: `readTranslationLabels(sdk.dataverse, solutionName)` → `{ ok: true, languages, lookup(table, id) }` or `{ ok: false, reason }` (it never throws); `parseTranslationWorkbook(xml)` reads `CrmTranslations.xml`, an Excel 2003 XML spreadsheet, with `strict-xml.js` and rules of its own (the `Localized Labels` sheet is validated whole first — every element and attribute the platform's, in its place — and a row, cell, type or element it does not recognise makes the WHOLE workbook unreadable; depth, name length and element counts are bounded while it reads); `settleCaption(export, { entity, id, lcid, text })` judges one caption (same, different, or unsettled with the reason); `isTranslationExport(method, url)` is the `sendOnce` rule that keeps the request from being sent twice. What `verify-spec.js` compares a tab's or a section's caption with in a language the form's own read does not carry (`readerFor`'s `translationLabels`)@@ -4259,10 +4259,12 @@ NODE20_BIN=/path/to/node20/bin node scripts/run-tests.js --with-sdk /path/to/powmakes. `scripts/tests/helpers/temp-dirs.js` (`makeTempDir`) is the shared way — require it at the topof the test file, and the folders it makes are removed after the file's last test. Every test file of therun shares that folder, and so the folder `lib/temp-workspace.js` makes the throwaway workspaces in, which- each process removes when it ends with nothing left in it; on Windows a folder being removed refuses a new- workspace for a moment, and under load for longer than the maker waits, so the workspace goes to the plain- temporary folder, as the code allows. A test file that checks WHERE a workspace is made therefore requires- `scripts/tests/helpers/own-temp-folder.js` first: it then works in a temporary folder of its own inside the+ each process removes when it ends with nothing left in it. On Windows judging that folder takes about a+ second, and a run holds it meanwhile (`lib/temp-workspace.js`, A RUN HOLDS THE FOLDER): before it did, the+ ends of other test processes kept removing it under the judgement, and the workspace went to the plain+ temporary folder, as the code allows. A test file that checks WHERE a workspace is made still requires+ `scripts/tests/helpers/own-temp-folder.js` first, so that nothing another process does in that folder is part+ of what it checks: it then works in a temporary folder of its own inside thesuite's, which the end of the file removes when it is empty (and leaves, for the run to name, when it is not).That folder's name is short whatever the file is called — `own-<first letter of each word of the file'sname>-<4 hex digits of a hash of it>-<random>`, 22 characters at most — because a workspace is two levelsdiff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex 32b36379a..7a6b6ddf1 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -5,6 +5,15 @@ All notable changes to the **model-apps** plugin.Entries are deliberately short: what changed and why it matters to you. The reasoning,evidence and trade-offs behind a change live in its PR, in `docs/`, or in the linked issue.+## [2.20.2]++The bundled SDK is unchanged (power-platform-ux a3443479).++### Fixed++- **Scripts run side by side on Windows keep their temporary workspaces where cleanup finds them.** A race could leave an+ interrupted run's workspace outside the plugin's temp folder, where it was never removed.+## [2.20.1]The bundled SDK is unchanged (power-platform-ux a3443479).diff --git a/plugins/model-apps/scripts/lib/strict-xml.js b/plugins/model-apps/scripts/lib/strict-xml.jsindex 32e0d2fa4..ac9f7a09f 100644--- a/plugins/model-apps/scripts/lib/strict-xml.js+++ b/plugins/model-apps/scripts/lib/strict-xml.js@@ -143,7 +143,7 @@ function position(xml, at) {* → { ok: false, detail: 'a second root element (a document has exactly one), at line 1, column 11' }** `path` is the names of the element's ancestors, outermost first, joined with "/" ('' for the root element); no name has a "/", so it says where the element- * is without ambiguity. `attrs` has no prototype and holds each attribute's value as an XML parser gives it: references decoded, and a tab, a line end or a+ * is without ambiguity. The paths are built after the document has been read to its end, so a document that is refused costs time in proportion to its length. `attrs` has no prototype and holds each attribute's value as an XML parser gives it: references decoded, and a tab, a line end or a* carriage return in the text of the value (not one written as `	`) a space (https://www.w3.org/TR/xml/#AVNormalize). Names are exact — XML is case-sensitive —* and a namespace prefix is part of the name.*@@ -192,6 +192,11 @@ function scan(xml, wanted, spans, maxDepth, elementOnly) {const elements = [];// The names of the elements that are open, outermost first, and the default namespace each is in (a `xmlns="…"` attribute sets it, and an element inherits it).const open = [];+ // The same open elements as a chain, innermost first, so that an answered element can say where it is without the path being built while the document may still be refused: a+ // document of n unclosed `<a>` and every element asked for would cost n²/2 characters of paths, all thrown away when the end of the text is reached. The paths are built once the+ // document has been read to its end (pathOf), so a refusal costs time in proportion to the text read.+ let innermost = null;+ const answeredAt = [];const defaultNamespace = [];// With `elementOnly`, beside `open`: whether each open element holds elements and white space only.const openElementOnly = [];@@ -308,9 +313,11 @@ function scan(xml, wanted, spans, maxDepth, elementOnly) {}let answered = null;if (wanted(name)) {- answered = { name, path: open.join('/'), attrs };+ // `path` keeps its place among the keys (name, path, attrs, start, end) and is filled in at the end of the document.+ answered = { name, path: '', attrs };if (spans) answered.start = from;elements.push(answered);+ answeredAt.push(innermost);}if (selfClosing) {if (spans && answered) answered.end = p;@@ -318,6 +325,7 @@ function scan(xml, wanted, spans, maxDepth, elementOnly) {} else {noteWhatTheSdkParserMisreads(from, p - 1, name, attrs);open.push(name);+ innermost = { name, parent: innermost, path: undefined };if (elementOnly) openElementOnly.push(!!elementOnly(name));if (spans) openAnswered.push(answered);state = CONTENT;@@ -358,6 +366,7 @@ function scan(xml, wanted, spans, maxDepth, elementOnly) {const expected = open[open.length - 1];if (found[0] !== expected) throw new Refusal(from, `closing tag </${found[0]}> where </${expected}> is expected`);open.pop();+ innermost = innermost.parent;defaultNamespace.pop();openElementOnly.pop();if (spans) {@@ -456,7 +465,31 @@ function scan(xml, wanted, spans, maxDepth, elementOnly) {if (state === PROLOG) throw new Refusal(n, 'there is no root element');if (state === CONTENT) throw new Refusal(n, `the element <${open[open.length - 1]}> is never closed`);if (misread) throw misread;+ for (let i = 0; i < elements.length; i += 1) elements[i].path = pathOf(answeredAt[i]);return elements;}-module.exports = { readXmlElements, XML_PREDEFINED };+// The names of `node` and of its ancestors, outermost first, joined with "/" ('' for no node). The path of a node is kept once built, so that the next element+// asked for under it adds one name to a path that is there; a node that is not asked for under is never given one, so an answer that is one element deep in a+// deep document costs one walk up, as it always did.+function pathOf(node) {+ if (node === null) return '';+ if (node.path === undefined) {+ const names = [];+ let ancestor = node;+ while (ancestor !== null && ancestor.path === undefined) {+ names.push(ancestor.name);+ ancestor = ancestor.parent;+ }+ const own = names.reverse().join('/');+ node.path = ancestor === null ? own : `${ancestor.path}/${own}`;+ work.pathCharacters += node.path.length;+ }+ return node.path;+}++// What the reader has done that grows with the depth of a document, for the tests that hold it to "a refusal costs what was read, not what the answer would have+// held": the characters of paths built. It is a count, not a clock, so it says the same on a loaded machine and on an idle one.+const work = { pathCharacters: 0 };++module.exports = { readXmlElements, XML_PREDEFINED, work };diff --git a/plugins/model-apps/scripts/lib/temp-workspace.js b/plugins/model-apps/scripts/lib/temp-workspace.jsindex a58af7306..eeb9e9fc4 100644--- a/plugins/model-apps/scripts/lib/temp-workspace.js+++ b/plugins/model-apps/scripts/lib/temp-workspace.js@@ -31,6 +31,20 @@// or take it over. The answer is asked once per folder and process. A folder that Windows is still removing — the last handle on it has not closed — refuses a new// entry and cannot be read for a moment: the attempt is made again after short pauses, and one that is still refusing after the last is not used (WAITS_MS).//+// A RUN HOLDS THE FOLDER WHILE IT JUDGES IT (Windows). Asking whether a folder that is there is private starts three programs (lib/windows-folder-acl.js) and takes about a second — more on a busy machine —+// and the answer is about the folder that was asked about (its file id). Every run that ends with nothing left in the plugin's folder removes it (THE END OF A RUN, below), so while one run was being told about the+// folder, another that ended took it away and a third made it again: the answer was about a folder that was no longer there, the run asked again about the new one, and that was replaced in its turn. With several+// runs starting and ending at once — an agent runs scripts side by side, a test suite runs dozens — the answers kept coming too late, and a run that had asked MAKE_ATTEMPTS times made its workspace in the plain+// temp folder, unrecorded and never swept (measured on one machine: about one run in twenty with three at a time, one in three with twelve; no folder refused an entry). So a run HOLDS the folder from the moment+// it has made or found it until its workspace is in it: an empty file of its own, `.hold-<machine>-<pid>-<6 hex>`, which the `rmdir` of a run that ends refuses to remove (ENOTEMPTY), as it refuses a workspace. The folder+// cannot go while it is judged, so the answer is about the folder the workspace is then made in. The hold is made after the access list of a folder this run made is set (nothing is put in a folder before that),+// and only in a plain folder (not through a link). It holds nothing, and is removed before makeTempWorkspace returns, whatever happened — on success only once the workspace is recorded, since its+// removal can wait on a scanner and a run killed in that wait must leave a workspace that a sweep can take; a hold that cannot be made leaves the run as it was without one (a full+// disk, a folder that takes no file), and one a run was killed while holding is removed by a later sweep once that run's pid is gone, so that the folder can go when it is empty. A pid means something only on+// the machine that gave it out, and a temp folder can be shared between machines (a network share, a profile that roams), so a hold names its machine — eight hex digits of a hash of the host name, the host+// an owner record names (lib/process-owner.js) — and a sweep takes only a hold of its own machine: one of another machine stays, and so does every hold when a sweep cannot read its own host name. On POSIX the question is one+// lstat, answered before anything could change: nothing is held, and a sweep there takes nothing for a hold (a file of that shape is an entry like any other, as it always was).+//// A WORKSPACE LENT TO ANOTHER PROGRAM (`makeTempWorkspace(prefix, { lent: true })`). A path inside a workspace is sometimes given to a program of another make — pac, writing its settings file into the// scratch folder of solution-settings.js. That program is not the run: on POSIX it outlives a run that is killed (SIGKILL, an agent's timeout), and a sweep that takes the folder because// the run is gone would remove it from under a program that is still writing in it. Nothing here follows such a program — a record that is changed after the program has started can be@@ -72,7 +86,7 @@// * A workspace of this process is named for its pid and six random characters, so no other run makes, opens or removes it. A sweep never opens a folder whose pid runs (on Linux it reads its record, and a run that is going// is "alive" there), and this process runs until the last listener of its `exit` event has returned.// * `rmdir` removes a folder only if it is empty, in one step. Another run's workspace in the plugin's folder — one that is there, or one `mkdtemp` is making that moment, which creates its entry in one step — makes it refuse-// (ENOTEMPTY), and the folder stays. A run that has made the folder and not yet its workspace in it has an empty folder for a moment, and CAN lose it: its `mkdtemp` then fails with ENOENT, which makeTempWorkspace answers by+// (ENOTEMPTY), and the folder stays; so does the hold of a run that is judging the folder (Windows: A RUN HOLDS THE FOLDER, above). A run that has made the folder and not yet its workspace in it has an empty folder for a moment, and CAN lose it: its `mkdtemp` then fails with ENOENT, which makeTempWorkspace answers by// making the folder again (MAKE_ATTEMPTS times), and on Windows a folder that is being removed refuses for a moment instead, which it answers by waiting (WAITS_MS). So no run fails for it; the cost is one more mkdir.// * The workspaces go first, so that the folder is looked at after this process has taken what is its own out of it.// What is NOT covered is a POSIX signal. The default action of SIGINT, SIGTERM and SIGHUP ends the process at once, and the `exit` event never runs: what the run left stays for the next run's sweep, and the folder goes with the next@@ -87,6 +101,7 @@// folder, written whole, there only while the folder holds more than a sweep looks at); the next sweep — in this process or a later one — starts after that name and wraps round to the first. Every entry is looked at within// ceil(entries / MAX_EXAMINED) sweeps, whatever the first of them are. The cursor says where to start and nothing else: it cannot make a sweep take what it would not have taken, one that is missing, unreadable or not what was written// starts at the first entry, and the name in it is only ever compared with the names in the folder.+const crypto = require('node:crypto');const fs = require('node:fs');const os = require('node:os');const path = require('node:path');@@ -102,6 +117,15 @@ const REMOVING_SUFFIX = '.removing';// that was killed while it wrote the cursor leaves. Nothing else is the sweep's own: a file or a folder that only looks like these is an entry like any other, and is never removed.const CURSOR_FILE = '.sweep-cursor.json';const isCursorName = (name) => name === CURSOR_FILE || (name.startsWith(`${CURSOR_FILE}.`) && /^\.\d+\.[a-z0-9]*\.tmp$/.test(name.slice(CURSOR_FILE.length)));+// What a run puts in the plugin's folder while it judges it (Windows: A RUN HOLDS THE FOLDER, at the top of this file): an empty FILE named for the machine and the run — `.hold-1f2e3d4c-4242-a1b2c3`: the+// machine (machineOf), the pid and six hex digits — so a sweep can tell, from the name alone, whether the run that made it is gone. A workspace is a folder and a removal ends in `.removing`, so neither is+// ever taken for a hold.+const HOLD_PREFIX = '.hold-';+const HOLD_NAME = /^\.hold-([0-9a-f]{8})-\d{1,10}-[0-9a-f]{6}$/;+const isHoldName = (name) => HOLD_NAME.test(name);+// The machine a host name is, as a hold's name says it: eight hex digits of its SHA-256. A hash and not the name, since a host name is not a safe part of a file name everywhere; it is only ever+// compared, never read back. Null for a host name that could not be read: no machine can be told from it.+const machineOf = (host) => (typeof host === 'string' && host !== '' ? crypto.createHash('sha256').update(host).digest('hex').slice(0, 8) : null);// What a prefix may be: a name, never a path. A prefix that is not one would put the folder outside the plugin's own.const SAFE_PREFIX = /^[A-Za-z0-9._-]+$/;// A record, or the cursor, is a few hundred bytes at most. One that is much larger is not one.@@ -181,7 +205,9 @@ function checkParent(parent, deps, { created = false } = {}) {if (!verdict.ok) throw new Error(`${parent} can be changed by others: ${verdict.reason}`);}-function ensureParent(parent, deps) {+// Makes the plugin's folder, or finds it, and judges it — holding it meanwhile where judging takes long (Windows: A RUN HOLDS THE FOLDER, at the top of this file). Answers the hold, which the caller releases+// once its workspace is in the folder (null when nothing is held); a folder that is refused throws, with the hold already released.+function ensureParent(parent, deps, stamp) {const fsx = deps.fs || fs;// Not `recursive`: a temp folder that is not there is the failure it always was (ENOENT, from the plain call this falls back to), not a folder this makes.let created = false;@@ -195,7 +221,53 @@ function ensureParent(parent, deps) {// workspace and every owner record the sweep will believe is then made inside it and inherits that grant. So before anything is put in it the folder is given an access list of its own — only// this user, the system and the administrators, protected from the folder above — and the list is read back (lib/windows-folder-acl.js).if (created && uidOf(deps) === null) protectNewParent(parent, deps);- checkParent(parent, deps, { created });+ const hold = holdParent(parent, deps, stamp);+ try {+ checkParent(parent, deps, { created });+ } catch (e) {+ releaseHold(hold, deps);+ throw e;+ }+ return hold;+}++// This run's hold on the plugin's folder (A RUN HOLDS THE FOLDER, at the top of this file), or null: nothing is held on POSIX, nor where the hold cannot be made — a full disk, a folder that takes no new+// file, a host name that cannot be read (the machine is part of the hold's name) — which leaves the run exactly as it was before holds. It is made only in a plain folder: a link is not followed (checkParent,+// which runs next, refuses the folder), and it is opened with `wx`, which makes a NEW file — nothing is ever written into it — so that what is removed later is this run's own. ENOENT is thrown — the folder+// went before the hold was in it — and the attempt is made again at once, as for any ENOENT; so is a refusal of the moment from the look at the folder (a folder Windows is removing cannot be opened), which+// is asked again after a pause. `stamp` is the run's owner stamp (lib/process-owner.js): its host and its pid name the hold.+function holdParent(parent, deps, stamp) {+ const machine = machineOf(stamp.host);+ if (uidOf(deps) !== null || machine === null) return null;+ const fsx = deps.fs || fs;+ if (!fsx.lstatSync(parent).isDirectory()) return null;+ const file = path.join(parent, `${HOLD_PREFIX}${machine}-${stamp.pid}-${crypto.randomBytes(3).toString('hex')}`);+ let fd;+ try {+ fd = fsx.openSync(file, 'wx', 0o600);+ } catch (e) {+ if (e && e.code === 'ENOENT') throw e;+ return null;+ }+ try { fsx.closeSync(fd); } catch { /* the file is made all the same, and is removed by its name */ }+ return file;+}++// Removes a hold. A scanner that has just seen the new file can refuse its removal for a moment (Windows: EPERM, EACCES or EBUSY), and a hold that stayed would keep the plugin's folder from going when the run+// ends, so the removal is asked again after the same short waits as a rename (writeWhole). It never throws: a hold that is gone already (a sweep that took this run for a dead one) is what was wanted, and one that+// cannot be removed is a dead run's hold to the next sweep once this run has ended.+function releaseHold(file, deps) {+ if (file === null) return;+ const fsx = deps.fs || fs;+ for (let attempt = 0; ; attempt += 1) {+ try {+ fsx.unlinkSync(file);+ return;+ } catch (e) {+ if (!windowsRefusesForAMoment(e, deps) || attempt >= WAITS_MS.length) return;+ (deps.pause || pauseSync)(WAITS_MS[attempt]);+ }+ }}// A folder this process made that cannot be made private is not used: it is removed — it is empty, and this process made it — and the workspace goes in the plain temp folder, where it always@@ -427,7 +499,7 @@ function windowOf(listing, parent, maxExamined, deps) {/*** Removes the workspaces in the plugin's folder whose owner is provably gone — and, for one that was lent to another program, only when it is old as well (LENT_KEEP_MS) — and finishes the- * removals that an earlier sweep began and was killed in. Looks at no more than `maxExamined` entries and removes no more than `maxRemoved`, and the entries it looks at move on from one sweep to the next+ * removals that an earlier sweep began and was killed in, and removes the holds of runs that are gone (Windows: A RUN HOLDS THE FOLDER, at the top of this file). Looks at no more than `maxExamined` entries and removes no more than `maxRemoved` workspaces, and the entries it looks at move on from one sweep to the next* (windowOf), so that none is out of reach for good. Never throws; never touches anything it cannot prove dead.* @param {object} [deps] test seams: fs, os, uid, owner (the process-owner.js seams: hostname, platform, pid, probe, now, …), limits ({ maxExamined, maxRemoved })* @returns {{ parent: string, removed: Array<{ name: string, stamp: object }>, failed: Array<{ name: string, stamp: object, error: string }>, kept: number }}@@ -501,11 +573,37 @@ function sweepDeadWorkspaces(deps = {}) {return true;};+ // A hold (Windows: A RUN HOLDS THE FOLDER, at the top of this file) that a run was killed while holding: an empty file, removed once its pid is gone, so that the plugin's folder can go when it is empty. Only a+ // hold of THIS machine — its name says which, and a pid says nothing on another — and only when this machine can be told at all (its host name is read as an owner record reads it, once a sweep meets a hold).+ // The hold of a run that is going — this one's own among them — is left, and so is a file of that name that is not empty: no run made it. Removing one says nothing (it held nothing) and costs no removal of the cap.+ let here;+ const thisMachine = () => {+ if (here === undefined) {+ try { here = machineOf(ownerStamp(deps.owner).host); } catch { here = null; }+ }+ return here;+ };+ const releaseDeadHold = (name) => {+ const machine = thisMachine();+ if (machine === null || HOLD_NAME.exec(name)[1] !== machine) return;+ if (probe(pidOfName(name)) !== 'gone') return;+ const file = path.join(parent, name);+ try {+ const st = fsx.lstatSync(file);+ if (st.isFile() && st.size === 0) fsx.unlinkSync(file);+ } catch { /* gone meanwhile, or held for a moment: the next sweep tries again */ }+ };+for (const entry of windowOf(listing, parent, maxExamined, deps)) {if (entry.isFile() && entry.name.endsWith(REMOVING_SUFFIX)) {if (!finishInterruptedRemoval(entry.name)) result.kept += 1;continue;}+ // Only where holds are made (Windows: `uid` is null, as for holdParent): elsewhere a file of that shape is an entry like any other, and is left as it always was.+ if (uidOf(deps) === null && entry.isFile() && isHoldName(entry.name)) {+ releaseDeadHold(entry.name);+ continue;+ }// A link, a file, anything that is not a folder was not made by a workspace maker.if (!entry.isDirectory()) continue;const named = pidOfName(entry.name);@@ -603,13 +701,15 @@ function makeTempWorkspace(prefix, deps = {}) {// always was. The plugin's folder is a courtesy to the next run, so a refusal of it is never this run's failure; an error is reported only if the plain call fails too, and then it// is that call's, with that call's path.let dir;+ let hold = null;try {- ensureParent(parent, deps);+ hold = ensureParent(parent, deps, stamp);// From here on the folder may be one this process made, so it is this process's to take away when it ends with nothing in it — also when the workspace below is refused (a full disk) and goes in the temp folder.prune(parent, deps);sweepOnce(parent, deps);dir = mkdtemp(path.join(parent, `${named}${stamp.pid}-`));} catch (e) {+ releaseHold(hold, deps);if (e && e.code === 'ENOENT') continue;if (windowsRefusesForAMoment(e, deps)) {if (attempt < MAKE_ATTEMPTS) {@@ -623,14 +723,17 @@ function makeTempWorkspace(prefix, deps = {}) {}break;}+ // The workspace is in the folder now, and keeps it from going as the hold did. It is recorded and registered BEFORE the hold is let go: letting go can wait on a scanner that holds the+ // new file (releaseHold), and a run that is killed in that wait must leave a workspace a sweep can prove dead, not an empty folder with no record, which no sweep ever takes.mark(dir, stamp, deps);// The end of the process removes what the run did not — unless it was lent: a program that was given a path in it may still be writing there (see THE END OF A RUN). A `mkdtempSync` seam that answers a// folder somewhere else is not the plugin's folder's, and is not touched.if (deps.lent !== true && path.dirname(dir) === parent) ownWorkspaces.set(dir, deps.fs || fs);+ releaseHold(hold, deps);return dir;}}return mkdtemp(path.join((deps.os || os).tmpdir(), prefix));}-module.exports = { PARENT_NAME, OWNER_FILE, REMOVING_SUFFIX, CURSOR_FILE, LENT_KEEP_MS, LIMITS: { MAX_EXAMINED, MAX_REMOVED }, workspaceParent, makeTempWorkspace, sweepDeadWorkspaces, sweepWarning, pruneWorkspaceParents };+module.exports = { PARENT_NAME, OWNER_FILE, REMOVING_SUFFIX, CURSOR_FILE, HOLD_PREFIX, LENT_KEEP_MS, LIMITS: { MAX_EXAMINED, MAX_REMOVED }, workspaceParent, makeTempWorkspace, sweepDeadWorkspaces, sweepWarning, pruneWorkspaceParents };diff --git a/plugins/model-apps/scripts/tests/check-auth.test.js b/plugins/model-apps/scripts/tests/check-auth.test.jsindex 3436c1fb4..7f322f2db 100644--- a/plugins/model-apps/scripts/tests/check-auth.test.js+++ b/plugins/model-apps/scripts/tests/check-auth.test.js@@ -184,7 +184,10 @@ function makeExecFile({ pacOrg = null, azUser = '[email protected]', azVersion =};}-function makeCancelableExecFile({ pacOrg = null, azUser = '[email protected]', azVersion = 'azure-cli 2.60.0', pacTimer = false, pacDelayMs = null }, calls) {+// `pacAnswers` (a promise): pac answers when the test resolves it, and not before — a test that needs pac still running when a verdict is+// reached gets that on any machine. A pac that answered on a timer raced the az answers, and won whenever the event loop was held up for+// longer than the timer, as a whole-suite run holds it. `azDelayMs`: the Azure CLI answers that long after it is started (a cold start).+function makeCancelableExecFile({ pacOrg = null, azUser = '[email protected]', azVersion = 'azure-cli 2.60.0', pacTimer = false, pacAnswers = null, azDelayMs = null }, calls) {return (cmd, args, _opts, cb) => {const argv = (args || []).join(' ');calls.push(`start ${cmd} ${argv}`);@@ -211,7 +214,7 @@ function makeCancelableExecFile({ pacOrg = null, azUser = '[email protected]', aif (pacOrg === null) cb(new Error(`spawn ${cmd} ENOENT`), '', '');else cb(null, pacOrg, '');});- if (pacDelayMs !== null) setTimeout(finishSuccess, pacDelayMs);+ if (pacAnswers) pacAnswers.then(finishSuccess);// With pac's own 5 ms timeout armed (pacTimer), its success must come first whatever holds the event loop:// setImmediate loses to an expired timer when the loop was busy for 5 ms first (the module warm-up of a// file's first test is), and the test then staged a pac timeout it never meant to. nextTick runs before any timer.@@ -219,7 +222,7 @@ function makeCancelableExecFile({ pacOrg = null, azUser = '[email protected]', aelse setImmediate(finishSuccess);return child;}- setImmediate(() => {+ const answer = () => {if (child.killed) return;calls.push(`done ${cmd}`);if (cmd === 'az' && argv.includes('--version')) {@@ -231,7 +234,9 @@ function makeCancelableExecFile({ pacOrg = null, azUser = '[email protected]', a} else {cb(new Error(`unexpected command: ${cmd} ${argv}`), '', '');}- });+ };+ if (azDelayMs !== null) setTimeout(answer, azDelayMs);+ else setImmediate(answer);return child;};}@@ -437,23 +442,28 @@ test('pac success is delivered even when async az/token work takes longer than passert.notEqual(r.blocker, 'pac_not_logged_in');});+// pac is still running when the az verdict is reached, however long the Azure CLI takes: it answers only once the test says so, after the+// verdict. It then answers into a probe that was cancelled, which delivers nothing.+async function cancelsPendingPac(exec) {+ const pacAnswers = deferred();+ const r = await runWithAsyncChildren({ argv: ['--env', ENVURL], exec: { ...exec, pacOrg: 'Connected as [email protected]\n', pacAnswers: pacAnswers.promise, azDelayMs: 80 } });+ pacAnswers.resolve();+ await new Promise((resolve) => setImmediate(resolve));+ return r;+}+test('az_missing cancels the pending pac probe before emitting', async () => {- const r = await runWithAsyncChildren({- argv: ['--env', ENVURL],- exec: { azUser: null, azVersion: null, pacOrg: 'Connected as [email protected]\n', pacDelayMs: 50 },- });+ const r = await cancelsPendingPac({ azUser: null, azVersion: null });assert.equal(r.blocker, 'az_missing');assert.ok(r.calls.indexOf('kill pac org who') !== -1, r.calls.join(' | '));assert.ok(!r.calls.includes('done pac'), r.calls.join(' | '));});test('az_not_logged_in cancels the pending pac probe before emitting', async () => {- const r = await runWithAsyncChildren({- argv: ['--env', ENVURL],- exec: { azUser: null, azVersion: 'azure-cli 2.60.0', pacOrg: 'Connected as [email protected]\n', pacDelayMs: 50 },- });+ const r = await cancelsPendingPac({ azUser: null, azVersion: 'azure-cli 2.60.0' });assert.equal(r.blocker, 'az_not_logged_in');assert.ok(r.calls.includes('kill pac org who'), r.calls.join(' | '));+ assert.ok(!r.calls.includes('done pac'), r.calls.join(' | '));});test('without --env the token is not warmed early, because the env URL comes from pac', async () => {diff --git a/plugins/model-apps/scripts/tests/helpers/kill-target.js b/plugins/model-apps/scripts/tests/helpers/kill-target.jsindex 9a9073796..25017560a 100644--- a/plugins/model-apps/scripts/tests/helpers/kill-target.js+++ b/plugins/model-apps/scripts/tests/helpers/kill-target.js@@ -24,6 +24,9 @@// node kill-target.js workspace-refused <prefix>// makes one with a maker that refuses to make a folder inside the plugin's own folder (a full disk: ENOSPC), so that the workspace is made in the temp folder itself — which it says, `workspace <folder>` —// and removes it, and ends: `done`. The plugin's folder was made, for the workspace that was refused.+// node kill-target.js workspace-hold-release <prefix>+// makes one on Windows terms (`uid: null`: the plugin's folder is held while it is judged; the access-list reader and maker are stood in for) with a file system on which the removal of the+// hold is refused (EACCES: a scanner has the new file open), and stops at the first wait to try that removal again: says `releasing <folder>` — the workspace it made — and waits to be killed.// node kill-target.js workspace-loop <prefix> <n> <ms> [<gateFile>]// n times: sweeps, makes a workspace, puts a file in it, waits <ms>, sweeps, checks that its own workspace is still whole (and recorded, if it is in the plugin's folder), removes it.// Says `ready`, waits for <gateFile> when one is given, and says `loop-done <how many times a workspace of its own was gone or unrecorded> <how many were made in the plain temp folder>`.@@ -158,6 +161,28 @@ async function main() {say(`workspace ${folder}`);fs.rmSync(folder, { recursive: true, force: true });say('done');+ } else if (mode === 'workspace-hold-release') {+ const { makeTempWorkspace, workspaceParent, HOLD_PREFIX } = require('../../lib/temp-workspace.js');+ const [prefix] = args;+ const deps = { uid: null, folderPrivacy: () => ({ ok: true, reason: 'stood in for' }), folderProtect: () => ({ ok: true, reason: 'stood in for' }) };+ let refused = false;+ deps.fs = { ...fs, unlinkSync: (file, ...rest) => {+ if (path.basename(String(file)).startsWith(HOLD_PREFIX)) {+ refused = true;+ throw Object.assign(new Error(`EACCES: permission denied, unlink '${file}'`), { code: 'EACCES' });+ }+ return fs.unlinkSync(file, ...rest);+ } };+ // The wait before the removal of the hold is tried again: the one moment this process is killed at.+ deps.pause = (ms) => {+ if (!refused) { pause(ms); return; }+ const parent = workspaceParent(deps);+ const [folder] = fs.readdirSync(parent).filter((name) => name.startsWith(`${prefix}${process.pid}-`));+ say(`releasing ${path.join(parent, folder)}`);+ pause(120000);+ };+ makeTempWorkspace(prefix, deps);+ say('returned');} else if (mode === 'workspace-loop') {const { makeTempWorkspace, sweepDeadWorkspaces, workspaceParent } = require('../../lib/temp-workspace.js');const [prefix, iterations, ms, gate] = args;diff --git a/plugins/model-apps/scripts/tests/helpers/own-temp-folder.js b/plugins/model-apps/scripts/tests/helpers/own-temp-folder.jsindex 430071c58..1667acb2e 100644--- a/plugins/model-apps/scripts/tests/helpers/own-temp-folder.js+++ b/plugins/model-apps/scripts/tests/helpers/own-temp-folder.js@@ -11,7 +11,10 @@// Under load the wait ran out, and a test that checks WHERE a workspace is made — in the plugin's folder, recorded, under the run's pid — failed// although the code did what it promises: verify's workspace was `<temp>/verify-<random>`, and the settings copy's work folder was not asked for// in the plugin's folder at all, in that test and in the next. With a temp folder of its own, no other process makes or removes this one's-// plugin folder. Every test file that checks where a workspace is made in its own process requires this module.+// plugin folder. Every test file that checks where a workspace is made in its own process requires this module. (Measured since, the commoner way+// a workspace went to the plain temp folder there was another: on Windows judging the plugin's folder takes about a second, and the ends of other+// processes kept removing it under the judgement until the maker ran out of attempts. A run now holds the folder while it judges it+// (lib/temp-workspace.js, A RUN HOLDS THE FOLDER), and this module still keeps what such a test checks free of every other process.)//// Require it at the TOP of the test file, before anything reads os.tmpdir(), so that a path the file works out when it loads is inside the folder// too. A child process that a test starts with this process's environment shares the folder, as it shared the suite's before.diff --git a/plugins/model-apps/scripts/tests/strict-xml.test.js b/plugins/model-apps/scripts/tests/strict-xml.test.jsindex b8a47a010..d96bedae0 100644--- a/plugins/model-apps/scripts/tests/strict-xml.test.js+++ b/plugins/model-apps/scripts/tests/strict-xml.test.js@@ -3,9 +3,34 @@// strict-xml-oracle.test.js; what a page is deleted by is in sitemap-pages.test.js and teardown-navigation-proof-real-bundle.test.js.const test = require('node:test');const assert = require('node:assert');-const { readXmlElements, XML_PREDEFINED } = require('../lib/strict-xml.js');+const { readXmlElements, XML_PREDEFINED, work } = require('../lib/strict-xml.js');const all = () => true;+// What reading a document costs, without a clock that a loaded machine can stretch: the characters of paths built (see `work` in lib/strict-xml.js) by one read.+const pathCharactersOf = (xml, wanted = all, options) => {+ const before = work.pathCharacters;+ const r = readXmlElements(xml, wanted, options);+ return { r, built: work.pathCharacters - before };+};+// For the cost that only a clock can tell (a scan of the text): how the time of a read grows with the size of the document, in this process, between a document and one `factor`+// times as large. Linear growth is `factor` times; the square is factor² times. The two sizes are read in turn, round after round, and the least time of each is kept: a busy machine+// slows both alike while it is busy, and the least of several reads leaves out what it adds to one. The bound sits at three times linear, far from the square, so a loaded run+// does not fail it and a quadratic reader cannot pass it. A small side shorter than a millisecond counts as one millisecond: timer noise is then not mistaken for growth.+const FACTOR = 8;+const assertLinearGrowth = (what, build, small, wanted = all, rounds = 25) => {+ const sizes = [small, small * FACTOR];+ const texts = sizes.map(build);+ const best = [Infinity, Infinity];+ texts.forEach((xml) => readXmlElements(xml, wanted));+ for (let round = 0; round < rounds; round += 1) {+ texts.forEach((xml, i) => {+ const started = process.hrtime.bigint();+ readXmlElements(xml, wanted);+ best[i] = Math.min(best[i], Number(process.hrtime.bigint() - started) / 1e6);+ });+ }+ assert.ok(best[1] < Math.max(best[0], 1) * FACTOR * 3, `${what}: ${best[0].toFixed(1)} ms at ${sizes[0]}, ${best[1].toFixed(1)} ms at ${sizes[1]} — growing faster than linearly`);+};const ok = (xml, wanted = all) => {const r = readXmlElements(xml, wanted);assert.strictEqual(r.ok, true, `${JSON.stringify(xml)}: ${r.detail}`);@@ -268,32 +293,69 @@ test('readXmlElements: the namespace an XHTML check goes by is the one in scope});test('readXmlElements: it is linear — a large flat document and a deeply nested one are read at once, and a document of many kinds of element is bounded', () => {- const flat = `<SiteMap><Area><Group>${'<SubArea Id="s" GenPageId="11111111-1111-4111-8111-111111111111" Title="Page & Page"/>'.repeat(20000)}</Group></Area></SiteMap>`;- let started = Date.now();- assert.strictEqual(ok(flat, (name) => name === 'SubArea').length, 20000);- assert.ok(Date.now() - started < 3000, `${Date.now() - started} ms for ${flat.length} characters`);+ const flatOf = (count) => `<SiteMap><Area><Group>${'<SubArea Id="s" GenPageId="11111111-1111-4111-8111-111111111111" Title="Page & Page"/>'.repeat(count)}</Group></Area></SiteMap>`;+ const subArea = (name) => name === 'SubArea';+ const flat = pathCharactersOf(flatOf(20000), subArea);+ assert.strictEqual(flat.r.ok, true);+ assert.strictEqual(flat.r.elements.length, 20000);+ assert.strictEqual(flat.built, 'SiteMap/Area/Group'.length, 'twenty thousand elements under one parent share the one path built for it');+ assertLinearGrowth('a flat document', flatOf, 500, subArea);const depth = 50000;- const nested = `${'<a>'.repeat(depth)}${'</a>'.repeat(depth)}`;- started = Date.now();- assert.strictEqual(ok(nested, () => false).length, 0, 'no recursion: a nesting depth costs one array slot');- assert.ok(Date.now() - started < 3000, `${Date.now() - started} ms for ${depth} levels`);- assert.strictEqual(ok(`${'<a>'.repeat(depth)}<b/>${'</a>'.repeat(depth)}`, (name) => name === 'b')[0].path.split('/').length, depth);+ const nestedOf = (levels) => `${'<a>'.repeat(levels)}${'</a>'.repeat(levels)}`;+ const nested = pathCharactersOf(nestedOf(depth), () => false);+ assert.strictEqual(nested.r.ok, true);+ assert.strictEqual(nested.r.elements.length, 0, 'no recursion: a nesting depth costs one array slot');+ assert.strictEqual(nested.built, 0, 'a path is built for an element that is answered, and for no other');+ // One element at the bottom of a deep document: its path is walked once, and no other is built on the way.+ const bottom = pathCharactersOf(`${'<a>'.repeat(depth)}<b/>${'</a>'.repeat(depth)}`, (name) => name === 'b');+ assert.strictEqual(bottom.r.elements[0].path.split('/').length, depth);+ assert.strictEqual(bottom.built, depth * 2 - 1);const kinds = (count) => `<r>${Array.from({ length: count }, (_, i) => `<k${i}>x</k${i}>`).join('')}</r>`;assert.strictEqual(ok(kinds(200)).length, 201);assert.match(refused(kinds(300)), /more than 256 different element names/);- const aLot = `<a>${'&'.repeat(100000)}${'<!-- x -->'.repeat(20000)}${'<![CDATA[x]]>'.repeat(20000)}${'<?p x?>'.repeat(20000)}</a>`;- started = Date.now();- ok(aLot);- assert.ok(Date.now() - started < 3000, `${Date.now() - started} ms for ${aLot.length} characters of references, comments, CDATA and PIs`);+ const aLotOf = (count) => `<a>${'&'.repeat(count * 5)}${'<!-- x -->'.repeat(count)}${'<![CDATA[x]]>'.repeat(count)}${'<?p x?>'.repeat(count)}</a>`;+ ok(aLotOf(20000));+ assertLinearGrowth('references, comments, CDATA sections and processing instructions', aLotOf, 500);});test('readXmlElements: it never reads past a refusal, so a hostile document cannot make it slow — text that is nothing but "<" or "&" is refused at once', () => {- const started = Date.now();- for (const xml of [`<a>${'<'.repeat(200000)}`, `<a>${'&'.repeat(200000)}`, `<a ${'b="1" '.repeat(1000)}>`, `<${'a'.repeat(200000)} `, `<a b="${'&'.repeat(100000)}`, '<a>'.repeat(10000)]) readXmlElements(xml, all);- assert.ok(Date.now() - started < 3000, `${Date.now() - started} ms`);+ // Refused where it goes wrong, not at the end of the text: the position says how far it read.+ assert.match(refused(`<a>${'<'.repeat(200000)}`), /^a "<" that starts no element.*, at line 1, column 4$/);+ assert.match(refused(`<a>${'&'.repeat(200000)}`), /^an "&" that is not one of the predefined entities.*, at line 1, column 4$/);+ assert.match(refused(`<a ${'b="1" '.repeat(1000)}>`), /^attribute b twice in one tag, at line 1, column 10$/);+ // A tag, a value and a name that are never closed are read to the end of the text once, and not again for each character.+ const unclosedName = (size) => `<${'a'.repeat(size)} `;+ const unclosedValue = (size) => `<a b="${'&'.repeat(size)}`;+ assert.match(refused(unclosedName(200000)), /^a tag that is never closed, at line 1, column 1$/);+ assert.match(refused(unclosedValue(100000)), /^an attribute value that is never closed, at line 1, column 6$/);+ assertLinearGrowth('a tag that is never closed', unclosedName, 25000);+ assertLinearGrowth('an attribute value that is never closed', unclosedValue, 6000);+ // Elements that are never closed, every one asked for: the document is refused at its end, so the paths of its elements — the square of its depth in characters — are never built.+ const unclosed = (levels) => '<a>'.repeat(levels);+ const deep = pathCharactersOf(unclosed(10000));+ assert.strictEqual(deep.r.ok, false);+ assert.strictEqual(deep.r.detail, 'the element <a> is never closed, at line 1, column 30001');+ assert.strictEqual(deep.built, 0, 'nothing of what a refusal throws away is built');+ assertLinearGrowth('elements that are never closed', unclosed, 1250);+});++// A refused document is refused after it was read to its end, and the paths of its elements are then not built; one that is read answers each element with the path it always had.+test('readXmlElements: the path of an element is the names of its ancestors, whatever order they were read in or how many elements share them', () => {+ const xml = '<r><a><b/><b><c/></b></a><a><c/><b><c/></b></a><d/></r>';+ const names = (e) => `${e.path}|${e.name}`;+ assert.deepStrictEqual(ok(xml).map(names), ['|r', 'r|a', 'r/a|b', 'r/a|b', 'r/a/b|c', 'r|a', 'r/a|c', 'r/a|b', 'r/a/b|c', 'r|d']);+ assert.deepStrictEqual(ok(xml, (name) => name === 'c').map(names), ['r/a/b|c', 'r/a|c', 'r/a/b|c']);+ assert.deepStrictEqual(ok(xml, (name) => name === 'd').map(names), ['r|d']);+ // The keys of an element, and their order, are those of a document read without this: the path is in its place from the start.+ assert.deepStrictEqual(Object.keys(ok('<r><a/></r>', (name) => name === 'a')[0]), ['name', 'path', 'attrs']);+ assert.deepStrictEqual(Object.keys(readXmlElements('<r><a/></r>', (name) => name === 'a', { spans: true }).elements[0]), ['name', 'path', 'attrs', 'start', 'end']);+ // Every level asked for: each path is its parent's with one name added.+ const levels = 300;+ const chain = ok(`${'<a>'.repeat(levels)}${'</a>'.repeat(levels)}`);+ assert.deepStrictEqual(chain.map((e) => e.path), Array.from({ length: levels }, (_, i) => Array(i).fill('a').join('/')));});// An element a caller asks for says its `path`, the names of its ancestors, so a document that is nested deep and is asked for at every level costs the SQUARE of its depth in memory:@@ -316,12 +378,12 @@ test('readXmlElements { maxDepth }: a document nested deeper than the caller all// The path of an element is as long as its depth, so the bound is also the bound of what the answer holds.const deepest = bounded(nest(5, '<z/>'), 6).elements.at(-1);assert.strictEqual(deepest.path.split('/').length, 5);- // A document of thousands of levels asked for at every one is refused at the bound, not read: the answer would be gigabytes of paths.- const started = Date.now();- const hostile = bounded(nest(6000), 32);- assert.strictEqual(hostile.ok, false);- assert.match(hostile.detail, /nested more than 32 levels deep/);- assert.ok(Date.now() - started < 3000, `${Date.now() - started} ms`);+ // A document of thousands of levels asked for at every one is refused at the bound, not read: the answer would be gigabytes of paths. The refusal says where it stopped — the 33rd <a> starts+ // after 96 characters — and no path was built on the way.+ const hostile = pathCharactersOf(nest(6000), all, { maxDepth: 32 });+ assert.strictEqual(hostile.r.ok, false);+ assert.match(hostile.r.detail, /nested more than 32 levels deep, at line 1, column 97$/);+ assert.strictEqual(hostile.built, 0);// Without the option nothing changes: a nesting of any depth is read, as before.assert.strictEqual(readXmlElements(nest(300), () => false).ok, true);assert.strictEqual(readXmlElements(nest(300), () => false, {}).ok, true);diff --git a/plugins/model-apps/scripts/tests/temp-workspace.test.js b/plugins/model-apps/scripts/tests/temp-workspace.test.jsindex 76b0c9708..33c966571 100644--- a/plugins/model-apps/scripts/tests/temp-workspace.test.js+++ b/plugins/model-apps/scripts/tests/temp-workspace.test.js@@ -9,7 +9,7 @@ const fs = require('node:fs');const os = require('node:os');const path = require('node:path');const {- PARENT_NAME, OWNER_FILE, REMOVING_SUFFIX, CURSOR_FILE, LENT_KEEP_MS, LIMITS, workspaceParent, makeTempWorkspace, sweepDeadWorkspaces, sweepWarning, pruneWorkspaceParents,+ PARENT_NAME, OWNER_FILE, REMOVING_SUFFIX, CURSOR_FILE, HOLD_PREFIX, LENT_KEEP_MS, LIMITS, workspaceParent, makeTempWorkspace, sweepDeadWorkspaces, sweepWarning, pruneWorkspaceParents,} = require('../lib/temp-workspace.js');const { ownerStamp, isOwnerStamp } = require('../lib/process-owner.js');const { privateTempRoot, tempEnv, startTarget, deadPid, pause, waitUntil } = require('./helpers/kill-target-client.js');@@ -1075,19 +1075,221 @@ test('where the system has no owners to compare (Windows) an EXISTING plugin\'sassert.deepStrictEqual(asked, []);});-test('a folder that is removed while its access list is being read — another run ended with nothing left in it — is made again, not taken for an unsafe one', (t) => {+test('a folder that is removed while its access list is being read — removed whole, as a tool that empties the temp folder does: the end of another run cannot take it, see below — is made again, not taken for an unsafe one', (t) => {const { deps } = tempRoot(t);const parent = workspaceParent({ ...deps, uid: null });fs.mkdirSync(parent);let asked = 0;// What the reader makes of a folder that goes away under it: it cannot save a list of what is not there, and says no.- const own = { ...deps, uid: null, folderPrivacy: () => { asked += 1; fs.rmdirSync(parent); return { ok: false, reason: 'its access list could not be saved' }; } };+ const own = { ...deps, uid: null, folderPrivacy: () => { asked += 1; fs.rmSync(parent, { recursive: true, force: true }); return { ok: false, reason: 'its access list could not be saved' }; } };const dir = makeTempWorkspace('genpage-', own);assert.strictEqual(path.dirname(dir), parent, 'made again in the plugin\'s folder, as the run that asked is owed — not in the temp folder, unrecorded');assert.ok(recordOfFolder(dir), 'and recorded');assert.strictEqual(asked, 1, 'the folder it was made in is the run\'s own, which is not asked about');});+// Windows asks whether a folder is private with three programs — about a second — and the end of every run that leaves nothing in the plugin's folder removes it (`rmdir`: THE END OF A RUN). With runs starting and+// ending side by side the folder was taken away, and made again, while it was being judged: the answer was about a folder that had gone, the run asked again about the new one, and after MAKE_ATTEMPTS answers made its+// workspace in the plain temp folder, unrecorded (measured on one machine: about one run in twenty with three at a time, one in three with twelve). A run now HOLDS the folder while it judges it.+// A hold is named for the machine and the run that made it: `.hold-<8 hex digits for the machine>-<pid>-<6 hex digits>`.+const holdName = new RegExp(`^${HOLD_PREFIX.replace(/\./g, '\\.')}[0-9a-f]{8}-${process.pid}-[0-9a-f]{6}$`);+// The hold a run leaves when it is killed while it holds the plugin's folder: made by the maker itself, on Windows terms (`deps` has `uid: null`), for the run `owner` says — its pid and+// machine (process-owner.js seams) — on a file system that never lets a hold be removed. The workspace the run made is removed again, so the hold is what is left. Answers its path.+function leftHold(deps, owner) {+ const parent = workspaceParent(deps);+ const before = new Set(fs.existsSync(parent) ? fs.readdirSync(parent) : []);+ const sticky = { ...fs, unlinkSync: (file, ...rest) => {+ if (path.basename(String(file)).startsWith(HOLD_PREFIX)) throw Object.assign(new Error(`EIO: i/o error, unlink '${file}'`), { code: 'EIO' });+ return fs.unlinkSync(file, ...rest);+ } };+ fs.rmSync(makeTempWorkspace('genpage-', { ...deps, fs: sticky, owner }), { recursive: true, force: true });+ const made = fs.readdirSync(parent).filter((name) => name.startsWith(HOLD_PREFIX) && !before.has(name));+ assert.strictEqual(made.length, 1, `one hold left: ${JSON.stringify(made)}`);+ return path.join(parent, made[0]);+}+// `rmdir` of a folder with something in it: ENOTEMPTY, or EEXIST where the system says so.+const notEmpty = (code) => (code === 'EEXIST' ? 'ENOTEMPTY' : code);++test('(Windows) a run that ends while another is judging the plugin\'s folder cannot take the folder from under it — the judging run holds it — so the answer is about the folder its workspace is made in', (t) => {+ const { deps } = tempRoot(t);+ const own = { ...deps, uid: null };+ const parent = workspaceParent(own);+ fs.mkdirSync(parent);+ const ends = [];+ // At every judgement another run ends with nothing of its own left in the folder — its end takes the folder with `rmdir`, as pruneWorkspaceParents does, which takes a folder only when it is empty — and a third+ // run starts and makes the folder again.+ const judging = { ...own, folderPrivacy: (folder) => {+ try {+ fs.rmdirSync(folder);+ fs.mkdirSync(folder);+ ends.push('taken, and made again');+ } catch (e) {+ ends.push(notEmpty(e.code));+ }+ return { ok: true, reason: 'private' };+ } };+ const dir = makeTempWorkspace('genpage-', judging);+ assert.strictEqual(path.dirname(dir), parent, `made in the plugin's folder — not in the temp folder because every answer was about a folder that had gone: ${ends.join(', ')}`);+ assert.ok(recordOfFolder(dir), 'and recorded, so a sweep finds it if the run is killed');+ assert.deepStrictEqual(ends, ['ENOTEMPTY'], 'the end of the other run could not take the folder, and the folder was judged once');+ assert.deepStrictEqual(fs.readdirSync(parent), [path.basename(dir)], 'the hold is gone once the workspace is in the folder: the workspace is all it holds');+});++test('(Windows) the hold is an empty file of the run\'s own, in the folder while it is judged and gone when makeTempWorkspace returns — whether the workspace is made there or refused — and a hold that cannot be made leaves the run as it was', (t) => {+ const listed = (folder) => fs.readdirSync(folder).map((name) => [name, fs.lstatSync(path.join(folder, name)).size]);+ // While the folder is judged, and while the workspace is made in it.+ const a = tempRoot(t);+ const own = { ...a.deps, uid: null };+ const parent = workspaceParent(own);+ fs.mkdirSync(parent);+ const seen = [];+ const dir = makeTempWorkspace('genpage-', { ...own,+ folderPrivacy: (folder) => { seen.push(['judged', listed(folder)]); return { ok: true }; },+ mkdtempSync: (start) => { seen.push(['made', listed(path.dirname(start))]); return fs.mkdtempSync(start); } });+ assert.strictEqual(path.dirname(dir), parent);+ assert.strictEqual(seen.length, 2, JSON.stringify(seen));+ const [[whenJudged, judged], [whenMade, atMake]] = seen;+ assert.deepStrictEqual([whenJudged, whenMade], ['judged', 'made']);+ assert.strictEqual(judged.length, 1, `one file in the folder while it is judged: ${JSON.stringify(judged)}`);+ const [[hold, size]] = judged;+ assert.match(hold, holdName, 'named for the run');+ assert.strictEqual(size, 0, 'and empty: it holds nothing');+ assert.deepStrictEqual(atMake, [[hold, 0]], 'still there when the workspace is made: the folder judged is the folder it is made in');+ assert.deepStrictEqual(fs.readdirSync(parent), [path.basename(dir)], 'and gone once the workspace is in the folder');++ // Refused: the folder is not private, or will not take a workspace (a full disk there) — the hold goes all the same, and the workspace is made in the temp folder, as before.+ const fullDisk = (root) => (start) => {+ if (path.dirname(start) !== root) throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' });+ return fs.mkdtempSync(start);+ };+ for (const [what, extra] of [+ ['not private', () => ({ folderPrivacy: () => ({ ok: false, reason: 'Everyone can write to it' }) })],+ ['a full disk', (root) => ({ folderPrivacy: () => ({ ok: true }), mkdtempSync: fullDisk(root) })],+ ]) {+ const b = tempRoot(t);+ const refusedDeps = { ...b.deps, uid: null, ...extra(b.root) };+ fs.mkdirSync(workspaceParent(refusedDeps));+ assert.strictEqual(path.dirname(makeTempWorkspace('genpage-', refusedDeps)), b.root, `${what}: made in the temp folder`);+ assert.deepStrictEqual(fs.readdirSync(workspaceParent(refusedDeps)), [], `${what}: no hold is left in the plugin's folder`);+ }++ // A hold that cannot be made — a full disk, a folder that takes no new file — is no reason to change anything: the workspace is made in the plugin's folder, recorded, as it was before holds.+ const c = tempRoot(t);+ const noHold = { ...fs, openSync: (file, ...rest) => { if (path.basename(String(file)).startsWith(HOLD_PREFIX)) throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' }); return fs.openSync(file, ...rest); } };+ fs.mkdirSync(workspaceParent({ ...c.deps, uid: null }));+ const unheld = makeTempWorkspace('genpage-', { ...c.deps, uid: null, fs: noHold });+ assert.strictEqual(path.dirname(unheld), workspaceParent({ ...c.deps, uid: null }));+ assert.ok(recordOfFolder(unheld));+});++// The last steps of making a workspace are to record it (its owner record), to register it for the end of the process, and to let go of the hold. Letting go can wait on a scanner that holds+// the new file (releaseHold, the WAITS_MS pauses), and a run that is killed in that wait must leave a workspace a sweep can prove dead — not an empty folder with no record, which no sweep+// ever takes, and which keeps the plugin's folder for good. So the hold goes last.+test('REAL KILL: a run killed while the removal of its hold waits on a scanner has already recorded its workspace — the next sweep takes the workspace and the hold, and the folder can go', async (t) => {+ const root = privateTempRoot(t);+ const deps = { os: { tmpdir: () => root }, uid: null, folderPrivacy: () => ({ ok: true, reason: 'stood in for' }), folderProtect: () => ({ ok: true, reason: 'stood in for' }) };+ const run = startTarget(t, ['workspace-hold-release', 'genpage-'], { env: tempEnv(root) });+ const folder = (await run.waitFor(/^releasing /)).slice('releasing '.length);+ await run.kill();+ assert.strictEqual(path.dirname(folder), workspaceParent(deps), 'the workspace was made in the plugin\'s folder');+ assert.ok(recordOfFolder(folder), `it was recorded before the hold was let go, so a sweep can prove its run gone: ${JSON.stringify(fs.readdirSync(folder))}`);+ assert.ok(fs.readdirSync(workspaceParent(deps)).some((name) => name.startsWith(HOLD_PREFIX)), 'and the killed run left its hold');+ const swept = sweepDeadWorkspaces(deps);+ assert.deepStrictEqual(swept.removed.map((r) => [r.name, r.stamp.pid]), [[path.basename(folder), run.pid]], 'the next sweep takes the workspace');+ assert.deepStrictEqual(fs.readdirSync(workspaceParent(deps)), [], 'and the hold: nothing is left to keep the plugin\'s folder');+});++test('POSIX: nothing is held — the folder is judged by one lstat, before anything could change — and the folder holds only the workspace', onlyPosix, (t) => {+ const { deps } = tempRoot(t);+ const atMake = [];+ const dir = makeTempWorkspace('genpage-', { ...deps, mkdtempSync: (start) => { atMake.push(...fs.readdirSync(path.dirname(start))); return fs.mkdtempSync(start); } });+ assert.strictEqual(path.dirname(dir), workspaceParent(deps));+ assert.deepStrictEqual(atMake, [], 'no hold in the folder when the workspace is made');+});++test('(Windows) a hold that a run was killed while holding is removed by the next sweep once its pid is gone, so the folder can go when it is empty — and the hold of a run that is going, or a file of that name with something in it, is left', (t) => {+ const { deps } = tempRoot(t);+ const own = { ...deps, uid: null };+ const parent = workspaceParent(own);+ const dead = deadPid();+ // All that is left in the folder is the hold of a run that was killed: the end of a run cannot take the folder until a sweep has removed it.+ const deadHold = leftHold(own, { pid: dead });+ assert.deepStrictEqual(fs.readdirSync(parent), [path.basename(deadHold)]);+ assert.throws(() => fs.rmdirSync(parent), (e) => notEmpty(e.code) === 'ENOTEMPTY', 'the hold keeps the folder');+ assert.deepStrictEqual([sweepDeadWorkspaces(own).removed, fs.existsSync(deadHold)], [[], false], 'the sweep removes it, and says nothing: a hold held nothing');+ fs.rmdirSync(parent);+ // The hold of a run that is going, and a file named like a hold that has something in it, are left.+ const liveHold = leftHold(own, {});+ const notAHold = leftHold(own, { pid: dead });+ fs.writeFileSync(notAHold, 'something');+ const swept = sweepDeadWorkspaces(own);+ assert.ok(fs.existsSync(liveHold), 'the hold of a run that is going is left');+ assert.ok(fs.existsSync(notAHold), 'a file of that name with something in it was not made by a run, and is left');+ assert.deepStrictEqual([swept.removed, swept.failed], [[], []]);+ assert.deepStrictEqual(entriesOf(parent), [path.basename(liveHold), path.basename(notAHold)].sort());+});++// A temp folder can be shared between machines — a network share, a profile that roams — and a pid says nothing on a machine that did not make it: one that no process has here may be a run+// that is going there. So a hold names its machine, as an owner record names its host (process-owner.js), and a sweep takes only a hold of its own machine. A hold of another machine stays,+// and so does every hold, when a sweep cannot tell which machine it runs on (no host name).+test('(Windows) a hold names its machine: a sweep on another machine that shares the temp folder leaves it, whatever the pid in it is there — so the end of a run there cannot take the folder from under this run\'s judgement', (t) => {+ const { deps } = tempRoot(t);+ const own = { ...deps, uid: null };+ const parent = workspaceParent(own);+ fs.mkdirSync(parent);+ // On the other machine, no process has this run's pid.+ const otherMachine = { ...own, owner: { hostname: () => 'another-machine', probe: () => 'gone' } };+ const seen = [];+ const dir = makeTempWorkspace('genpage-', { ...own, owner: { hostname: () => 'this-machine' }, folderPrivacy: (folder) => {+ // While this run judges the folder, a run on the other machine sweeps it, and ends with nothing of its own left in it.+ sweepDeadWorkspaces(otherMachine);+ const left = fs.readdirSync(folder);+ let ended;+ try {+ fs.rmdirSync(folder);+ fs.mkdirSync(folder);+ ended = 'taken, and made again';+ } catch (e) {+ ended = notEmpty(e.code);+ }+ seen.push({ left, ended });+ return { ok: true, reason: 'private' };+ } });+ assert.strictEqual(seen.length, 1, `the folder was judged once: ${JSON.stringify(seen)}`);+ assert.strictEqual(seen[0].left.length, 1, `this run's hold is still in the folder after the other machine's sweep: ${JSON.stringify(seen)}`);+ assert.ok(seen[0].left[0].startsWith(HOLD_PREFIX));+ assert.strictEqual(seen[0].ended, 'ENOTEMPTY', 'so the end of the run there could not take the folder');+ assert.strictEqual(path.dirname(dir), parent, 'and the workspace is in the plugin\'s folder');+ fs.rmSync(dir, { recursive: true, force: true });++ // A hold of this machine, of a run that is gone: a sweep that cannot read the name of its own machine leaves it; a sweep of this machine takes it.+ const thisMachine = { hostname: () => 'this-machine', probe: () => 'gone' };+ const gone = leftHold(own, { hostname: () => 'this-machine', pid: deadPid() });+ sweepDeadWorkspaces({ ...own, owner: { ...thisMachine, hostname: () => { throw new Error('no host name'); } } });+ assert.ok(fs.existsSync(gone), 'a sweep that cannot tell its own machine leaves every hold');+ sweepDeadWorkspaces({ ...own, owner: thisMachine });+ assert.ok(!fs.existsSync(gone), 'the sweep of its own machine takes it');+});++// Holds are made only where the system has no owners to compare (Windows), and only taken there: where it has (POSIX), a file of that shape in the plugin's folder is an entry like any+// other, and a sweep leaves it as it always did, however dead the pid in its name is. Shown on every system: the folder is shown to the sweep as one this user owns, with the mode a+// POSIX plugin folder has.+test('POSIX: a sweep where the system has owners leaves an empty file shaped like the hold of a dead run, as it always did — holds are made, and taken, only on Windows', (t) => {+ const { deps } = tempRoot(t);+ const uid = POSIX ? process.getuid() : 4242;+ const parent = workspaceParent({ ...deps, uid });+ fs.mkdirSync(parent, { mode: 0o700 });+ const ownedByUs = { isDirectory: () => true, isSymbolicLink: () => false, uid, mode: 0o40700 };+ const posix = { ...deps, uid, fs: { ...fs, lstatSync: (target, ...rest) => (target === parent ? ownedByUs : fs.lstatSync(target, ...rest)) }, owner: { probe: () => 'gone' } };+ // Named as the maker names the hold of a run of this machine that is gone — the maker made it, on Windows terms, in a temp folder of its own.+ const windowsTerms = tempRoot(t);+ const shaped = path.join(parent, path.basename(leftHold({ ...windowsTerms.deps, uid: null }, { pid: deadPid() })));+ fs.writeFileSync(shaped, '');+ const swept = sweepDeadWorkspaces(posix);+ assert.ok(fs.existsSync(shaped), 'left where it is');+ assert.deepStrictEqual([swept.removed, swept.failed], [[], []]);+});+test('the answer about a folder is the answer about THAT folder: one that is removed and made again — by someone else — is asked about again', (t) => {const { deps } = tempRoot(t);const parent = workspaceParent({ ...deps, uid: null });