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.27.0 (#851)
Akshay Maloocb07d811d384
diff --git a/evals/model-apps/routing/EVAL_GUIDE.md b/evals/model-apps/routing/EVAL_GUIDE.mdindex c658015b5..e26aeafcf 100644--- a/evals/model-apps/routing/EVAL_GUIDE.md+++ b/evals/model-apps/routing/EVAL_GUIDE.md@@ -50,7 +50,16 @@ rule things out, and these are how a rule-out that is read too widely would showloads for Claude — `--safe-mode` would skip it but also drops the plugin's own skills — and CIrunners have none.- **Read-only.** The tool set is cut to "invoke a skill + read files". The trade-off is that a real- session offers more tools, so the model sees a slightly smaller menu.+ session offers more tools, so the model sees a slightly smaller menu. Because nothing can be built+ with it, every prompt is sent after a short note (`TRIAL_NOTE` in `lib/agents.js`, shown by+ `--dry-run`): it says that only a skill or a file read is possible, and that if no skill fits the+ agent should answer in one sentence and stop. It names no skill and no product. Why: in saved+ transcripts of the failing negative cases the first turn chose no skill; some runs then said they+ had no file-write or shell tool, and some runs (with or without that remark) later called+ `report-issue`, the generic skill, while checking what tooling exists. These are separate+ observations, and the working inference is that an agent with an empty menu has no way to finish.+ It is not shown that every weekly mis-route follows that sequence; compare a whole-eval run+ before and after a change to the note to see its effect.- **Stopped at the decision.** The JSONL transcript is parsed as it streams, and the agent is killedthe moment it invokes a model-apps skill, so a positive trial costs about one model turn. A run thathas not chosen a skill goes on to its own end, so a skill it reaches for later is seen, and graded, too@@ -79,7 +88,9 @@ The agent runs with a read-only menu (a skill, `view`, `glob`, `grep`: no file wthat is plainly not for the plugin can therefore go like this: turn 0 looks at the empty workspace anddecides that no skill applies, which is the right answer, and turn 1, with nothing to build with, asks fora skill as a stand-in. The grade counts that request, so the case fails, and the first turn's decision is-what tells a stand-in from a description that pulls the request in.+what tells a stand-in from a description that pulls the request in. The note described under+[How a trial runs](#how-a-trial-runs) tells the agent how to finish without a skill, which is what removes+most stand-ins; one that still happens is counted as before.| | Meaning | Part of the grade ||---|---------|-------------------|@@ -107,7 +118,7 @@ Each trial has `routedTo` (the first plugin skill of the run), `initial` (the fi`delayed` (the later one or `null`) and `turn` (which turn asked for the first plugin skill).Read a `later:` count as a question. In a real session the agent has file and shell tools and would do the-work itself, so a stand-in is partly a property of this menu. A count that grows after a description edit,+work itself, so a stand-in is partly a property of this menu, which the note in each prompt answers. A count that grows after a description edit,though, means the agent reached for the plugin on a request that is not for it. No option grades only thefirst turn: it would pass every negative case on any run that reads the workspace before it asks for a skill.diff --git a/evals/model-apps/routing/lib/agents.js b/evals/model-apps/routing/lib/agents.jsindex 93dbf7bbd..cd6c5f3d4 100644--- a/evals/model-apps/routing/lib/agents.js+++ b/evals/model-apps/routing/lib/agents.js@@ -68,6 +68,24 @@ function buildInvocation(agent, { pluginDir, model = null, maxTurns = 4, copilotthrow new Error(`unknown agent ${JSON.stringify(agent)}`);}+// The menu above is read-only, so an agent that has decided no skill fits has no tool to do the work+// with. Observed in saved Copilot CLI transcripts of the failing negative cases (separate observations,+// not one proven sequence): some runs decide that no product skill fits and then say they have no+// file-write or shell tool; other runs, which never say it, go on to call `report-issue`+// (the generic skill, whose frontmatter lists Bash) while checking what tooling exists. The grade counts+// that call, so a "none" first turn can still fail a case no description pulls in. The working+// inference is that the empty menu leaves such an agent without a way to finish; it is not shown that+// every mis-route in a weekly run follows it. This note names the way out the menu lacks; it names no+// skill and does not say which to prefer, so a description that really pulls a request in is still seen.+const TRIAL_NOTE = 'This is a routing test. You can only call a skill or read files: nothing can be written or run here, '+ + 'and you cannot ask me a question. If one of the available skills fits the request, call it. If none of them does, '+ + 'reply in one short sentence naming what the request needs, and stop: do not try to build it.';++/** The text sent to the agent for one case: the harness note, a blank line, then the user's prompt verbatim. */+function trialPrompt(prompt) {+ return `${TRIAL_NOTE}\n\n${prompt}`;+}+/*** Quote one argument for cmd.exe (used only on Windows, where `.cmd` shims require a shell).* Our arguments are flags, tool names and file-system paths — never the prompt (stdin) — so@@ -78,4 +96,4 @@ function quoteForCmd(arg) {return /[\s"&|<>^()%!,;]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;}-module.exports = { buildInvocation, quoteForCmd, TELEMETRY_OPTOUT };+module.exports = { buildInvocation, quoteForCmd, trialPrompt, TRIAL_NOTE, TELEMETRY_OPTOUT };diff --git a/evals/model-apps/routing/run-routing.js b/evals/model-apps/routing/run-routing.jsindex 9d3fa84f0..5fe6009b4 100644--- a/evals/model-apps/routing/run-routing.js+++ b/evals/model-apps/routing/run-routing.js@@ -40,7 +40,7 @@ const { spawn, spawnSync } = require('node:child_process');const { TIERS } = require('../lib/eval-args.js');const { TranscriptParser, AGENTS } = require('./lib/transcript.js');-const { buildInvocation, quoteForCmd } = require('./lib/agents.js');+const { buildInvocation, quoteForCmd, trialPrompt, TRIAL_NOTE } = require('./lib/agents.js');const { summarizeCase, validateEvals, decisionOf } = require('./lib/grade.js');const REPO_ROOT = path.resolve(__dirname, '..', '..', '..');@@ -390,7 +390,7 @@ async function runTrialWithAgent(opts, evalCase, plugin) {bin,args: inv.args,env: inv.env,- prompt: evalCase.prompt,+ prompt: trialPrompt(evalCase.prompt),cwd,timeoutMs: opts.timeout * 1000,plugin,@@ -441,7 +441,7 @@ async function runRouting(opts, { runTrial = runTrialWithAgent, evalsData, writeif (opts.dryRun) {const inv = buildInvocation(opts.agent, { pluginDir: PLUGIN_DIR, model: opts.model, copilotHome: '<temp COPILOT_HOME>' });write(`# dry run — would launch ${cases.length} case(s) × ${opts.runs} trial(s):`);- write(`# ${opts.agentBin || inv.bin} ${inv.args.join(' ')} (prompt on stdin, cwd = empty temp dir)`);+ write(`# ${opts.agentBin || inv.bin} ${inv.args.join(' ')} (prompt on stdin, cwd = empty temp dir, each prompt follows this note: ${TRIAL_NOTE})`);for (const c of cases) write(`# #${c.id} [${c.tier}] expect ${c.expect === null ? 'none' : c.expect}: ${c.prompt}`);return { exitCode: 0, results: null };}diff --git a/evals/model-apps/routing/tests/routing-lib.test.js b/evals/model-apps/routing/tests/routing-lib.test.jsindex ef6112d9e..f3fa790db 100644--- a/evals/model-apps/routing/tests/routing-lib.test.js+++ b/evals/model-apps/routing/tests/routing-lib.test.js@@ -8,7 +8,7 @@ const path = require('node:path');const { TranscriptParser, parseTranscript } = require('../lib/transcript.js');const { gradeTrial, summarizeCase, validateEvals, acceptable } = require('../lib/grade.js');-const { buildInvocation, quoteForCmd, TELEMETRY_OPTOUT } = require('../lib/agents.js');+const { buildInvocation, quoteForCmd, trialPrompt, TRIAL_NOTE, TELEMETRY_OPTOUT } = require('../lib/agents.js');const PLUGIN = { pluginName: 'model-apps', pluginSkills: ['app-builder', 'genpage', 'report-issue', 'telemetry'] };const sample = (name) => fs.readFileSync(path.join(__dirname, 'transcripts', name), 'utf8');@@ -190,6 +190,19 @@ test('agents(copilot): isolated COPILOT_HOME required; variadic --available-toolassert.deepEqual(inv.args.slice(inv.args.indexOf('--disable-mcp-server'), inv.args.indexOf('--disable-mcp-server') + 2), ['--disable-mcp-server', 'playwright']);});+// A read-only menu leaves an agent that has decided no skill fits with nothing to do the work with, and it+// then asks for the nearest generic skill as a stand-in (a correct "none" graded as a mis-route). The note+// gives it a way to finish, and must not steer a request toward or away from any skill.+test('agents: trialPrompt sends the case prompt verbatim after a note that tells the agent how to finish without a skill', () => {+ const prompt = 'Build a React dashboard.\nNo Power Platform.';+ const sent = trialPrompt(prompt);+ assert.ok(sent.endsWith(`\n\n${prompt}`), 'the user\'s words are untouched, and last');+ assert.equal(sent.slice(0, sent.length - prompt.length - 2), TRIAL_NOTE);+ assert.match(TRIAL_NOTE, /nothing can be written or run/);+ assert.match(TRIAL_NOTE, /If none of them does, reply in one short sentence[^.]*, and stop/);+ assert.doesNotMatch(TRIAL_NOTE, /genpage|app-builder|report-issue|telemetry|Power|Dataverse|model-driven|React/i, 'names no skill and no product');+});+test('agents: quoteForCmd quotes paths with spaces and cmd metacharacters only', () => {assert.equal(quoteForCmd('--verbose'), '--verbose');assert.equal(quoteForCmd('C:\\Program Files\\x'), '"C:\\Program Files\\x"');diff --git a/evals/model-apps/routing/tests/run-routing.test.js b/evals/model-apps/routing/tests/run-routing.test.jsindex 7ddd69bcc..2a2d4a960 100644--- a/evals/model-apps/routing/tests/run-routing.test.js+++ b/evals/model-apps/routing/tests/run-routing.test.js@@ -12,6 +12,7 @@ const path = require('node:path');const { spawnSync } = require('node:child_process');const { parseArgs, runRouting, spawnTrial, DEFAULTS } = require('../run-routing.js');+const { TRIAL_NOTE } = require('../lib/agents.js');const RUNNER = path.join(__dirname, '..', 'run-routing.js');const FAKE = path.join(__dirname, 'fake-agent.js');@@ -151,6 +152,35 @@ test('CLI --dry-run prints the isolated invocation and launches nothing', () =>assert.equal(r.status, 0, r.stderr);assert.match(r.stdout, /# dry run — would launch \d+ case\(s\) × 3 trial\(s\)/);assert.match(r.stdout, /copilot .*--plugin-dir .*--available-tools skill view glob grep/);+ assert.ok(r.stdout.includes(TRIAL_NOTE), 'the note every prompt follows is shown, so what the agent is sent can be reviewed');+});++// The note only works if the agent is actually sent it. This drives the real trial path (runRouting's default+// trial function, the Copilot preflight, the transcript save) through an executable stand-in for the CLI, and+// reads back what reached the agent's stdin: the fake echoes it as the transcript's user message.+test('CLI trial: the agent receives the whole note, then the case prompt verbatim and last', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'routing-note-'));+ try {+ const shim = path.join(dir, process.platform === 'win32' ? 'agent.cmd' : 'agent.sh');+ fs.writeFileSync(shim, process.platform === 'win32'+ ? `@"${process.execPath}" "${FAKE}" %*\r\n`+ : `#!/bin/sh\nexec "${process.execPath}" "${FAKE}" "$@"\n`, { mode: 0o755 });+ const transcripts = path.join(dir, 'transcripts');+ const evalCase = require('../evals.json').evals.find((c) => c.id === 28);+ const r = spawnSync(process.execPath, [RUNNER, '--agent', 'copilot', '--agent-bin', shim, '--eval', String(evalCase.id), '--runs', '1', '--transcripts', transcripts], {+ encoding: 'utf8', env: { ...process.env, FAKE_AGENT_MODE: 'copilot-answer' },+ });+ assert.equal(r.status, 0, r.stdout + r.stderr);+ const file = path.join(transcripts, `${evalCase.id}-1.copilot.jsonl`);+ const sent = fs.readFileSync(file, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)).find((e) => e.type === 'user.message').data.content;+ assert.equal(sent, `${TRIAL_NOTE}\n\n${evalCase.prompt}`, 'the note, a blank line, then the user\'s words untouched');+ assert.ok(sent.endsWith(evalCase.prompt), 'the case prompt is last');+ // Both directions: a fitting skill is called, and with none the agent finishes in one sentence.+ assert.match(sent, /If one of the available skills fits the request, call it\./);+ assert.match(sent, /If none of them does, reply in one short sentence naming what the request needs, and stop: do not try to build it\./);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+ }});// ---------- spawnTrial against a fake agent (real process plumbing) ----------diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex 47f2a9f39..3d1f08dba 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.26.0",+ "version": "2.27.0","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 47f2a9f39..3d1f08dba 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.26.0",+ "version": "2.27.0","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 1721f7c59..26b9657c6 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -631,7 +631,16 @@ the pipeline and delegates each script's **behavioral spec** to the entries belowhich reads each page again — as each rebuild does — and a page that already holds its content is not written (and is published only if this workspace did not record that this very content was published), so its history does not record the prompt again.**All of the build's Dataverse access is via the SDK** (see "Dataverse Access From Scripts" for thesanctioned exceptions elsewhere), so metadata is persisted under- `<app-folder>/.maker-workspace/` for reuse/edits. The 16 phases+ `<app-folder>/.maker-workspace/` for reuse/edits. Environment variables and connection references are the+ exception: the SDK's copies of them (values, defaults, value schemas, secret references, connection ids) stay in+ that SDK instance's memory and are never written to any workspace, the build's throwaway one included+ (`lib/workspace-configuration-memory.js`, applied by `lib/maker-sdk.js` to every SDK it makes). Copies an earlier+ version wrote there are never deleted or hidden by the plugin: a pair the SDK's own metadata proves clean (the copy+ equals its last-synced `snapshot`) is left on disk and never used as configuration (it is read only to prove it clean); anything else (a draft, a lone file, a file that cannot be+ read) is refused with `WORKSPACE_LEGACY_CONFIGURATION_COPY` at the SDK's first touch of that artifact, naming its two+ files and quoting none of their content, and checked again on the next touch; every SDK made over a folder that still+ holds such files warns once per process, naming the folders. The maker removes them by hand (app-builder skill,+ "Sensitive configuration in the workspace"). The 16 phases(`solution·data-model·sample-data·web-resources·views·charts·forms·business-rules·business-process-flows·commands·dashboards·app-shell·pages·ai-features·security·publish`)are unchanged; independent ops run with bounded parallelism.**Business rules are environment-gated, and the gate has two forms** (`sdk-build.js`, the `business-rules` loop; `skipIf` is the whole decision). An environment that does not declare the@@ -1789,7 +1798,7 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo**It restores protected configuration** (`configurationIdentity: "stable-v1"`; `lib/declared-configuration-io.js`,`restoreManagedConfiguration`). A configuration group keeps no declaration, so each one is rebuilt from the boundrows as they are now, read IN MEMORY at their exact ids (`readConfigurationRow`), never through the SDK's cached- `fetchArtifact` (which writes current values, defaults and connection ids into workspace files). It is accepted+ `fetchArtifact` (whose copy holds current values, defaults and connection ids, kept in the SDK's memory). It is acceptedonly when `restoreProofOf` (`lib/configuration-protected.js`) proves a rebuild of it changes nothing: the build'sown exact location, plan and judgment, every planned row matching a committed consumer row, and each such row'scurrent projection equal to the one the build committed (that comparison is what catches a row edited by hand,@@ -3572,12 +3581,29 @@ run's own epoch, `attemptProvenUnsent`, the group still at the attempt's base gefound made): an operation the SDK refused before its first request (`CUSTOM_API_LABELS_UNSUPPORTED` on anenvironment with more than one language) must not hold the group, or every later declaration — the earlierone, another edit, the same one — stops on a pending attempt prepared for another declaration. Anything that-may have been sent keeps the attempt, and the run's own stop stands either way. Environment variable and connection reference updates (definition, first+may have been sent keeps the attempt, and the run's own stop stands either way. A create REQUEST the service refused+before carrying it out (#847: `managed-feature-contract.js` `notStartedAnswer`, a 400/403/404/412 with a Dataverse+error code, never a `$batch`; only a POST whose every row is a create — a refused PATCH of an existing row keeps its+owed recovery) is un-sealed by the transport while its scope is open (`managed-create-transport.js`+`refusedUnstarted` -> `store.noteRowsNotStarted`: those rows back to undispatched, one count from `possible` to+`notStarted`). One Dataverse operation is rolled back whole, so if it was the attempt's only send the port's+`ctx.release` succeeds and the item stops as `create-refused` (`refusedStop`, `nothingCreated`, the service+code), routed to the refused bucket so later items still run: nothing is pending, and the next build creates it+again from what the App Spec then declares (a secret variable's value from the settings), or drops it. Measured live, a+secret variable's protected create is two sends (the definition, then its value): a refused value therefore keeps the+attempt (`create-outcome-unknown`, the definition row left), and the maker retires it as the reference describes. Environment variable and connection reference updates (definition, firstvalue, own value replacement) go through the protected port as one checked set over the item's plan; a valuerow the binding does not hold is `create-identity-conflict`. Before any service change, every build runs thestore-driven `pendingSweep` (the hookup's `sweep`, run by `configuration-build.js` `sweepPendingConfiguration`regardless of the opt-in, the declarations or the phases): an undeclared pending or unusable protected record-stops it with `managed-settlement-pending`. Before an overwriting fetch of a protected item (preflight, port and+stops it with `managed-settlement-pending`, except an attempt the store lets go by its own checked write (#847):+one still `prepared` (`retireUnsentAttempt`), one `attemptProvenUnsent` (`retireProvenUnsentAttempt`), and+one that may have been sent only under the maker's exact `--authorize retire:<kind>:<port key>@<attempt token>`+(printed by the stop; read by `configurationAuthorizationKeys` into `opts.configurationRetirements`, refused for a+declared item with `CONFIGURATION_RETIRE_DECLARED`; `store.abandonAttempt`). Abandoning deletes and sends+nothing: rows the attempt may have created stay unmanaged, and a later declaration is an unbound create whose+derived-id read stops on them (`create-identity-conflict`), so nothing is created twice. Each retired attempt is+named through `opts.warn`. Before an overwriting fetch of a protected item (preflight, port andverify), a workspace copy with unsynced edits (`hasUnsyncedEdits`) stops it. The build never resets or deletesthat copy on its own, a failed or uncertain send included: the copy is shared with the maker, the SDK diff is notlocked and there is no conditional overwrite, so no check can prove a reset discards only the build's own change@@ -4149,6 +4175,7 @@ scripts/apply-snapshot-store.js ← changed-only: atomic snapshot write (writeFileAtomic, also the baseline's and the page ownership and publish records', with the access tokens the process obtained taken out of what it writes — a text, or bytes masked with as many `*` — `lib/output-redaction.js` `redactFileData`) + workspace lease + invalidate/claim/tombstone/delete + distrust marker. `acquireLease` is the one exclusive-create-and-reclaim protocol for a lock file in a workspace: the snapshot lease (`apply-snapshot.lock`) and the build's pages lock (`pages-<app>.lock`, `sdk-build.js` `acquireAppPagesLease`) both use it, the pages lock with the owner record of `process-owner.js` and a stricter rule for "stale" — a lock left by a build that was killed is released by the next build, which says so (`released the pages lock for '<app>': the build that held it (pid …) is no longer running`), but only when that build is provably gone; a lock whose pid runs, another machine's, one with no readable record, is refused in the words it always had, and none is ever taken by ageapply-snapshot-index.js ← changed-only: build result.created → snapshot artifact mapworkspace-paths.js ← the `.maker-workspace` name + the guard that gates destructive --clear-workspace cleanup+ workspace-configuration-memory.js ← keeps the SDK's environment-variable and connection-reference copies (values, defaults, value schemas, secret references, connection ids) in memory, never in a workspace file; never deletes or hides copies an earlier version left (a clean pair is left in place and never used as configuration, anything else is refused with WORKSPACE_LEGACY_CONFIGURATION_COPY; maker-sdk.js warns naming their folders)workspace-binding.js ← a persistent `.maker-workspace` belongs to the environment it was first opened for (only `--apply` opens it; a dry run uses a temporary workspace): turns the SDK's `WORKSPACE_ORG_MISMATCH`, and a manifest the JSON parser rejects, into the build's halt (both environments as origins, the safe remedies — the teardown one only for another environment that was built in, with the folder printed on its own line; a folder that was only opened gets no build-there/teardown advice; a folder with no usable environment is moved aside, not deleted; never clears or re-binds) and into the dry run's warningchanged-only-flow.js ← changed-only: --changed-only orchestration (decide fast/full, live identity, snapshot lifecycle)projection.js ← changed-only: pure post-apply verifiers (form placement / sitemap / page dual-hash)@@ -7094,7 +7121,11 @@ cases are graded as a pass rate over N trials, on the first plugin skill the ageasks for at any turn. The decision of its **first turn** is reported beside thatgrade and never in place of it: a skill it reaches for only after a first turn thatchose none (a stand-in, perhaps, when its read-only menu has no way to do the work)-still fails a negative case, and the case line says the first turn chose none. **Run it when you edit a skill+still fails a negative case, and the case line says the first turn chose none. Because+that menu cannot do any work, every prompt is sent after a short note (`TRIAL_NOTE` in+`lib/agents.js`) that says so and tells the agent to answer in one sentence and stop when+no skill fits; saved transcripts show an agent that had already chosen none later calling+`report-issue` while checking its tooling. The note names no skill and no product. **Run it when you edit a skill`description:`.** It is not a per-PR gate (cost, non-determinism):`model-apps-agent-evals.yml` runs it on a same-repo PR labelled`run-agent-evals`, weekly, and on demand, using Copilot CLI authenticated by thediff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex 18aed8b93..255c32941 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -5,6 +5,24 @@ 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.27.0]++- **Same-named declared views (#845):** `--verify` checks each declared view against its own row (managed binding, then `viewId`, then name), so two same-named views on one table, each with its own `key`, no longer fail verification.+- `--changed-only` sees an edit to the earlier of two same-named declared views and runs the full build that applies it.+- Both views of such a pair join the app's components and declared pins, not only the later one.+- **Sensitive configuration stays off disk (#846):** the SDK workspace keeps environment-variable and connection-reference copies in memory, so the values, secret references and connection ids that deployment settings supply are never written to its files.+- A protected environment-variable create left pending, by this version or a 2.26 build, now prints the steps and the exact approval that retire it (#847).+- Copies an earlier version left in a workspace are never used as configuration, hidden or deleted: the build names their folders and refuses one it cannot prove clean.++### Limits++- Without `configurationIdentity`, a whole-build retry after a lost configuration create answer can still create a second row (#807).+- A protected secret variable is created in two requests: if its value is refused, the build stops with the outcome unknown and the definition left; retire it and delete that row before declaring it again (#847).+- For two same-named declared views with no managed binding or `viewId`, `verify` lists their content as unverified and does not prove each has its own row.+- Workspace copies an earlier version left stay until removed by hand (see the app-builder skill).+- A publish refused because another customization is running still stops after the ordinary retries (#848).+- `/genpage` does not yet ask before editing a page other apps use (#676).+## [2.26.0]- **Managed downloads restore more of an app:** declared views and charts, environment variables, connection references and Custom API scaffolds the binding store proves unchanged; values, defaults, secrets and connection ids are never written (#811).diff --git a/plugins/model-apps/references/app-spec-schema-advanced.md b/plugins/model-apps/references/app-spec-schema-advanced.mdindex 88c8b1b73..8dc159750 100644--- a/plugins/model-apps/references/app-spec-schema-advanced.md+++ b/plugins/model-apps/references/app-spec-schema-advanced.md@@ -741,6 +741,11 @@ spec's new columns.other joins) is kept. `viewId` pins the view to edit in one environment. A new declared view iscreated and published like any other view. The stock `Active <plural>` and `Inactive <plural>` viewsexist on every table, new ones included, so declaring one of them is an adoption (see Approvals).+ `--verify` finds a declared view as the build does: by the row the workspace's managed bindings record+ for its key, else by its `viewId`, else by its name on its table. So two declared views with one name on+ one table, each with its own `key`, are each checked against their own row. With neither a binding nor a+ `viewId`, the name cannot tell such a pair apart: both are checked as present, and their content is listed+ as unverified.- **`charts[].reconcile: "declared"`** — the chart type, category, series and description follow thespec. `title` is written only to a chart whose stored layout already has a title; a new chart cannotstore one, so a declared `title` on a new chart is refused (`chart-title-not-stored`).@@ -775,8 +780,10 @@ unchanged and unbound without a stop (with `createIdentity`, the build warns andAdoption below). `--authorize overwrite:view:<table>/<name>` (or `chart:`)approves replacing changes made elsewhere, and `--allow-destructive` approves removing columns. Each keyapproves only the artifact of its family, so a view and a chart with the same name are approved-separately. Within a family a key must name one artifact: two declared views on one table need different-names, and so do two declared charts (a chart's name is compared with its outer spaces trimmed). A+separately. Within a family a key must name one artifact: two declared charts on one table need different+names (a chart's name is compared with its outer spaces trimmed), and so do two declared views unless each+has its own `key` (a view's key is its `key` when set, else `<table>/<name>`, and its approval keys name it:+`adopt:view:<key>`). A`viewId` pin chooses the row a view edits but is not part of its key, so it does not tell twosame-named declared views apart. A build or a plan refuses such a pair before any work; teardown andverification only warn. The same name on another table, or on a view and a chart, is fine. The older `adopt:<table>/<name>` form still works when it names exactly one declared view or@@ -1537,7 +1544,12 @@ the field builds exactly as before.reads the binding store for protected items whose create or edit has not finished. If the App Spec nolonger declares such an item, the build stops with `managed-settlement-pending` and sends nothing.This applies with or without the field and whatever phases run. Declare the item again, with the- field, to finish it.+ field, to finish it. Or, if you no longer want it, stop tracking it: the stop prints the exact+ approval, `--authorize retire:<kind>:<key>@<attempt token>`. Pass it as printed, with the item still+ left out of the App Spec. Nothing is deleted: rows the create may have made stay in the environment,+ unmanaged, and declaring the item again later stops with `create-identity-conflict` until you remove+ them. An unfinished item that the binding store proves was never sent is let go without an approval,+ with a warning.An item that finished before it was removed from the App Spec does not stop the build.- **`--changed-only` runs the whole build.** While the field is set, or the binding store holdsconfiguration state, a `--changed-only` apply runs the full build and prints@@ -1558,10 +1570,28 @@ the field builds exactly as before.environment with more than one language, `CUSTOM_API_LABELS_UNSUPPORTED`) stops that build and leavesnothing unfinished: the next build is judged on what the App Spec then declares, the earlierdeclaration, another edit or the same one.+- **A create the service refused.** When the service refuses the only request of a protected create with an+ error code, nothing was created. The item stops with `create-refused` and the code, the items after it still+ run, and nothing is left unfinished: correct the declaration or its deployment settings value and build+ again, or remove it from the App Spec. A refused edit of an existing row is different: it stays unfinished,+ as above. A secret environment variable is created in two requests, its definition and then its value:+ when the service refuses the value (for example a Key Vault reference it rejects), the definition already+ exists, so the build stops with the outcome unknown and keeps the attempt; retire it as described next, then+ delete that definition row before you declare the variable again.+ A create an earlier plugin version (2.26.0 or before) left unfinished after such a refusal is not+ released by corrected settings: that version did not record that nothing was created, so the build+ stops with `create-completion-required` and sends nothing. The stop prints the way out with the exact+ approval: remove the item (and its deployment settings entry) from the App Spec, run the build with+ `--apply` and the printed `--authorize retire:<kind>:<key>@<attempt token>` (nothing is deleted or+ sent), then restore the item and its settings and build again; it is then created once. If the+ refused create had already made a row at the item's derived id (for example a variable's definition+ whose value was refused), the restored build stops with `create-identity-conflict` naming that id:+ delete that row in the environment if you do not need it, then build again.- **A create that did not finish.** The next build decides it from what the first one recorded beforesending, never from today's rows, and sends nothing while it does: a create that is complete is bound;a create that is missing a row, its solution membership or the rule's initial state stops with- `create-completion-required` — complete it under the same ids, then build again. An initial+ `create-completion-required` — complete it under the same ids, then build again (or let it go as+ described for a refused create above). An initialpublication that failed or whose answer was lost is never sent again by the build: publish the ruleunder the same id yourself. The one exception is a rule whose content was saved, but whose publishrequest the record proves was never sent (the run stopped first). The next build sends that publishdiff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.jsindex 2bd2e9a35..8c2fa67c4 100644--- a/plugins/model-apps/scripts/build-model-app.js+++ b/plugins/model-apps/scripts/build-model-app.js@@ -22,11 +22,14 @@// create-identity-conflict a namesake or a row the binding does not hold stands where a row would go// (a single namesake: the stop says whether it can be adopted, and prints the// --authorize adopt:<kind>:<key>@<row id> approvals when it can)-// create-completion-required an earlier create is incomplete: complete it under the same ids+// create-completion-required an earlier create is incomplete: complete it under the same ids, or let it go+// (the stop prints how: remove the item, pass the --authorize retire:... it+// names, restore the item)// create-ownership-required rows to bind: pass each printed --authorize adopt:<kind>:... after checking it// configuration-row-not-found a bound row is gone (never replaced by a namesake)// managed-pending-intent-changed the declaration changed while its create was unfinished-// managed-settlement-pending an unfinished item the App Spec no longer declares+// managed-settlement-pending an unfinished item the App Spec no longer declares: restore it, or stop+// tracking it with the printed --authorize retire:<kind>:<key>@<attempt token>// managed-binding-store-unreadable the binding store cannot be read// workspace-copy-unsent-edits a local copy differs from the server's: --authorize overwrite:<kind>:<key>const fs = require('node:fs');@@ -857,7 +860,7 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {const lines = removals.map((o) => ` • ${o.label} — ${o.detail}`);// --authorize names one change it consents to and never approves a removal on this list, so a run that was given one is// told so: otherwise "without --allow-destructive" reads as if the key it was given had been ignored.- const authorizeGiven = [opts.authorizedDestructive, opts.authorizedAdoption, opts.authorizedOverwrite, opts.authorizedWebResourceAdoption, opts.authorizedWebResourceOverwrite, opts.publicationRisk, opts.configurationApprovals,+ const authorizeGiven = [opts.authorizedDestructive, opts.authorizedAdoption, opts.authorizedOverwrite, opts.authorizedWebResourceAdoption, opts.authorizedWebResourceOverwrite, opts.publicationRisk, opts.configurationApprovals, opts.configurationRetirements,...(opts.commandStateApprovals ? [opts.commandStateApprovals.rows, opts.commandStateApprovals.tables] : [])].some((s) => s && s.size > 0);const msg = `refusing ${removals.length} destructive operation(s) without --allow-destructive${authorizeGiven ? ' (the --authorize keys given approve none of them)' : ''}:\n${lines.join('\n')}`;@@ -1010,6 +1013,7 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {// to this store and builds the configuration hookup over, and the maker's adopt:<configuration kind>:... row approvals....(deps.managedCreateGate ? { managedCreateGate: deps.managedCreateGate } : {}),...(opts.configurationApprovals ? { configurationApprovals: opts.configurationApprovals } : {}),+ ...(opts.configurationRetirements ? { configurationRetirements: opts.configurationRetirements } : {}),// commandStates: the exact --authorize tokens of the feature, the raw client its rows are read and written through, and the invocation's observer....(opts.commandStateApprovals ? { commandStateApprovals: opts.commandStateApprovals } : {}),...(deps.commandStateClient ? { commandStateClient: deps.commandStateClient } : {}),@@ -1479,6 +1483,11 @@ const readLanguageFlag = (flags) => readAliasedFlag(flags, 'language-code', 'lan// declared item is refused (CONFIGURATION_ADOPT_AMBIGUOUS). Environment variables,// connection references and Custom APIs only: a duplicate rule is never adopted, so its// and its conditions' tokens keep only the plain reading above, as in 2.24.0+// retire:<kind>:<key>@<attempt token> letting the binding store stop tracking ONE unfinished protected configuration attempt of an+// item the spec no longer declares, which may have been sent, exactly as the managed-settlement-+// pending stop printed it (lib/configuration-protected.js pendingSweep); rows it may have created+// stay in the environment, unmanaged, and nothing is deleted. Read with or without the opt-in;+// a key the spec declares is refused (CONFIGURATION_RETIRE_DECLARED) (configurationRetirements)// The family is part of the key because ids collide across families: a view and a chart may share <table>/<name>, and a view// may be named "quickFind". Each approval is stored under its family-typed id (reconcile-common.js approvalKey, the flag minus// its verb) and each guard asks only for its own family, so consent to one artifact never reaches another. The untyped form@@ -1544,7 +1553,11 @@ function authorizationKeys(argv, spec) {? `'${token}' is not adopt:<kind>:<declared key> or adopt:<child kind>:<declared key>/<declared child>, as a configuration stop prints it (ending @<row id> when it adopts a namesake)`: code === 'CONFIGURATION_ADOPT_AMBIGUOUS'? `'${token}' reads both as the approval of one declared configuration item and, ending @<row id>, as the adoption of another's namesake; it approves neither. Rename one of the two keys`- : `'${token}' is not <kind>:<declared key>:<field> for a field a configuration change can consent to`)));+ : code === 'CONFIGURATION_RETIRE_DECLARED'+ ? `'${token}' stops tracking a configuration item the spec still declares; a build of its declaration settles it instead. Remove the declaration first, or drop the approval`+ : code === 'CONFIGURATION_RETIRE_INVALID'+ ? `'${token}' is not retire:<kind>:<key>@<attempt token>, as the managed-settlement-pending stop prints it`+ : `'${token}' is not <kind>:<declared key>:<field> for a field a configuration change can consent to`)));problems.push(...commandStates.problems);// The ids each approval family's artifacts carry in this spec. A view's or chart's is the reconcile's intent key, `<table>/<name>`// with the table in lower case (a spec whose declared artifact does not compile fails validation before any key is used); a Quick@@ -1789,7 +1802,7 @@ function authorizationKeys(argv, spec) {const i = problems.findIndex((p) => p.startsWith(`'${key}' `));if (i >= 0) problems[i] += ` — ${hint}`;}- return { keys, adopt, overwrite, webResourceAdopt, webResourceOverwrite, publicationRisk, configurationApprovals: configuration.rowApprovals || new Set(), commandStateRows: commandStates.rows, commandStateTables: commandStates.tables, error: problems.length ? `--authorize: ${problems.join('; ')}` : null };+ return { keys, adopt, overwrite, webResourceAdopt, webResourceOverwrite, publicationRisk, configurationApprovals: configuration.rowApprovals || new Set(), configurationRetirements: configuration.retire || new Set(), commandStateRows: commandStates.rows, commandStateTables: commandStates.tables, error: problems.length ? `--authorize: ${problems.join('; ')}` : null };}function parseLanguageCode(value) {@@ -2017,6 +2030,7 @@ async function main() {...(authorization.webResourceOverwrite.size ? { authorizedWebResourceOverwrite: authorization.webResourceOverwrite } : {}),...(authorization.publicationRisk.size ? { publicationRisk: authorization.publicationRisk } : {}),...(authorization.configurationApprovals.size ? { configurationApprovals: authorization.configurationApprovals } : {}),+ ...(authorization.configurationRetirements.size ? { configurationRetirements: authorization.configurationRetirements } : {}),...(authorization.commandStateRows.size || authorization.commandStateTables.size ? { commandStateApprovals: { rows: authorization.commandStateRows, tables: authorization.commandStateTables } } : {}),nonInteractive: flags['non-interactive'] === true || envTruthy(process.env.POWER_PLATFORM_SKILLS_NONINTERACTIVE),languageCode,diff --git a/plugins/model-apps/scripts/lib/app-components.js b/plugins/model-apps/scripts/lib/app-components.jsindex 90d78813b..6a518b66c 100644--- a/plugins/model-apps/scripts/lib/app-components.js+++ b/plugins/model-apps/scripts/lib/app-components.js@@ -289,6 +289,15 @@ function declaredForms(created) {return out;}+// Every view id the build's result.created records: the `entity|name` entries, then each declared view that shares its name with another+// one on its table and so has no entry of its own (sdk-build.js, the views step: `sameNamedViews`, { entity, name, key, id }). A spec+// without such views has no `sameNamedViews`, so this is exactly the values of `created.views`, as before.+function createdViewIds(created) {+ const ids = Object.values((created && created.views) || {}).filter(Boolean);+ for (const v of (created && created.sameNamedViews) || []) if (v && v.id && !ids.includes(v.id)) ids.push(v.id);+ return ids;+}+// The components a NEW app is created with. The legacy projection (no `declared`) is what every existing spec sends: one// Main form per table, the views and the charts. `declared: true` (app.pinDeclaredArtifacts) lists every declared form —// other Main forms and Quick Create forms included — and the dashboards, still leaving out a Main form that a Main-form@@ -301,7 +310,7 @@ function appComponentsFor(created, mainFormsByTable, { declared = false } = {}): Object.entries(created.forms || {}).filter(([table, id]) => id && allowed(table, id)).map(([, id]) => id);return {forms,- views: Object.values(created.views || {}).filter(Boolean),+ views: createdViewIds(created),charts: Object.values(created.charts || {}).filter(Boolean),...(declared ? { dashboards: Object.values(created.dashboards || {}).filter(Boolean) } : {}),...(mainFormsByTable === undefined ? {} : { mainFormsByTable }),@@ -348,7 +357,7 @@ async function applyAppMainForms(provision, appId, mainFormsByTable, { mainForms// declared form is listed (declaredForms); pinDeclaredArtifacts then drops a Main form the Main-form list leaves out.function declaredAppPins(created) {const values = (map) => Object.values(map || {}).filter(Boolean);- return { forms: declaredForms(created).map((form) => form.id), views: values(created && created.views), charts: values(created && created.charts), dashboards: values(created && created.dashboards) };+ return { forms: declaredForms(created).map((form) => form.id), views: createdViewIds(created), charts: values(created && created.charts), dashboards: values(created && created.dashboards) };}// app.pinDeclaredArtifacts: add the declared ids to the app copy's explicit pins before a push. A fetch carries no@@ -844,7 +853,7 @@ async function appEntityComponentsFor(sdk, appUnique, wanted) {module.exports = {currentAppLayer, currentLayerRows, currentLayerRow, savedPageRows, publishedAppLayer, appComponentRows, collectionRows, tableRefs, tableComponentIds, pinAppTables,- publishAppComponents, appComponentsFor, applyAppMainForms, explainAppPushWarnings, declaredAppPins, pinDeclaredArtifacts, exactMembershipOutcome,+ publishAppComponents, appComponentsFor, applyAppMainForms, explainAppPushWarnings, declaredAppPins, pinDeclaredArtifacts, createdViewIds, exactMembershipOutcome,resolveMainForms, readMainFormMembership, publishedMainFormsProof, appMainFormsFor, appEntityComponentsFor,APP_COMPONENT_ENTITY_SOURCES, TABLE_NAME, readAppComponentInventory, appComponentEntities, downloadAppMainForms, setAppMembershipFloor, setAppThemeFloor,};diff --git a/plugins/model-apps/scripts/lib/classify-changes.js b/plugins/model-apps/scripts/lib/classify-changes.jsindex c28ba5e6a..10a36cd63 100644--- a/plugins/model-apps/scripts/lib/classify-changes.js+++ b/plugins/model-apps/scripts/lib/classify-changes.js@@ -117,11 +117,26 @@ function classifyPages(cur, prior) {// #3 views: every changed view must be a PURE COLUMN APPEND (prior columns are an exact prefix of current;// everything else identical). A removed/reordered/edited column set does NOT converge (the engine only// UNIONS columns and never removes/reorders) → full build + debt. A new view → full build creates it.+//+// #845: two declared views may share one name on one table under two keys (views[].key). Aligned by `entity|name` alone, the+// later of the two takes the place of the earlier on both sides (indexBy keeps the last), so an edit of the earlier one was not+// seen at all. A name shared that way is aligned by its name AND key instead (viewAlignment). A shared name whose views cannot+// all be told apart by a key of their own (a legacy workspace, a key missing or repeated) cannot be aligned: if anything in it+// changed, which view changed cannot be said, so it is a full build with debt, as a non-append edit is.function classifyViews(cur, prior) {const out = { fast: [], full: [], debt: [] };- const { added, removed, common } = alignByIdentity(cur.views, prior.views, identityOf.view);+ const { alignKey, label, debtIdentity, unalignable } = viewAlignment(cur.views, prior.views);+ for (const [id, sides] of unalignable) {+ if (stableStringify(sides.cur) === stableStringify(sides.prior)) continue;+ out.full.push(`views: the views named '${id}' share their name on the table without a key of their own each, and one of them changed — which one cannot be told, so it is not convergent`);+ out.debt.push({ artifactType: 'view', identity: id, reason: 'view-nonappend-edit' });+ }+ const alignable = (arr) => (Array.isArray(arr) ? arr.filter((v) => !(v && typeof v === 'object' && unalignable.has(identityOf.view(v)))) : arr);+ const aligned = alignByIdentity(alignable(cur.views), alignable(prior.views), alignKey);+ const named = (e) => ({ ...e, id: label(e.cur || e.prior), debtId: debtIdentity(e.cur || e.prior) });+ const [added, removed, common] = [aligned.added.map(named), aligned.removed.map(named), aligned.common.map(named)];if (added.length) out.full.push(`views: ${added.length} new view(s) added — a new artifact needs a full build`);- for (const r of removed) { out.full.push(`views: view '${r.id}' removed`); out.debt.push({ artifactType: 'view', identity: r.id, reason: 'view-removed' }); }+ for (const r of removed) { out.full.push(`views: view '${r.id}' removed`); out.debt.push({ artifactType: 'view', identity: r.debtId, reason: 'view-removed' }); }for (const c of common) {const restSame = equalExcept(c.cur, c.prior, ['columns']);const colsSame = stableStringify(c.cur.columns || []) === stableStringify(c.prior.columns || []);@@ -132,12 +147,44 @@ function classifyViews(cur, prior) {// width/order/filter/sort change, a non-append column edit, or a removal/reorder — the additive// engine only unions columns, so this cannot be converged incrementally.out.full.push(`views: view '${c.id}' changed beyond a pure column-append (reorder/remove/width/filter/sort) — not convergent`);- out.debt.push({ artifactType: 'view', identity: c.id, reason: 'view-nonappend-edit' });+ out.debt.push({ artifactType: 'view', identity: c.debtId, reason: 'view-nonappend-edit' });}}return out;}+// How classifyViews aligns the current views with the prior ones. A name (`entity|name`, identityOf.view) held by one view on each+// side aligns by that name, exactly as before. A name held by two or more views on either side aligns by [name, key] when every one+// of them, on both sides, has a key of its own (a non-empty string, not repeated): JSON, so it cannot collide with a plain name.+// Otherwise the name is `unalignable` (id -> { cur, prior }: its views on each side, in order). `label` is how a message names a+// view: its `entity|name`, plus its key when the name is shared. A debt entry names it by `debtIdentity` instead, which is its+// alignment key: `entity|name` for a name held once, exactly as before, and the [name, key] JSON for a shared one. The label is+// for a person and cannot be the identity: a view may be named like another's label ("Twin (view key v2)" beside the keyed Twin+// v2), and the snapshot keeps one entry per identity (apply-snapshot.js addDebt), so two changed views would owe one debt. JSON+// cannot collide with a plain name: no table's logical name starts with '['.+function viewAlignment(curViews, priorViews) {+ const side = (arr) => (Array.isArray(arr) ? arr.filter((v) => v && typeof v === 'object') : []);+ const groups = new Map();+ for (const [name, arr] of [['cur', side(curViews)], ['prior', side(priorViews)]]) {+ for (const v of arr) {+ const id = identityOf.view(v);+ if (!groups.has(id)) groups.set(id, { cur: [], prior: [] });+ groups.get(id)[name].push(v);+ }+ }+ const ownKeys = (members) => members.every((v) => typeof v.key === 'string' && v.key !== '') && new Set(members.map((v) => v.key)).size === members.length;+ const keyed = new Set();+ const unalignable = new Map();+ for (const [id, sides] of groups) {+ if (sides.cur.length < 2 && sides.prior.length < 2) continue;+ if (ownKeys(sides.cur) && ownKeys(sides.prior)) keyed.add(id);+ else unalignable.set(id, sides);+ }+ const alignKey = (v) => (keyed.has(identityOf.view(v)) ? JSON.stringify([identityOf.view(v), v.key]) : identityOf.view(v));+ const label = (v) => (keyed.has(identityOf.view(v)) ? `${identityOf.view(v)} (view key ${v.key})` : identityOf.view(v));+ return { alignKey, label, debtIdentity: alignKey, unalignable };+}+// #4 app-shell: fast ONLY when the SITEMAP structure (appShell) changed but the app object is// byte-identical. The object is compared WHOLE, so a change to any app field — name, description,// routing description, icon — is not a sitemap-only edit.@@ -246,6 +293,11 @@ function classifyChanges(current, prior) {fullReasons.push(`${phase}: changed — always a full build`);continue;}+ // Every changed phase must account for its change: a fast shape or a reason for a full build. A phase whose slice changed+ // while its detectors found nothing (a change they do not look at, or an entry hidden by another of the same identity, #845)+ // would otherwise ride along with another phase's fast shape — a pages-only run would then skip it and record the new spec+ // as applied. So it is a full build, as it already is when no phase found anything (below).+ const before = fastChanges.length + fullReasons.length;switch (phase) {case 'pages': merge(classifyPages(cur, prior)); break;case 'views': merge(classifyViews(cur, prior)); break;@@ -279,6 +331,7 @@ function classifyChanges(current, prior) {// An unrecognized changed phase must never silently pass as fast (fail-closed).fullReasons.push(`${phase}: changed — no fast-path shape recognized`);}+ if (fastChanges.length + fullReasons.length === before) fullReasons.push(`${phase}: changed, but no change in it could be classified — full build (fail-closed)`);}// Dedup debt (a phase can push the same identity twice across detectors is unlikely, but be safe).diff --git a/plugins/model-apps/scripts/lib/configuration-artifacts.js b/plugins/model-apps/scripts/lib/configuration-artifacts.jsindex 266d865f6..7e3d8e0a5 100644--- a/plugins/model-apps/scripts/lib/configuration-artifacts.js+++ b/plugins/model-apps/scripts/lib/configuration-artifacts.js@@ -598,6 +598,8 @@ function tagged(kind, key, code, outcome, report) {// - the port's typed stops carry lower-case codes (create-identity-conflict: a row of that name sits at another// id; create-identity-unverified: the derived id could not be read; create-outcome-unknown;// create-completion-required) and pass through unchanged, so a caller can name them;+// - the port's create-refused stop (`nothingCreated`: the service refused every request unstarted and the port released+// the attempt, #847) is refused even after execute was entered: the store itself proves nothing it sent can land;// - any other failure after execute was entered is unknown: what was sent is not known.const PORT_CODE = /^create-[a-z0-9-]{2,60}$/;const UNKNOWN_PORT_CODES = new Set(['create-identity-unverified', 'create-outcome-unknown', 'create-completion-required']);@@ -608,11 +610,16 @@ function portCode(error) {function routeFailure(error, sent) {if (error && error[TAGGED]) return error.report || { bucket: error.outcome === 'nothing' ? 'refused' : 'unknown', code: error.code };const code = portCode(error);+ if (code && error.nothingCreated === true && !UNKNOWN_PORT_CODES.has(code)) return { bucket: 'refused', code, ...serviceCodeOf(error) };if (code) return { bucket: sent || UNKNOWN_PORT_CODES.has(code) ? 'unknown' : 'refused', code };if (sent) return { bucket: 'unknown', code: 'create-outcome-unknown' };return { bucket: 'refused', code: codeOf(error) === 'UNEXPECTED_ERROR' ? 'CREATE_REFUSED' : codeOf(error) };}+// The Dataverse error code a refused request was answered with (`0x80072040`), carried to the halt line; anything else+// is dropped, so a message or a value can never ride along.+const serviceCodeOf = (error) => (error && typeof error.serviceCode === 'string' && /^0x[0-9a-f]{8}$/i.test(error.serviceCode) ? { serviceCode: error.serviceCode } : {});+const portOf = (ctx) => (ctx.creates && typeof ctx.creates.run === 'function' ? ctx.creates : null);function emptyResult() {@@ -656,10 +663,13 @@ function identityStop(code, id) {// A copy that holds edits the service has not seen (an earlier run's unsent change, or one made by hand) is the maker's to// keep or drop, never this read's: it stops typed, the copy kept (the protected preflight names it first, as// workspace-copy-unsent-edits with the one approval that replaces it, overwrite:<kind>:<key>). Only a diff (lib/unsynced-edits.js), no request; a copy the workspace does not hold reads clean, and a diff-// that cannot be made reads as edits, so a doubtful copy is kept too.+// that cannot be made reads as edits, so a doubtful copy is kept too. A copy an earlier plugin version left that the+// workspace cannot prove clean is refused by the workspace itself (lib/workspace-configuration-memory.js); that refusal+// keeps its own code (WORKSPACE_LEGACY_CONFIGURATION_COPY), whose remedy differs: delete the old files, not refresh them.async function refuseLocalDraft(sdk, kind, id) {const { hasUnsyncedEdits } = require('./unsynced-edits.js');- if (await hasUnsyncedEdits(sdk, kind, id)) throw identityStop('create-completion-required', id);+ const { isLegacyCopyRefusal } = require('./workspace-configuration-memory.js');+ if (await hasUnsyncedEdits(sdk, kind, id, { rethrow: isLegacyCopyRefusal })) throw identityStop('create-completion-required', id);}// The id a typed stop is about, when it names one, so a maker can inspect the row the next run could not read. The@@ -1889,7 +1899,7 @@ async function applyCreate(op, ctx, result, known) {const lost = routed.bucket === 'unknown' && error && error[TAGGED];pushFinding(result, routed.bucket, {kind, key, id: routed.bucket === 'unknown' && given ? given.id : undefined,- code: lost ? 'create-outcome-unknown' : routed.code, cause: lost ? routed.code : undefined,+ code: lost ? 'create-outcome-unknown' : routed.code, cause: lost ? routed.code : undefined, serviceCode: routed.serviceCode,}, routed.bucket === 'unknown' ? handle : null);return;}@@ -2042,7 +2052,7 @@ async function applyUpdate(op, ctx, result, known) {const routed = routeFailure(error, false);// A write (not a create) whose answer was lost: what it changed is not known.const lost = routed.bucket === 'unknown' && error && error[TAGGED] && !error.report;- pushFinding(result, routed.bucket, { kind, key, id, code: lost ? 'CONFIGURATION_WRITE_UNKNOWN' : routed.code, cause: lost ? routed.code : undefined }, routed.bucket === 'unknown' ? handle : null);+ pushFinding(result, routed.bucket, { kind, key, id, code: lost ? 'CONFIGURATION_WRITE_UNKNOWN' : routed.code, cause: lost ? routed.code : undefined, serviceCode: routed.serviceCode }, routed.bucket === 'unknown' ? handle : null);return;}if (stop) { pushFinding(result, stop.bucket, { kind, key, id, code: stop.code }, handle); return; }@@ -2521,7 +2531,7 @@ function configurationContext({ sdk, creates, managed, bindings, solutionUniqueNconst configurationDestructive = (plan) => [...new Set(((plan && plan.operations) || []).filter((op) => op.destructive).flatMap((op) => op.authorize || []))];// A halt item: kind, key and fixed code, plus the tokens a refusal needs consent for (DESTRUCTIVE_CHANGE_UNAUTHORIZED's `authorize`).-const haltItem = ({ kind, key, code, authorize }) => ({ kind, key, code, ...(Array.isArray(authorize) && authorize.length ? { authorize: authorize.slice() } : {}) });+const haltItem = ({ kind, key, code, authorize, serviceCode }) => ({ kind, key, code, ...(Array.isArray(authorize) && authorize.length ? { authorize: authorize.slice() } : {}), ...serviceCodeOf({ serviceCode }) });// The configuration halt's text. A refusal that needs consent ends with the exact flags that give it, e.g.// environmentVariable contoso_Mode (DESTRUCTIVE_CHANGE_UNAUTHORIZED) (approve with --authorize environmentVariable:contoso_mode:defaultValue)@@ -2551,8 +2561,18 @@ const SAVED_UNPUBLISHED = Symbol('savedUnpublished');const UNPUBLISHED_RULE_HINT = 'saved, but its publication did not complete: publish the rule in the environment\'s duplicate detection rules settings, '+ 'or set "status": "published" on it in the App Spec and build again; a build without "status" keeps it unpublished';const markSavedUnpublished = (item) => Object.defineProperty(item, SAVED_UNPUBLISHED, { value: true, enumerable: false });+// A protected create or edit the service refused (create-refused, #847) was released in the same run, so its line says+// that nothing is pending and what to correct, naming the Dataverse error code when the answer carried one — never the+// service's message, which can echo a Key Vault reference or a connection id:+// environmentVariable contoso_Key (create-refused) (the service refused it (0x80072040): nothing was created or changed and nothing is left pending; ...)+const REFUSED_FIX = {+ environmentVariable: 'correct its value in the deployment settings (for a secret, a Key Vault secret reference this environment can read) or its definition in the App Spec',+ connectionReference: 'correct its connection in the deployment settings or its definition in the App Spec',+};+const refusedHint = (p) => `the service refused it${p.serviceCode ? ` (${p.serviceCode})` : ''}: nothing was created or changed and nothing is left pending; `+ + `${REFUSED_FIX[p.kind] || 'correct its definition in the App Spec'}, then build again, or remove it from the App Spec`;function configurationHaltMessage(items) {- const hint = (p) => (p[SAVED_UNPUBLISHED] && p.kind === 'duplicateRule' ? ` (${UNPUBLISHED_RULE_HINT})` : '');+ const hint = (p) => (p[SAVED_UNPUBLISHED] && p.kind === 'duplicateRule' ? ` (${UNPUBLISHED_RULE_HINT})` : p.code === 'create-refused' ? ` (${refusedHint(p)})` : '');const line = (p) => `${p.kind} ${p.key} (${p.code})${p.authorize && p.authorize.length ? ` (approve with ${authorizeFlags(p.authorize)})` : ''}${hint(p)}`;return `${items.length} configuration item${items.length === 1 ? '' : 's'} not completed: ${items.map(line).join(', ')}`;}@@ -2617,7 +2637,7 @@ const TOKEN_ROOTS = Object.freeze({// Sort the `--authorize` tokens the maker passed: those of this module's kinds are checked against the App Spec// (the root must be declared; the field must be one a plan can ask for) and normalized exactly as a plan writes them// (lower-cased names and child names; a rule's key and a condition's key byte for byte). Tokens of other kinds are-// answered unclaimed, for their own grammar. `{keys: Set, overwrite: Set, rowApprovals: Set, problems: [{token, code}], unclaimed: [token]}`.+// answered unclaimed, for their own grammar. `{keys: Set, overwrite: Set, retire: Set, rowApprovals: Set, problems: [{token, code}], unclaimed: [token]}`.// `overwrite:<kind>:<declared key>` (e.g. overwrite:customApi:contoso_Calc) is the one approval that replaces a protected// item's local workspace copy with the server's (lib/configuration-protected.js, the preflight's stop on a copy that// differs). It names a whole root item, matched as the other tokens are (a duplicate rule's key exactly), and is read only@@ -2657,9 +2677,19 @@ const ADOPT_CHILD_TOKEN = /^adopt:(environmentVariableValue|customApiRequestParaconst ADOPT_CHILD_PARENT = Object.freeze({environmentVariableValue: 'environmentVariable', customApiRequestParameter: 'customApi', customApiResponseProperty: 'customApi', duplicateRuleCondition: 'duplicateRule',});+// `retire:<kind>:<key>@<attempt token>` (#847) lets the binding store stop tracking ONE unfinished protected attempt of an+// item the App Spec no longer declares, which may have been sent (configuration-protected.js pendingSweep prints it with+// the attempt's own random token and the key as the store keys it), e.g.+// retire:environmentVariable:contoso_key@6f1c2b9e-1d3a-4c5e-9f00-0a1b2c3d4e5f+// The key is everything between the kind and the LAST '@' (a token holds none; a duplicate-rule key may). It names an+// item the App Spec does NOT declare (a declared one is settled by its own build: CONFIGURATION_RETIRE_DECLARED) and is+// read with or without the opt-in, since the store's debt is swept either way. It lands in `retire` as+// `<kind>\u0000<port key>\u0000<token>` (lower-case token); the sweep matches it to the attempt exactly.+const RETIRE_TOKEN = /^retire:(environmentVariable|connectionReference|customApi|duplicateRule):([\s\S]+)@([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;function configurationAuthorizationKeys(tokens, spec) {const keys = new Set();const overwrite = new Set();+ const retire = new Set();const rowApprovals = new Set();const problems = [];const unclaimed = [];@@ -2688,6 +2718,13 @@ function configurationAuthorizationKeys(tokens, spec) {const protectedSpec = isObject(spec) && spec.configurationIdentity === 'stable-v1';for (const token of tokens || []) {const text = typeof token === 'string' ? token : '';+ if (text.startsWith('retire:')) {+ const m = RETIRE_TOKEN.exec(text);+ if (!m) problems.push({ token: text, code: 'CONFIGURATION_RETIRE_INVALID' });+ else if (rootOf(m[1], m[2])) problems.push({ token: text, code: 'CONFIGURATION_RETIRE_DECLARED' });+ else retire.add(`${m[1]}\u0000${portKeyOf(m[1], m[2])}\u0000${m[3].toLowerCase()}`);+ continue;+ }const replace = OVERWRITE_TOKEN.exec(text);if (replace) {const [, kind, name] = replace;@@ -2753,7 +2790,7 @@ function configurationAuthorizationKeys(tokens, spec) {if (!TOKEN_FIELDS[kind].test(tail)) { problems.push({ token: text, code: 'CONFIGURATION_AUTHORIZATION_INVALID' }); continue; }keys.add(`${kind}:${portKeyOf(kind, root)}:${tail}`);}- return { keys, overwrite, rowApprovals, problems, unclaimed };+ return { keys, overwrite, retire, rowApprovals, problems, unclaimed };}// The build runner's items for this feature: ONE data-model item and ONE solution-version item, whatever thediff --git a/plugins/model-apps/scripts/lib/configuration-build.js b/plugins/model-apps/scripts/lib/configuration-build.jsindex ea862789e..edaf2fb55 100644--- a/plugins/model-apps/scripts/lib/configuration-build.js+++ b/plugins/model-apps/scripts/lib/configuration-build.js@@ -57,19 +57,34 @@ function namedByPages(pages) {// Every stop before the build's first write: the same plan stops again, so it is RETRY.NEVER.const preflightHalt = (preflightCode, message) => new BuildHalt(message, { phase: 'preflight', code: preflightCode, recoverable: false, retry: RETRY.NEVER });+// Why the sweep let an undeclared attempt go (pendingSweep `retired[].how`), as the build's notice says it.+const RETIRED_WHY = {+ unsent: 'it was never sent',+ 'not-started': 'the service refused it and nothing was created',+ approved: 'as approved; rows it may have created stay in the environment, unmanaged',+};+/*** The binding store's own configuration debt (lib/configuration-protected.js pendingSweep, answered by the build's hookup* `opts.protectedConfiguration.sweep`), read before the build's first service change: an attempt an earlier build left* unfinished for an item this App Spec no longer declares stops the build here, with nothing sent. It runs whatever the* App Spec declares — sdk-build.js calls it directly for an App Spec that uses no configuration kind, and the runtime's- * preflight calls it first otherwise — so omitting a declaration never bypasses its debt. No hookup, nothing to read.+ * preflight calls it first otherwise — so omitting a declaration never bypasses its debt. An attempt the store let go there+ * (proved never sent, or under the maker's `retire:` approval) does not stop the build; `opts.warn` names it. No hookup,+ * nothing to read.*/function sweepPendingConfiguration(spec, opts = {}) {const sweep = opts.protectedConfiguration && opts.protectedConfiguration.sweep;if (typeof sweep !== 'function') return { halts: [] };- const { halts } = sweep({ spec });+ const { halts, retired = [] } = sweep({ spec });+ // An undeclared attempt the store let go (proved never sent, or under the maker's retire approval) is named once, so a+ // maker sees what the store stopped tracking.+ if (typeof opts.warn === 'function') {+ for (const r of retired) opts.warn(`configuration: the binding store no longer tracks the unfinished attempt for ${r.kind} ${r.key}, which this App Spec no longer declares (${RETIRED_WHY[r.how] || r.how})`);+ }if (!halts.length) return { halts };- const others = halts.slice(1).map((h) => `${h.kind} ${h.key}`);+ // Each further possibly-sent attempt keeps its own exact approval in the one stop, so one run can settle them all.+ const others = halts.slice(1).map((h) => `${h.kind} ${h.key}${Array.isArray(h.authorize) && h.authorize.length ? ` (or stop tracking it with ${C.authorizeFlags(h.authorize)})` : ''}`);throw preflightHalt(halts[0].code, `${halts[0].kind} ${halts[0].key}: ${halts[0].message}${others.length ? ` Also held: ${others.join(', ')}.` : ''}`);}diff --git a/plugins/model-apps/scripts/lib/configuration-protected.js b/plugins/model-apps/scripts/lib/configuration-protected.jsindex 88e0bf272..77dcc1a8b 100644--- a/plugins/model-apps/scripts/lib/configuration-protected.js+++ b/plugins/model-apps/scripts/lib/configuration-protected.js@@ -36,6 +36,8 @@ const CONFLICT_CODE = 'create-identity-conflict';const COMPLETION_CODE = 'create-completion-required';const OWNERSHIP_CODE = 'create-ownership-required';const OPT_IN_CODE = 'create-identity-opt-in-required';+// A create or edit the service refused unstarted and the run released (#847, refusedStop): nothing pending is left.+const REFUSED_CODE = 'create-refused';// A local workspace copy that differs from the server's: the declared views' and charts' stop (sdk-build.js// refuseUnsentCopy), with the same way on — keep what you want in the App Spec, then approve replacing the copy.const DRAFT_CODE = 'workspace-copy-unsent-edits';@@ -92,6 +94,25 @@ function stop(code, message, extra = {}) {return error;}+// #847: what the run's own answers say when the service refused its requests unstarted — the transport saw an answer+// that says a request was never carried out (managed-create-transport.js refusedUnstarted) and the store took its rows+// back to unsent (noteRowsNotStarted). Read BEFORE ctx.release, which drops the attempt's facts. Answers null, or+// { serviceCode } (the Dataverse error code the answer carried, or null). Only a stop when the release then succeeds:+// that is the store's own proof (attemptProvenUnsent) that nothing any request of the attempt carried can land.+function refusedUnsent(ctx, attempt, pushed) {+ if (pushed.checked || pushed.localError || typeof ctx.facts !== 'function') return null;+ const refused = ctx.facts(attempt.token).find((f) => f.type === 'row' && f.notStarted === true);+ return refused ? { serviceCode: typeof refused.serviceCode === 'string' ? refused.serviceCode : null } : null;+}++// The stop for a create or edit the service refused, released in the same run: nothing was created or changed and the+// store holds nothing pending for it, so the next build plans it afresh (a create again under the same derived ids).+// `nothingCreated` routes it as refused, not unknown (configuration-artifacts.js routeFailure), so later items still run.+function refusedStop(kind, key, id, { serviceCode }, what) {+ return stop(REFUSED_CODE, `the service refused the ${kind} "${key}" ${what}${serviceCode ? ` (${serviceCode})` : ''}; nothing was ${what === 'create' ? 'created' : 'changed'} and nothing is left pending`,+ { kind, key, id, nothingCreated: true, serviceCode });+}+function declaredItems(spec) {const out = [];for (const [kind, list, field] of LISTS) {@@ -303,7 +324,9 @@ async function firstCreateVerdict(dataverse, planned, { exactId }) {const rootId = planned.plan.rows[0].id;if (exactId) {const read = await B.readConfigurationRow(dataverse, planned.kind, rootId);- if (read.state === 'present') return { id: rootId, code: CONFLICT_CODE, message: `the ${planned.kind} "${planned.key}" derived id ${rootId} is taken by a row no binding holds; it is not adopted, and no service changes were sent by this build` };+ if (read.state === 'present') return { id: rootId, code: CONFLICT_CODE, message: `the ${planned.kind} "${planned.key}" derived id ${rootId} is taken by a row no binding holds; it is not adopted, and no service changes were sent by this build. `+ + 'The id is derived from this item, so the row is most likely one an earlier build of it made (one whose unfinished attempt was retired with `--authorize retire:...`, say). '+ + 'If it is, and you do not need it, delete that row in the environment, then run again' };if (read.state !== 'absent') return { id: rootId, code: UNVERIFIED_CODE, message: `the ${planned.kind} "${planned.key}" derived id ${rootId} could not be read; no service changes were sent by this build` };}const conflicts = await B.readConfigurationConflicts(dataverse, planned);@@ -764,6 +787,27 @@ async function publishOnce(env, ctx, item) {return settled.verdict;}+// The way out of a pending create that only its own ids can complete (#847). A create the service refused under an earlier+// plugin version is pending in phase "sending" with no record that nothing started (2.26.0 kept none), so it reads as+// possibly sent and a build given corrected settings still stops here: nothing proves its rows were never made, and an+// absent read alone is not that proof. The maker can let it go instead, by the exact approval the debt sweep reads+// (pendingSweep: the store stops tracking the attempt, nothing is deleted or sent). That approval is read only for an+// item the App Spec no longer declares (build-model-app.js CONFIGURATION_RETIRE_DECLARED), so the stop names the whole+// procedure, with the attempt's own token: remove the item, run with the approval, restore it. A row the attempt made+// at its derived id then stops the restored create (firstCreateVerdict), which names that row. Never for an edit or an+// adoption, which hold no create of their own to let go.+function withWayOut(item, h) {+ if (item.edit || item.adoption || !item.token || h.code !== COMPLETION_CODE) return h;+ const flags = A.authorizeFlags([retireToken(h.kind, A.portKeyOf(h.kind, h.key), item.token)]);+ return {+ ...h,+ message: `${h.message}. If it cannot be completed that way (a create an earlier plugin version left pending after the service refused it, say), `+ + `stop tracking it instead: remove this item (and its deployment-settings entry) from the App Spec and run the build again with ${flags} `+ + '(nothing is deleted or sent), then restore them and run again. If the attempt made a row at its derived id, that build stops with '+ + 'create-identity-conflict naming the row',+ };+}+const haltOf = (kind, key, verdict) => ({kind, key, ...(verdict.rows && verdict.rows[0] ? { id: verdict.rows[0].id } : {}), code: verdict.code || UNVERIFIED_CODE, message: verdict.message || `the ${kind} "${key}" could not be recovered`,...(Array.isArray(verdict.approvals) && verdict.approvals.length ? { approvals: verdict.approvals.slice() } : {}),@@ -835,7 +879,12 @@ async function preflightProtectedConfiguration({ spec, store, ctx, dataverse, so// own (a failed send included): a diff says that the copy differs, never whose the difference is.if (item.state !== 'unbound' && !item.adoption && sdk) {const id = item.planned.plan.rows[0].id;- if (await hasUnsyncedEdits(sdk, kind, id)) {+ // A copy an earlier version left that the workspace overlay cannot prove clean is refused by the SDK itself+ // (WORKSPACE_LEGACY_CONFIGURATION_COPY, naming its two files): that refusal is rethrown so the item stops with its+ // own remedy (remove those files), not the overwrite approval below, which the same refusal would defeat. Required+ // here, as in configuration-artifacts.js, so the overlay module loads only where a protected build reaches this.+ const { isLegacyCopyRefusal } = require('./workspace-configuration-memory.js');+ if (await hasUnsyncedEdits(sdk, kind, id, { rethrow: isLegacyCopyRefusal })) {if (!approvesOverwrite(authorizedOverwrite, overwriteKey(kind, item.planned.key))) {halts.push({ kind, key: item.planned.key, id, code: DRAFT_CODE, message: draftMessage(kind, item.planned.key, id), overwrite: `overwrite:${overwriteKey(kind, item.planned.key)}` });continue;@@ -863,7 +912,7 @@ async function preflightProtectedConfiguration({ spec, store, ctx, dataverse, so// A saved rule create whose initial publication provably never left: resolve sends it once (unsentPublication).const owed = unsentPublication(ctx, item, rec);if (owed && owed.would.action === 'commit') continue;- halts.push(haltOf(kind, item.planned.key, owed ? owed.would : rec.verdict));+ halts.push(withWayOut(item, haltOf(kind, item.planned.key, owed ? owed.would : rec.verdict)));continue;}// A complete edit settles read-only (resolve): nothing more is written for it, so it is not judged as an edit.@@ -1013,7 +1062,7 @@ function protectedConfigurationPort({ spec, store, ctx, dataverse, solution, binconst owed = unsentPublication(ctx, item, rec);if (owed) verdict = owed.would.action === 'commit' ? await publishOnce(await env(), ctx, item) : owed.would;if (verdict.action === 'commit') return { state: 'present', id: rootId };- const h = haltOf(kind, item.planned.key, verdict);+ const h = withWayOut(item, haltOf(kind, item.planned.key, verdict));throw stop(h.code, h.message, h);} else if (adoptionAsked(ctx, kind, item.planned.key)) {const answer = adopted(kind, await adoptNamesake(await env(), ctx, item, key));@@ -1046,9 +1095,12 @@ function protectedConfigurationPort({ spec, store, ctx, dataverse, solution, binconst id = planned.plan.rows[0].id;const childIds = Object.fromEntries(planned.rows.filter((r) => r.slot !== null).map((r) => [r.slot, r.id]));const pushed = await scope(() => fn({ id, childIds }), B.acceptResultFor(planned));- // An operation refused before its first request (nothing counted, nothing dispatched) leaves no attempt behind;- // one that may have sent anything keeps it for recovery (ctx.release refuses it). The stop below stands either way.- if (!pushed.checked) ctx.release(attempt);+ // An operation refused before its first request (nothing counted, nothing dispatched) leaves no attempt behind, and+ // so does one whose every request the service refused unstarted (#847, refusedUnsent); one that may have sent+ // anything keeps it for recovery (ctx.release refuses it). The stop below stands either way.+ const refused = refusedUnsent(ctx, attempt, pushed);+ const released = !pushed.checked && ctx.release(attempt);+ if (refused && released) throw refusedStop(kind, planned.key, id, refused, 'create');if (pushed.error) throw pushed.error;if (pushed.localError) throw stop(pushed.localError.code || UNVERIFIED_CODE, String(pushed.localError.message || pushed.localError), { kind, key: planned.key, id });if (!pushed.checked) throw stop('create-outcome-unknown', `the ${kind} "${planned.key}" create was not acknowledged`, { kind, key: planned.key, id });@@ -1109,7 +1161,11 @@ function protectedConfigurationPort({ spec, store, ctx, dataverse, solution, bin// As in run(): an edit the SDK refused before its first request — a Custom API label edit on an environment with// more than one language (CUSTOM_API_LABELS_UNSUPPORTED) — is released, so the next build plans from the committed// group whatever it declares; kept, it held the group for a declaration that is never sent.- if (!pushed.checked) ctx.release(attempt);+ // And as in run(): an edit whose every request created a new child (a variable's first value) and was refused+ // unstarted is released too (#847); a refused PATCH of a row that exists stays owed (managed-create-transport.js).+ const refused = refusedUnsent(ctx, attempt, pushed);+ const released = !pushed.checked && ctx.release(attempt);+ if (refused && released) throw refusedStop(kind, planned.key, rootId, refused, 'edit');if (pushed.error) throw pushed.error;if (pushed.localError) throw stop(pushed.localError.code || UNVERIFIED_CODE, String(pushed.localError.message || pushed.localError), { kind, key: planned.key, id: rootId });if (!pushed.checked) throw stop('create-outcome-unknown', `the ${kind} "${planned.key}" edit was not acknowledged`, { kind, key: planned.key, id: rootId });@@ -1126,23 +1182,70 @@ function protectedConfigurationPort({ spec, store, ctx, dataverse, solution, bin* The binding store's own debt, read before ANY service change of a build — whatever the App Spec declares today, with or* without the opt-in, whichever phases run: every unfinished attempt (or unusable group) of a protected configuration kind* whose item the App Spec no longer declares. Omitting a declaration never lets a build go on past what an earlier one left- * pending: its rows may exist and its effects may be owed, and only its own declaration can settle it. Nothing is retired,- * deleted or reset here, and a committed group the App Spec dropped is not debt (its rows simply stay). A declared item is- * judged by the protected preflight (or, without the opt-in, by optInObligations), so it is not listed twice.- * A local store read only: nothing is sent. Answers { halts: [{ kind, key, code, message }] }.+ * pending when its rows may exist or its effects may be owed. Three such attempts are let go here instead (#847), each by+ * the store's own checked write under its lease, and none by deleting or sending anything:+ * - one the store proves never sent: still `prepared` (retireUnsentAttempt), or `sending` with every request it counted+ * answered as not started and nothing dispatched (attemptProvenUnsent, retireProvenUnsentAttempt) — a create the+ * service refused under an earlier plugin that did not release it in the same run;+ * - one that may have been sent, only under the maker's exact approval for that attempt,+ * `--authorize retire:<kind>:<key>@<attempt token>` (`retirements`, configuration-artifacts.js+ * configurationAuthorizationKeys): the store stops tracking it (abandonAttempt), and rows it may have created stay in+ * the environment, unmanaged. A later declaration of the item is then an unbound create, whose reads stop on a row+ * already at the derived id (create-identity-conflict), so nothing is created twice or bound unseen.+ * Anything else — an attempt that may have been sent with no approval, a store write that is refused, or a group the store+ * cannot use — still stops the build, and the stop for a possibly-sent attempt prints the exact approval. A committed group+ * the App Spec dropped is not debt (its rows simply stay). A declared item is judged by the protected preflight (or,+ * without the opt-in, by optInObligations), so it is not listed twice. Nothing is sent. Answers+ * { halts: [{ kind, key, code, message, authorize? }], retired: [{ kind, key, how }] }.*/-function pendingSweep({ spec, store }) {- if (!store || typeof store.snapshot !== 'function') return { halts: [] };+function pendingSweep({ spec, store, retirements = [] }) {+ if (!store || typeof store.snapshot !== 'function') return { halts: [], retired: [] };if (typeof store.refresh === 'function') store.refresh();const declared = new Set(declaredItems(spec || {}).map(({ kind, key }) => `${kind}\u0000${A.portKeyOf(kind, key)}`));+ const approved = new Set(retirements);const halts = [];+ const retired = [];for (const unit of store.snapshot().units()) {if (!KINDS.has(unit.family) || !(unit.attempt || unit.invalid) || declared.has(`${unit.family}\u0000${unit.key}`)) continue;- const what = unit.attempt ? 'an unfinished attempt' : 'a record it cannot use';- halts.push({ kind: unit.family, key: unit.key, code: PENDING_CODE, message: `the binding store holds ${what} for ${unit.family} "${unit.key}", which this App Spec no longer declares. `- + 'Restore its declaration, with configurationIdentity "stable-v1", so a build can settle it, then run again. No service changes were sent by this build.' });+ const name = `${unit.family} "${unit.key}"`;+ if (unit.invalid || !unit.attempt) {+ halts.push({ kind: unit.family, key: unit.key, code: PENDING_CODE, message: `the binding store holds a record it cannot use for ${name}, which this App Spec no longer declares. `+ + 'Restore its declaration, with configurationIdentity "stable-v1", so a build can settle it, then run again. No service changes were sent by this build.' });+ continue;+ }+ const a = unit.attempt;+ const how = a.phase === 'prepared' ? 'unsent' : attemptProvenUnsent(a, unit.effects) ? 'not-started' : approved.has(retireKey(unit.family, unit.key, a.token)) ? 'approved' : null;+ if (how && retireUndeclared(store, unit, a, how)) {+ retired.push({ kind: unit.family, key: unit.key, how });+ continue;+ }+ const token = retireToken(unit.family, unit.key, a.token);+ halts.push({ kind: unit.family, key: unit.key, code: PENDING_CODE, authorize: [token], message: `the binding store holds an unfinished attempt for ${name}, which this App Spec no longer declares. `+ + 'Restore its declaration, with configurationIdentity "stable-v1", so a build can settle it, then run again. '+ + `It may have been sent, so it is not dropped silently: to stop tracking it, run again with ${A.authorizeFlags([token])}. Rows it may have created at its derived ids then stay in the environment, unmanaged; nothing is deleted. `+ + 'No service changes were sent by this build.' });+ }+ return { halts, retired };+}++// The approval of one undeclared attempt: `retire:<kind>:<key>@<attempt token>`, the key as the store keys it (portKeyOf)+// and the attempt's own random token, so an approval never carries over to another attempt of the same item.+const retireToken = (kind, key, token) => `retire:${kind}:${key}@${token}`;+// The same approval as configuration-artifacts.js configurationAuthorizationKeys files it (`retire`): NUL-joined, so a+// duplicate-rule key that holds ':' or '@' cannot run into the token.+const retireKey = (kind, key, token) => `${kind}\u0000${key}\u0000${token}`;++// One undeclared attempt let go by the store's own checked write (pendingSweep). Answers true when it was retired, false+// when the store refused (another invocation changed it, or it is not what the snapshot showed): the stop then stands.+function retireUndeclared(store, unit, a, how) {+ try {+ if (how === 'unsent') store.retireUnsentAttempt({ token: a.token, baseGeneration: a.baseGeneration });+ else if (how === 'not-started') store.retireProvenUnsentAttempt({ token: a.token, epoch: a.sendWindow.epoch });+ else store.abandonAttempt({ token: a.token, family: unit.family, key: unit.key });+ return true;+ } catch {+ return false;}- return { halts };}/**@@ -1152,7 +1255,7 @@ function pendingSweep({ spec, store }) {* the local store read a build without the opt-in runs (optInObligations), and sweep is the store-driven debt read every* build runs before its first service change (pendingSweep). Nothing here creates a gate or a store: the build owns them.*/-function createProtectedConfiguration({ store, gate, ctx, apiBase = null } = {}) {+function createProtectedConfiguration({ store, gate, ctx, apiBase = null, retirements = [] } = {}) {if (!store || typeof store.readGroup !== 'function') throw new TypeError('createProtectedConfiguration needs the managed binding store');if (!ctx || typeof ctx.begin !== 'function' || typeof ctx.run !== 'function' || typeof ctx.settle !== 'function') throw new TypeError('createProtectedConfiguration needs the managed create context');return {@@ -1164,7 +1267,7 @@ function createProtectedConfiguration({ store, gate, ctx, apiBase = null } = {})// A build without the opt-in: what the store still holds for its declared items (optInObligations), read locally.obligations: ({ spec }) => optInObligations({ spec, store }),// Every build, before its first service change: what the store still owes for items the App Spec no longer declares.- sweep: ({ spec }) => pendingSweep({ spec, store }),+ sweep: ({ spec }) => pendingSweep({ spec, store, retirements }),};}diff --git a/plugins/model-apps/scripts/lib/maker-sdk.js b/plugins/model-apps/scripts/lib/maker-sdk.jsindex c22b0e3eb..31c88c072 100644--- a/plugins/model-apps/scripts/lib/maker-sdk.js+++ b/plugins/model-apps/scripts/lib/maker-sdk.js@@ -32,12 +32,37 @@// The `workspaceStorage` the caller names is handed to the SDK with one addition too (lib/output-redaction.js): every text it is asked to write has the access tokens this process obtained taken out of it. The SDK writes each file// of its workspace — an artifact, its metadata, the manifest — through the storage's `writeTextAtomic`, and through nothing else, so a token a service repeated in an answer (which is the caller's data and is returned as it came) cannot// land in a file. The folder, the paths and every other member are the storage's own: the wrapper has it for a prototype, so a caller's `instanceof` and the SDK's own look for a file-system storage still hold.+// Over it, the copies the SDK keeps of the two configuration kinds that carry what a deployment is given — environment variables (their current value,+// default value, value schema, and for a secret the Key Vault reference the build sends) and connection references (their connection id) — are kept in+// this instance's memory and never reach the storage (lib/workspace-configuration-memory.js, #846/#847): the SDK still creates, pushes and reads them+// back within the run, but no file of any workspace — the build's throwaway one or the app folder's `.maker-workspace` — holds one at rest, even when the+// process dies between two steps. A copy an earlier plugin version left there is never deleted or hidden by this plugin: one+// the SDK's own metadata proves clean is left in place and never used as configuration (it is read only to prove it clean), anything else is refused (WORKSPACE_LEGACY_CONFIGURATION_COPY) at the+// SDK's first touch of that artifact, and the folders still holding such files are named in one warning per workspace per process.const bundle = require('../vendor/cds-maker-sdk.cjs');const { loadVendoredTypeScript } = require('./typescript-compiler.js');const { guardPageNesting } = require('./page-nesting.js');const { guardTableLists } = require('./collection-answers.js');const { guardAppHeaderWrites } = require('./app-header-text.js');const { guardWorkspaceStorage } = require('./output-redaction.js');+const { keepSensitiveConfigurationInMemory, legacyCopyFolders, legacyCopyWarning } = require('./workspace-configuration-memory.js');++// Workspace folders already warned about in this process: a build makes several SDKs over one folder, and the maker needs the+// warning once, not once per instance.+const warnedLegacyFolders = new Set();++// Names the sensitive folders of `storage` that still hold files an earlier plugin version wrote (names only, never content),+// on stderr as every script's warnings are. Telling the maker must never stop an SDK from being made, so a failure is ignored.+function warnLegacyCopies(storage) {+ try {+ const root = typeof storage.getRoot === 'function' ? storage.getRoot() : null;+ if (typeof root !== 'string' || warnedLegacyFolders.has(root)) return;+ const folders = legacyCopyFolders(storage);+ if (folders.length === 0) return;+ warnedLegacyFolders.add(root);+ process.stderr.write(`WARNING: ${legacyCopyWarning(root, folders)}\n`);+ } catch { /* the warning is advice; the SDK is made regardless */ }+}// `create` given the vendored compiler unless the options name one, and — only for a caller that asked — the Power Apps service client// (a seam for the test: the bundle's own exports are read-only). The `connectivity` request itself is the factory's, never the SDK's.@@ -56,7 +81,15 @@ function withVendoredCompiler(create) {}if (made.httpClient) made.httpClient = guardTableLists(made.httpClient, (code, message) => new bundle.SdkError(code, message));if (made.httpClient) made.httpClient = guardAppHeaderWrites(made.httpClient, (code, message) => new bundle.SdkError(code, message));- if (made.workspaceStorage) made.workspaceStorage = guardWorkspaceStorage(made.workspaceStorage);+ if (made.workspaceStorage) {+ // Outermost, so a sensitive copy never even reaches the token guard's write; the caller's storage stays the prototype.+ const own = made.workspaceStorage;+ made.workspaceStorage = keepSensitiveConfigurationInMemory(guardWorkspaceStorage(own), {+ prototype: own,+ refuse: (code, message) => new bundle.SdkError(code, message),+ });+ warnLegacyCopies(own);+ }if (connectivity && made.powerAppsServiceClient === undefined) {// Required here, not at the top: the client pulls in the Azure CLI token code, which an instance that never reads connections does not need.const { createPowerAppsServiceClient } = require('./power-apps-service-client.js');diff --git a/plugins/model-apps/scripts/lib/managed-bindings.js b/plugins/model-apps/scripts/lib/managed-bindings.jsindex 123594522..86c432c7d 100644--- a/plugins/model-apps/scripts/lib/managed-bindings.js+++ b/plugins/model-apps/scripts/lib/managed-bindings.js@@ -2473,6 +2473,48 @@ function openManagedBindings({ workspaceDir, environment, appUniqueName, solutioif (a.sendWindow) a.sendWindow.possible += 1;});},+ /**+ * The send-once transport (lib/managed-create-transport.js), after the service answered ONE sealed create request (a+ * POST whose every row is a create) with a rejection that says it was not carried out (lib/managed-feature-contract.js+ * notStartedAnswer: a 400, 403, 404 or 412 carrying a Dataverse error code, or a 412 to an If-Match request; never a+ * `$batch`), while the scope that sent it was+ * still open (#847). A single Dataverse operation that fails is rolled back whole — a deep insert's children with its+ * root — and the client never re-sends a send-once request, so nothing that request carried exists: its rows go back+ * to what they were before sealRowDispatch (`dispatched: false`, no sealed projection) and its one count moves from+ * `possible` to `notStarted`, in one write. Then the attempt's own record proves nothing it sent can land+ * (attemptProvenUnsent) unless another of its requests was dispatched, and the run that holds it can release it+ * (retireProvenUnsentAttempt) instead of leaving a pending create no later build can settle.+ * rows: [{ kind, key, id, sentSha256 }] — exactly the rows that request sealed, each still dispatched under that same+ * sealed projection. Checked under the lease against the record reread there: a configuration attempt still sending,+ * with an observed send window at exactly `epoch` that counts at least one possible send. Anything else (another run+ * claimed the attempt, a row was never sealed or was sealed by another request) is refused with nothing written, and+ * the attempt stays possibly sent: a refusal here only ever leaves the stricter state.+ */+ noteRowsNotStarted({ token, epoch, rows } = {}) {+ if (!Array.isArray(rows) || rows.length === 0) throw storeError(CODES.notSettled, 'noteRowsNotStarted needs the rows the refused request carried');+ if (!Number.isInteger(epoch)) throw storeError(CODES.notSettled, 'noteRowsNotStarted needs the send window epoch the request was sent under');+ mutate((env, disk, spend) => {+ const a = sendingRowAttempt(env, disk, token, epoch);+ spend(token);+ const name = `the managed ${a.family} "${a.key}"`;+ if (!a.sendWindow || a.sendWindow.epoch !== epoch || a.sendWindow.possible < 1) throw storeError(CODES.notSettled, `${name} attempt has no counted send at this epoch to answer`);+ const found = rows.map((s) => {+ const r = a.rowProtocol.rows.find((x) => x.kind === s.kind && x.key === s.key);+ if (!r || r.id !== normalizeGuid(s.id) || !r.dispatched || r.sentSha256 !== s.sentSha256) {+ throw storeError(CODES.requestMismatch, `the ${s.kind} row ${s.id} of ${name} is not dispatched under the request that was refused; it stays possibly sent`);+ }+ return r;+ });+ if (new Set(found).size !== found.length) throw storeError(CODES.requestMismatch, `the refused request of ${name} names one row twice; it stays possibly sent`);+ for (const r of found) {+ r.sentFields = null;+ r.sentSha256 = null;+ r.dispatched = false;+ }+ a.sendWindow.possible -= 1;+ a.sendWindow.notStarted += 1;+ });+ },/** Mark one completion effect (a solution membership, a rule's state) of a sending configuration attempt dispatched, before it leaves. */markRowEffectDispatch({ token, epoch, kind, id } = {}) {mutate((env, disk, spend) => {@@ -2777,6 +2819,33 @@ function openManagedBindings({ workspaceDir, environment, appUniqueName, solutioif (barrier) barrier.release(token);return { retired: true, effects: removed };},+ /**+ * Stop tracking the unfinished configuration attempt `token` of (`family`, `key`), under the maker's exact approval+ * (`--authorize retire:<family>:<key>@<token>`, lib/configuration-protected.js pendingSweep) — for an item the App+ * Spec no longer declares, whose attempt may have been sent, so neither retire above applies (#847: a create whose+ * answer was lost, or one an earlier plugin left pending after the service refused it). Without this an attempt+ * nobody declares any more could never be settled (only its own declaration settles it) and every build of the app+ * stopped on it. Nothing is deleted or sent: one write removes only that attempt and the effects it owns; its+ * committed group, if any, its publication debt and every other attempt and effect stay. Rows the attempt may have+ * created stay on the service, unmanaged — a later declaration of the item goes through the unbound create path, whose+ * reads stop on a row already at the derived id, so nothing is ever created twice or bound unseen. Checked under the+ * lease against the record reread there: the attempt must still be `token`, of a configuration family, for exactly+ * that family and key (an approval given for one attempt never retires another). Answers { retired: true, effects }.+ */+ abandonAttempt({ token, family, key } = {}) {+ if (typeof token !== 'string' || !token) throw storeError(CODES.notSettled, 'abandonAttempt needs the attempt token');+ let removed = 0;+ mutate((env, disk) => {+ const a = requireAttempt(env, disk, token);+ if (!isRowFamily(a.family) || a.family !== family || a.key !== key) throw storeError(CODES.notSettled, `the attempt ${token} is not the configuration attempt of the managed ${family} "${key}"; nothing is retired`);+ const owned = env.workflowEffects.filter((e) => e.attemptToken === a.token);+ env.attempts = env.attempts.filter((x) => x !== a);+ env.workflowEffects = env.workflowEffects.filter((e) => e.attemptToken !== a.token);+ removed = owned.length;+ });+ if (barrier) barrier.release(token);+ return { retired: true, effects: removed };+ },/*** Step 1 of a retirement: observe the group (`family`, `key`) BEFORE the fresh service reads that prove its root* absent. Rereads the file and answers { observation }: an opaque fingerprint of the group, its pending attempt anddiff --git a/plugins/model-apps/scripts/lib/managed-create-transport.js b/plugins/model-apps/scripts/lib/managed-create-transport.jsindex ec9ae81bc..408c23ec3 100644--- a/plugins/model-apps/scripts/lib/managed-create-transport.js+++ b/plugins/model-apps/scripts/lib/managed-create-transport.js@@ -26,7 +26,9 @@// - a mutation the classifier does not recognise, a token outside the set, a row the protocol does not name under// that id and parent, or a row or effect already sent once in this scope or by an earlier run.// Response facts are kept in memory only, per row and effect (see answerOf); they are evidence a driver turns into-// receipts after a fresh read (lib/managed-create-context.js), never a binding by themselves.+// receipts after a fresh read (lib/managed-create-context.js), never a binding by themselves. One answer also writes the+// store: a row request the service refused with an answer that says it was never carried out is un-sealed again+// (managed-bindings.js noteRowsNotStarted), so the run can release an attempt nothing of which exists (#847).// Every local refusal or store failure is also recorded in the scope: the SDK may catch the thrown error and report its// own (or nothing), so runWithManagedCreateSet answers the FIRST local failure as `localError`, and a caller must surface// it as the typed local failure it is — never as a network error to retry, and never as a saved result.@@ -190,7 +192,9 @@ function memberNameRepeats(text, arrays) {* `expect`: null for a completion effect (only its status is read); otherwise { id, table?, key?, children? } — the* row the request prepared, its entity set and primary-key field, and [{ id, at, key, match }] for each deep-insert* child to find in the body's `at` array by its `match` fields. A string is taken as { id }.- * A non-2xx answer is not treated as "not started" here: only a fresh read decides what is there.+ * A non-2xx answer is never an outcome but `unknown` here. Only one kind of rejection is used at all, and not as an+ * outcome: an answer that says a create request was never carried out (managed-feature-contract.js notStartedAnswer)+ * un-seals the rows of that one request in the store (rowHandle, refusedUnstarted); everything else waits for a fresh read.*/function answerOf(res, expect) {const status = res && Number.isInteger(res.statusCode) ? res.statusCode : res && Number.isInteger(res.status) ? res.status : null;@@ -288,7 +292,7 @@ function checkRows(scope, store, c) {return rows;}-function rowHandle(scope, store, entry, c, rows) {+function rowHandle(scope, store, entry, c, rows, req) {for (const r of rows) scope.sent.add(`row\u0000${c.token}\u0000${r.id}`);const expectId = c.expectId === undefined ? rows[0].id : c.expectId === null ? null : normalizeGuid(c.expectId);const expect = { id: expectId, table: c.expectTable, key: c.expectKey, children: rows.filter((r) => r.answer).map((r) => ({ id: r.id, ...r.answer })) };@@ -309,11 +313,35 @@ function rowHandle(scope, store, entry, c, rows) {if (state.answered || scope.closed) return;state.answered = true;// The answer is to the whole request: a deep insert is one transaction, so every row it carried shares it.- scope.facts.push(...fact(answerOf(res, expect)));+ const answer = answerOf(res, expect);+ const refused = answer.outcome === 'unknown' && state.dispatched ? refusedUnstarted(store, entry, c.token, rows, req, res) : null;+ scope.facts.push(...fact(refused ? { ...answer, ...refused } : answer));},};}+// #847: a rejection that says a CREATE request was never carried out (notStartedAnswer) un-seals the rows it carried in+// the store (managed-bindings.js noteRowsNotStarted), so the run can release an attempt nothing of which exists instead of+// leaving a pending create that no later build can settle. Only a POST whose every row is a create (a root's deep insert,+// or a new child such as a variable's value row): an edit of a row that exists (a PATCH) keeps its pinned recovery, where+// a refused edit stays owed until a fresh read settles it. The fact stays `unknown` (no answer here is ever a receipt);+// `notStarted` only says the store now records the request as not started, and `serviceCode` is the Dataverse error code+// the answer carried (`0x80072040`, never its message, which can echo what was sent). Best effort and never a throw into+// the SDK's answer path: a store that refuses or cannot be written leaves the rows possibly sent, the stricter state, and+// the attempt on its usual recovery path. Loaded lazily: only a refused request needs the contract module, which itself+// loads the store.+function refusedUnstarted(store, entry, token, rows, req, res) {+ if (!req || req.method !== 'POST' || !rows.every((r) => r.mode === 'create') || typeof store.noteRowsNotStarted !== 'function') return null;+ const { notStartedAnswer, dataverseErrorCode } = require('./managed-feature-contract.js');+ if (!notStartedAnswer(req, res)) return null;+ try {+ store.noteRowsNotStarted({ token, epoch: entry.epoch, rows: rows.map(({ kind, key, id, sentSha256 }) => ({ kind, key, id, sentSha256 })) });+ } catch {+ return null;+ }+ return { notStarted: true, serviceCode: dataverseErrorCode(res.body) };+}+function effectHandle(scope, store, entry, c) {const id = normalizeGuid(c.id);if (c.kind !== 'membership' && c.kind !== 'rule-state') throw mismatch(`a completion effect of kind ${c.kind} is not one a create set prepares; it was not sent`);@@ -451,7 +479,7 @@ function createDeferredManagedCreateGate() {if (!c) throw mismatch(`a ${m} was not sent: it is not a change the protected ${scope.label} prepared`);const entry = scope.entries.get(c.token);if (!entry) throw mismatch(`a ${m} was not sent: it names an attempt outside this create set`);- if (c.type === 'rows') return rowHandle(scope, store, entry, c, checkRows(scope, store, c));+ if (c.type === 'rows') return rowHandle(scope, store, entry, c, checkRows(scope, store, c), { method: m, url, headers });if (c.type === 'effect') return effectHandle(scope, store, entry, c);throw mismatch(`a ${m} was not sent: the classifier answered an unknown request type`);});diff --git a/plugins/model-apps/scripts/lib/managed-feature-contract.js b/plugins/model-apps/scripts/lib/managed-feature-contract.jsindex bf1540dc9..edfa519c0 100644--- a/plugins/model-apps/scripts/lib/managed-feature-contract.js+++ b/plugins/model-apps/scripts/lib/managed-feature-contract.js@@ -1408,6 +1408,7 @@ module.exports = {createAttemptSendObserver,attemptProvenUnsent,notStartedAnswer,+ dataverseErrorCode,rowsCreatedByAttempt,existingRowDispatches,editSwitchRequired,diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.jsindex 0abbf15c1..d34b0ae14 100644--- a/plugins/model-apps/scripts/lib/sdk-build.js+++ b/plugins/model-apps/scripts/lib/sdk-build.js@@ -148,7 +148,7 @@ const { odataLit } = require('./odata.js');const { exactOne, distinctRows } = require('./query-completeness.js');const { isRestrictedSolution } = require('./system-solutions.js');const { tableRefs, pinAppTables, publishAppComponents, resolveMainForms, appComponentsFor, applyAppMainForms, explainAppPushWarnings, savedPageRows,- declaredAppPins, pinDeclaredArtifacts } = require('./app-components.js');+ declaredAppPins, pinDeclaredArtifacts, createdViewIds } = require('./app-components.js');const { pinIntentOf, pinWarningOf, reconcileUnconfirmedPin } = require('./app-pin-recovery.js');const { createAppPublication } = require('./app-publication-policy.js');const { appWriteTables, appPushTables, preAppTables, publishTablesXml, readSavedNotPublished, describeSavedNotPublished, readAppFormChartTables, describePreAppRefusal, describeUnreadAppComponents } = require('./table-publish.js');@@ -3587,7 +3587,7 @@ function protectedConfigurationInPlay(spec, { apply, env, workspaceDir, appDir }// an attempt needs it and kept by its gate: every attempt of a whole-build retry (build-model-app.js) shares the one managed create// context, so an answer one attempt received is still known to the next. Keyed by the gate, which the CLI makes once per invocation.const protectedHookups = new WeakMap();-function protectedConfigurationFor(gate, store, { env, approvals } = {}) {+function protectedConfigurationFor(gate, store, { env, approvals, retirements } = {}) {const made = protectedHookups.get(gate);if (made && made.store === store) return made;const { createManagedCreateContext } = require('./managed-create-context.js');@@ -3596,7 +3596,8 @@ function protectedConfigurationFor(gate, store, { env, approvals } = {}) {// The maker's `--authorize adopt:<kind>:...` row approvals (build-model-app.js authorizationKeys), exactly as the preflight printed them.const ctx = createManagedCreateContext({ store, approvals: approvals ? [...approvals] : [], notFoundCode: NOT_FOUND_CODE });// The API root the SDK prefixes every request with (the bundle uses v9.0): a Custom API change set is admitted only under it.- const hookup = createProtectedConfiguration({ store, gate, ctx, apiBase: `${new URL(String(env)).origin}/api/data/v9.0` });+ // `retirements` are the maker's `--authorize retire:...@<attempt token>` approvals, which only the debt sweep reads (pendingSweep).+ const hookup = createProtectedConfiguration({ store, gate, ctx, apiBase: `${new URL(String(env)).origin}/api/data/v9.0`, retirements: retirements ? [...retirements] : [] });protectedHookups.set(gate, hookup);return hookup;}@@ -4088,7 +4089,7 @@ async function runSdkBuildPhases(spec, opts, owed) {let configurationOpts = opts;if (opts.managedCreateGate && workflowStore && !opts.protectedConfiguration) {opts.managedCreateGate.bind(workflowStore);- configurationOpts = { ...opts, protectedConfiguration: protectedConfigurationFor(opts.managedCreateGate, workflowStore, { env: opts.env, approvals: opts.configurationApprovals }) };+ configurationOpts = { ...opts, protectedConfiguration: protectedConfigurationFor(opts.managedCreateGate, workflowStore, { env: opts.env, approvals: opts.configurationApprovals, retirements: opts.configurationRetirements }) };}// A declared artifact that did not settle stops the build. Its result's own findings decide — never the SDK error// behind them: rethrown, a 5xx answer would make the runner judge an unsettled create as transient and retry it, and a@@ -7329,6 +7330,19 @@ async function runSdkBuildPhases(spec, opts, owed) {// only PER ENTITY, so a name-only key lets a same-named view on another entity OVERWRITE this id and// cross-wire dashboards / sub-grids / AI-summaries to the wrong entity's view.(spec.views || []).forEach((v, i) => { result.created.views[`${v.entity.toLowerCase()}|${v.name}`] = ids[i]; });+ // #845: two declared views may share one name on one table under two keys (views[].key), and the build makes both, but the+ // `entity|name` entry above holds only the last of them. Each other one is listed in `sameNamedViews` as { entity, name, key, id },+ // so the views this run made or reused are all recorded: the app's components and declared pins and the views the default-view+ // enrichment leaves alone read them through createdViewIds (lib/app-components.js). A list of fields, not more `entity|name|key`+ // entries: a view may itself be named `Twin|v1`, and a joined key would take its entry. The `entity|name` entries are exactly as+ // before, so a lookup by name (a dashboard tile, a sub-grid, the per-table publish, the snapshot index) is unchanged, and a spec+ // without same-named declared views records exactly what it did (no `sameNamedViews`).+ const sameNamed = [];+ (spec.views || []).forEach((v, i) => {+ const entity = v.entity.toLowerCase();+ if (ids[i] && isDeclaredView(v) && result.created.views[`${entity}|${v.name}`] !== ids[i]) sameNamed.push({ entity, name: v.name, key: declaredViewKey(v), id: ids[i] });+ });+ if (sameNamed.length) result.created.sameNamedViews = sameNamed;}// 4a. Quick Find (entities[].quickFind, lib/quick-find.js): the columns the search box matches on are the table's Quick Find@@ -7377,7 +7391,7 @@ async function runSdkBuildPhases(spec, opts, owed) {}};if (has('views')) {- const authorViewIds = Object.values(result.created.views || {}).filter(Boolean);+ const authorViewIds = createdViewIds(result.created);for (const e of spec.entities || []) {if (!enrichesDefaultViews(spec, e)) continue;const logical = e.schemaName.toLowerCase();diff --git a/plugins/model-apps/scripts/lib/unsynced-edits.js b/plugins/model-apps/scripts/lib/unsynced-edits.jsindex 3cfe63ee9..5e26814a0 100644--- a/plugins/model-apps/scripts/lib/unsynced-edits.js+++ b/plugins/model-apps/scripts/lib/unsynced-edits.js@@ -28,13 +28,15 @@//// FAILS OPEN: an SDK without the method, or a diff that throws (a workspace file that cannot be read), says// "changed", so the caller writes exactly as it did before this check existed. A skipped write has to be-// proven unnecessary; a doubtful one is made.-async function hasUnsyncedEdits(sdk, type, id) {+// proven unnecessary; a doubtful one is made. `rethrow(error)` names the errors a caller must see as they are instead+// (a refusal that says itself what the maker should do, which "changed" would hide).+async function hasUnsyncedEdits(sdk, type, id, { rethrow } = {}) {if (!sdk || typeof sdk.diffArtifact !== 'function') return true;try {const diff = await sdk.diffArtifact(type, id);return !(diff && Array.isArray(diff.changes) && diff.changes.length === 0);- } catch {+ } catch (error) {+ if (typeof rethrow === 'function' && rethrow(error)) throw error;return true;}}diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.jsindex e33e8b239..a4fdcf29c 100644--- a/plugins/model-apps/scripts/lib/verify-spec.js+++ b/plugins/model-apps/scripts/lib/verify-spec.js@@ -48,7 +48,7 @@ const { formEmbedsOfPage, verifyFormPageEmbed } = require('./form-page-embeds.jsconst { answerOf, statusReasonChecks, alternateKeyChecks } = require('./status-reasons-keys.js');const { columnTypeChecks, declaredTableFlags, verifyTableFlags } = require('./schema-feature-contract.js');const { verifyDateBehaviors } = require('./date-behavior.js');-const { isDeclaredView, compileViewIntent } = require('./view-reconcile.js');+const { isDeclaredView, declaredViewKey, compileViewIntent } = require('./view-reconcile.js');const { expectedQuickFindProjection } = require('./quick-find.js');const { readXmlElements, XML_PREDEFINED } = require('./strict-xml.js');const { usesCommandStates, normalizeCommandStates } = require('./command-state-contract.js');@@ -332,9 +332,52 @@ async function verifySpec(spec, read, opts = {}) {const readChoices = typeof read.choiceAttributes === 'function'? memoizeChoiceReader((entity) => read.choiceAttributes(entity, { languageCode: spec.languageCode })): null;- plan.each(spec.views || [], async ({ add }, views) => {+ // #845: which row is the view. A DECLARED view (views[].reconcile "declared") is found as the build finds it (lib/view-reconcile.js+ // planViewReconcile): by the row its managed binding in this workspace (`opts.managedManifest`) records, else by its `viewId` pin,+ // and only then by its name on its table. Two declared views may share one name on one table under two keys (views[].key; a managed+ // download writes one for each view), and the build makes and binds a row for each: the name finds only one of them, so the other+ // view's columns and filters used to be held to its namesake's row and failed. A row read by id must be that id, on the view's+ // table; when it is not there the view is missing, and a view of the same name is not taken in its place. A binding with an attempt+ // still pending, a group record that is not usable, or a binding store that cannot be read at all (openBindingIn) proves nothing+ // yet: the view is unverified (its managed listing says why), never read by its name in place of the row the store may bind.+ // A keyed view that shares its table and name with another view of the spec, and has neither binding nor pin, is found by its name+ // as before, but which of the rows of that name it is cannot be told, so its content is unverified rather than held to a row that+ // may be the other view's; a check that fails on such a view names its key. Every other view is read by its name, as it always was.+ const viewGuid = (g) => {+ const s = String(g || '').trim().toLowerCase().replace(/^\{|\}$/g, '');+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(s) ? s : '';+ };+ const viewNameOn = (v) => `${String(v.entity).toLowerCase()}|${String(v.name).toLowerCase()}`;+ const viewsByName = new Map();+ for (const v of spec.views || []) if (v && v.entity != null) viewsByName.set(viewNameOn(v), (viewsByName.get(viewNameOn(v)) || 0) + 1);+ const keyedNamesake = (v) => isDeclaredView(v) && typeof v.key === 'string' && !!v.key && viewsByName.get(viewNameOn(v)) > 1;+ const viewIdentity = (v) => {+ if (!isDeclaredView(v)) return null;+ const key = declaredViewKey(v);+ const pin = v.viewId === undefined ? '' : viewGuid(v.viewId);+ const m = opts.managedManifest;+ if (m && Array.isArray(m.groups)) {+ const open = openBindingIn(m.pending, 'view', key) || openBindingIn(m.invalid, 'view', key);+ if (open) return { key, open: notSettledDetail(key, open) };+ const g = m.groups.find((x) => x && x.family === 'view' && x.key === key);+ if (g) {+ const id = viewGuid(g.root && g.root.id);+ if (!id) return { key, open: `its managed binding (${key}) records no view id — unverified, not proven correct` };+ if (pin && pin !== id) return { key, conflict: `its viewId ${String(v.viewId)} is not the view its managed binding (${key}) is bound to (${id}); correct or remove the viewId` };+ return { key, id, by: `the view its managed binding (${key}) is bound to (${id})` };+ }+ }+ return pin ? { key, id: pin, by: `the view its viewId pins (${pin})` } : null;+ };+ plan.each(spec.views || [], async ({ add: addCheck, unverified }, views) => {for (const v of views) {const viewName = `${String(v.entity).toLowerCase()}.${v.name}`;+ // Two views of one name on one table are told apart in what fails by their keys; every other view reports as before.+ const namesakeKey = keyedNamesake(v) ? declaredViewKey(v) : '';+ const add = (kind, name, present, detail) => addCheck(kind, name, present, namesakeKey && !present ? `${detail ? `${detail} ` : ''}(view key ${namesakeKey})` : detail);+ const who = viewIdentity(v);+ if (who && who.open) { unverified.push(`view:${viewName} (${who.open})`); continue; }+ if (who && who.conflict) { add('view', viewName, false, who.conflict); continue; }// Also select layoutxml so a CONTENT check can catch a spec column the view does not carry (an// added or renamed column that never landed would otherwise pass an existence-only verify). It// cannot catch a column REMOVED from the spec: reconcileView is additive-union, so the column stays@@ -343,12 +386,21 @@ async function verifySpec(spec, read, opts = {}) {let rows = [];let readError = null;try {- rows = await read.queryRecords('savedquery', { select: ['savedqueryid', 'layoutxml', 'fetchxml'], filter: `returnedtypecode eq '${String(v.entity).toLowerCase()}' and name eq '${odataLit(v.name)}'`, top: 1 });+ rows = who+ ? await read.queryRecords('savedquery', { select: ['savedqueryid', 'returnedtypecode', 'layoutxml', 'fetchxml'], filter: `savedqueryid eq ${who.id}`, top: 1 })+ : await read.queryRecords('savedquery', { select: ['savedqueryid', 'layoutxml', 'fetchxml'], filter: `returnedtypecode eq '${String(v.entity).toLowerCase()}' and name eq '${odataLit(v.name)}'`, top: 1 });} catch (error) {readError = error;}- const row = rows && rows[0];- add('view', viewName, row, readError ? String(readError.message || readError) : '');+ let row = rows && rows[0];+ // Read by id, the row is the view only when it IS that id (a reader that did not apply the filter answers another row), on the+ // view's own table where the row says which.+ if (who && row && (viewGuid(row.savedqueryid) !== who.id || (row.returnedtypecode != null && String(row.returnedtypecode).toLowerCase() !== String(v.entity).toLowerCase()))) row = undefined;+ add('view', viewName, row, readError ? String(readError.message || readError) : who && !row ? `${who.by} was not found on its table; a view of the same name is not taken in its place` : '');+ if (row && !who && namesakeKey) {+ unverified.push(`view-content:${viewName} (several views on ${String(v.entity).toLowerCase()} have this name, and this one (${namesakeKey}) has neither a managed binding nor a viewId, so which of the rows it is cannot be told)`);+ continue;+ }const specCols = specViewColumnNames(v);if (row && row.layoutxml && specCols.length) {// Deployed column set from the saved view's layoutxml (<cell name="…"/> per column). We require@@ -427,9 +479,10 @@ async function verifySpec(spec, read, opts = {}) {//// Which row is the chart: a DECLARED chart (charts[].reconcile "declared") that the managed bindings of this workspace// (`opts.managedManifest`) bind is the bound row, read by its id — the build resolves it so, and a namesake made since is not it. A- // bound row that is gone is missing; the name is not asked in its place. A group with an attempt still pending, or a stored record- // that is not usable, proves nothing about the chart: it is unverified (its managed listing says why). Every other chart is found by- // its name on its table, as before; two charts of that name are not told apart, so the chart is present but its content unverified.+ // bound row that is gone is missing; the name is not asked in its place. A group with an attempt still pending, a stored record+ // that is not usable, or a store that cannot be read at all (openBindingIn), proves nothing about the chart: it is unverified (its+ // managed listing says why). Every other chart is found by its name on its table, as before; two charts of that name are not told+ // apart, so the chart is present but its content unverified.//// The content columns are read only for the comparison; a reader that answers without them (the eval's synthesized reader answers// ids) has its charts checked for presence, and their content named unverified — a row's presence never stands in for what it holds.@@ -439,9 +492,8 @@ async function verifySpec(spec, read, opts = {}) {const m = opts.managedManifest;if (!m || !Array.isArray(m.groups) || !isDeclaredChart(ch)) return null;const key = declaredChartKey(ch);- const unsettled = (list) => (Array.isArray(list) ? list : []).find((x) => x && ((x.family === 'chart' && x.key === key) || x.family === 'store'));- const open = unsettled(m.pending) || unsettled(m.invalid);- if (open) return { key, open: `its managed binding (${key}) is not settled (${open.code || open.reason || 'managed-binding-group-invalid'}) — unverified, not proven correct` };+ const open = openBindingIn(m.pending, 'chart', key) || openBindingIn(m.invalid, 'chart', key);+ if (open) return { key, open: notSettledDetail(key, open) };const g = m.groups.find((x) => x && x.family === 'chart' && x.key === key);if (!g) return null;const id = chartGuid(g.root && g.root.id);@@ -528,16 +580,15 @@ async function verifySpec(spec, read, opts = {}) {// (committed root first), and keeps a maker's rename, so its spec name may find nothing, or a namesake made since. Every// check that asks ownDashboard (the dashboard check and its tile checks below, and the site map's dashboard subareas)// then reads the same row the managed check reads. A binding verify cannot use never falls back to the name: an- // authored dashboardId that is not the bound row fails, and a group with an attempt still pending, or a stored record- // that is not usable, is unverified (its managed listing says why).+ // authored dashboardId that is not the bound row fails, and a group with an attempt still pending, a stored record+ // that is not usable, or a store that cannot be read at all (openBindingIn), is unverified (its managed listing says why).const boundByName = new Map();if (opts.managedManifest && Array.isArray(opts.managedManifest.groups)) {- const unsettled = (list, key) => (Array.isArray(list) ? list : []).find((p) => p && p.family === 'dashboard' && p.key === key);for (const [key, d] of declaredDashboardsByKey(spec)) {if (!d.name) continue;- const open = unsettled(opts.managedManifest.pending, key) || unsettled(opts.managedManifest.invalid, key);+ const open = openBindingIn(opts.managedManifest.pending, 'dashboard', key) || openBindingIn(opts.managedManifest.invalid, 'dashboard', key);if (open) {- boundByName.set(d.name, { detail: `its managed binding (${key}) is not settled (${open.code || open.reason || 'managed-binding-group-invalid'}) — unverified, not proven correct` });+ boundByName.set(d.name, { detail: notSettledDetail(key, open) });continue;}const g = opts.managedManifest.groups.find((x) => x && x.family === 'dashboard' && x.key === key);@@ -1544,7 +1595,8 @@ async function verifySpec(spec, read, opts = {}) {continue;}// A declared rule bound in this workspace's store, or one whose attempt is still pending, is checked by its own row id first- // (boundWorkflowOf), never by name: a namesake must not pass for it. Its key is the helper's (lib/rule-settlement.js ruleKey).+ // (boundWorkflowOf), never by name: a namesake must not pass for it. One the store cannot settle (its record not usable, or the+ // store unreadable) is unverified. Its key is the helper's (lib/rule-settlement.js ruleKey).const boundRule = boundWorkflowOf(opts.managedManifest, 'rule', rule.key ? String(rule.key) : `${entityLogical}/${rule.name}`, rule.reconcile === 'declared');if (boundRule) {await checkBoundWorkflow(read, 'business-rule', name, boundRule, (rule.status || 'Active') === 'Active', { add, unverified }, {@@ -1605,7 +1657,8 @@ async function verifySpec(spec, read, opts = {}) {const entityLogical = String(flow.entity).toLowerCase();const name = `${entityLogical}.${flow.name}`;// A declared flow bound in this workspace's store, or one whose attempt is still pending, is checked by its own row id first- // (boundWorkflowOf), never by name: a namesake must not pass for it.+ // (boundWorkflowOf), never by name: a namesake must not pass for it. One the store cannot settle (its record not usable, or the+ // store unreadable) is unverified.const boundFlow = boundWorkflowOf(opts.managedManifest, 'bpf', `${entityLogical}/${flow.name}`, flow.reconcile === 'declared');if (boundFlow) {// An omitted status on a flow the store already holds means "keep the state its last build proved" (the build changes@@ -2186,7 +2239,7 @@ async function verifySpec(spec, read, opts = {}) {// named `bpfUniqueName(flow.name)` (live-measured), and holding privileges on it is what lets a// persona run the process. Subset semantics as everywhere else — a persona legitimately holds far// more than this one grant.- plan.each(spec.businessProcessFlows || [], async ({ add }, flows) => {+ plan.each(spec.businessProcessFlows || [], async ({ add, unverified }, flows) => {for (const f of flows) {if (!f || !f.securityRoles || !Array.isArray(f.securityRoles.personas)) continue;if (typeof read.rolePrivileges !== 'function' || typeof read.entityPrivileges !== 'function') continue;@@ -2206,19 +2259,55 @@ async function verifySpec(spec, read, opts = {}) {// we could not look, so the derivation stands and the privilege read below fails closed anyway.let backingTable = bpfUniqueName(f.name);let flowMissing = false;- try {- const rows = await read.queryRecords('workflow', {- select: ['workflowid', 'uniquename'],- filter: bpfFilter(f.name, String(f.entity).toLowerCase()),- orderBy: 'createdon asc',- top: 5,- });- const row = rows && rows[0];- if (!row) flowMissing = true;- else if (row.uniquename) backingTable = String(row.uniquename).toLowerCase();- // A row WITHOUT a uniquename keeps the derivation: the flow demonstrably exists, so the- // derived name is the best available answer for anything this tool created.- } catch { /* could not look — keep the derivation; the privilege read below fails closed */ }+ // A DECLARED flow is the row the presence check above holds it to (boundWorkflowOf), read here by its id, as the build grants its+ // roles on the backing table of its settled row (sdk-build.js): a same-named flow found by name has another table, whose grants+ // would prove nothing about this one. A binding the store cannot settle, a pending attempt that names no row, and a read that+ // fails, answers another row or does not carry the row's stored backing table are unverified, never checked on a table found by+ // name or derived from it.+ const boundFlow = boundWorkflowOf(opts.managedManifest, 'bpf', `${String(f.entity).toLowerCase()}/${f.name}`, f.reconcile === 'declared');+ if (boundFlow) {+ if (!boundFlow.id) {+ unverified.push(`bpf-roles:${f.name} (${boundFlow.open || 'an earlier build\'s change of it is still waiting to be proved, and the store does not name its row, so it is not looked up by name'})`);+ continue;+ }+ const want = String(boundFlow.id).toLowerCase().replace(/^\{|\}$/g, '');+ let list;+ try {+ list = Array.from((await read.queryRecords('workflow', { select: ['workflowid', 'uniquename'], filter: `workflowid eq ${boundFlow.id}`, top: 1 })) || []);+ } catch (e) {+ unverified.push(`bpf-roles:${f.name} (its bound row ${boundFlow.id} could not be read: ${String((e && e.message) || e).replace(/\s+/g, ' ').slice(0, 200)})`);+ continue;+ }+ const row = list.find((w) => w && String(w.workflowid || '').toLowerCase().replace(/^\{|\}$/g, '') === want);+ if (!row && list.length) { unverified.push(`bpf-roles:${f.name} (the read of its bound row ${boundFlow.id} answered another row)`); continue; }+ if (!row) {+ add('bpf-roles', f.name, false, `its bound row ${boundFlow.id} is not there, so its backing table cannot be identified and no role grant on it can be verified`);+ continue;+ }+ // The build grants a declared flow's roles only on the backing table its row STORES (a table's logical name), never on one+ // derived from the display name (an adopted or renamed flow keeps another), and stops when that name cannot be read+ // (sdk-build.js bpf-backing-unproved). A row read without a usable stored name proves nothing about where the grants are.+ const stored = typeof row.uniquename === 'string' ? row.uniquename.toLowerCase() : '';+ if (!/^[a-z][a-z0-9_]{0,127}$/.test(stored)) {+ unverified.push(`bpf-roles:${f.name} (its bound row ${boundFlow.id} was read without the name of its backing table, so no role grant on it can be verified)`);+ continue;+ }+ backingTable = stored;+ } else {+ try {+ const rows = await read.queryRecords('workflow', {+ select: ['workflowid', 'uniquename'],+ filter: bpfFilter(f.name, String(f.entity).toLowerCase()),+ orderBy: 'createdon asc',+ top: 5,+ });+ const row = rows && rows[0];+ if (!row) flowMissing = true;+ else if (row.uniquename) backingTable = String(row.uniquename).toLowerCase();+ // A row WITHOUT a uniquename keeps the derivation: the flow demonstrably exists, so the+ // derived name is the best available answer for anything this tool created.+ } catch { /* could not look — keep the derivation; the privilege read below fails closed */ }+ }if (flowMissing) {add('bpf-roles', f.name, false,`no business process flow named '${f.name}' exists on '${String(f.entity).toLowerCase()}', so its backing table cannot be identified and no role grant on it can be verified`);@@ -2608,6 +2697,21 @@ function incompleteDuplicateRead(n) {return `the read answered ${n} definition row(s) and said more exist, so neither "deployed once" nor "not deployed" is proven`;}+// The entry of a managed manifest's `pending` or `invalid` list that leaves the declared `family` artifact `key` unsettled: its own+// group's, or the one entry readManagedManifest lists for a binding store it cannot read at all, e.g.+// { family: 'store', key: 'managed-bindings', reason: '…', code: 'managed-binding-store-unreadable' }+// Such a store holds no group, so without this every declared artifact would look unbound and be found by its pin or name — a+// namesake could pass for it. Views, charts, dashboards, business rules and process flows all ask this one helper, so a family cannot+// miss the store case again. Null when nothing is open for the artifact.+function openBindingIn(list, family, key) {+ return (Array.isArray(list) ? list : []).find((x) => x && ((x.family === family && x.key === key) || x.family === 'store')) || null;+}++// What an artifact openBindingIn found unsettled reports: why, by the entry's code or reason, and that nothing about it is proven.+function notSettledDetail(key, open) {+ return `its managed binding (${key}) is not settled (${open.code || open.reason || 'managed-binding-group-invalid'}) — unverified, not proven correct`;+}+// The row a declared workflow (a business rule, family 'rule', or a process flow, 'bpf') is bound to in this workspace's store,// taken BEFORE any lookup by name: a name read cannot tell the bound row from a same-named one, so a pending rule renamed in Maker// beside an Active namesake would pass on the namesake's state. Answers@@ -2619,7 +2723,9 @@ function incompleteDuplicateRead(n) {// a committed group whose declaration names the status its last build proved ('Active'|'Draft';// a process flow's `declaration.applied.status`). For a flow, an omitted `status` keeps that state// (lib/bpf-settlement.js editsOf), so it is the state verify expects; see the flow check;-// { id: null, pending } a pending attempt whose row the view does not name: nothing can be checked safely, so it is unverified.+// { id: null, pending } a pending attempt whose row the view does not name: nothing can be checked safely, so it is unverified;+// { id: null, open } a declared entry whose group record is not usable, or a store that cannot be read at all (openBindingIn):+// which row is its own is not known, so it is unverified and never looked up by name.// A committed group whose entry is no longer declared is left to the name check here: the build's legacy path reuses the oldest// namesake for it, and the managed section still holds the group to its bound id.function boundWorkflowOf(manifest, family, key, declared) {@@ -2627,6 +2733,8 @@ function boundWorkflowOf(manifest, family, key, declared) {const p = (manifest.pending || []).find((x) => x && x.family === family && x.key === key);if (p) return { id: p.root && typeof p.root.id === 'string' && p.root.id ? p.root.id : null, pending: true };if (!declared) return null;+ const open = openBindingIn(manifest.invalid, family, key);+ if (open) return { id: null, pending: false, open: notSettledDetail(key, open) };const g = (manifest.groups || []).find((x) => x && x.family === family && x.key === key);if (g && g.root && typeof g.root.id === 'string' && g.root.id) {const applied = g.declaration && g.declaration.applied && g.declaration.applied.status;@@ -2639,6 +2747,7 @@ function boundWorkflowOf(manifest, family, key, declared) {// reading by name: no id, a read that failed, or a reader that answered another row than the bound one is unverified, never a pass.// `words` = { draft, active } are the kind's own failure details.async function checkBoundWorkflow(read, kind, name, bound, wantActive, { add, unverified }, words) {+ if (bound.open) { unverified.push(`${kind}:${name} (${bound.open})`); return; }const pendingNote = bound.pending ? 'an earlier build\'s change of it is still waiting to be proved, and ' : '';if (!bound.id) { unverified.push(`${kind}:${name} (${pendingNote}the store does not name its row, so it is not looked up by name)`); return; }const want = String(bound.id).toLowerCase().replace(/^\{|\}$/g, '');diff --git a/plugins/model-apps/scripts/lib/workspace-configuration-memory.js b/plugins/model-apps/scripts/lib/workspace-configuration-memory.jsnew file mode 100644index 000000000..f605fcbbf--- /dev/null+++ b/plugins/model-apps/scripts/lib/workspace-configuration-memory.js@@ -0,0 +1,240 @@+'use strict';+// The SDK workspace never holds sensitive configuration at rest (#846, #847).+//+// The SDK keeps a local copy of every artifact it creates, pushes or fetches: the artifact itself and a metadata file holding+// the snapshot it last synced, under keys like+// ['environment-variables', '<id>.json'] the artifact+// ['.metadata', 'environment-variables', '<id>.meta.json'] { etag, snapshot: <the artifact as fetched>, … }+// ['connection-references', '<id>.json'] the artifact+// ['.metadata', 'connection-references', '<id>.meta.json'] likewise+// For an environment variable that copy is its definition AND its value: `defaultValue`, `schema`, `currentValue.value`+// (for a secret variable, the Key Vault secret reference the build sends); for a connection reference it is `connectionId`.+// A file-backed storage wrote all of it to disk: into the build's throwaway configuration workspace while it lived (and for+// good if the process died before its cleanup), and into the app folder's `.maker-workspace` whenever `build --verify` read+// the items back. The SDK needs the copy within the run (a create writes it and then pushes it; a fetch writes the server's+// copy and the caller reads it back), so the copy is not withheld from the SDK — it is kept in memory instead.+//+// What this wrapper changes, and only for the keys of those two kinds (the artifact folder and its `.metadata` folder):+// - writeTextAtomic stores the text in this wrapper's memory, never in the storage;+// - readText / exists answer from that memory only;+// - deleteFile / deleteByPrefix drop the memory entries too, and still reach the storage, exactly as the SDK asked (the SDK+// deletes only its own artifact's exact keys, or a prefix it chose — as it did before this wrapper existed).+// Every other key (the manifest, the other kinds, entity metadata) is the storage's own, exactly as before. The manifest+// keeps one entry per artifact ({ type, id, name, entityLogicalName, isDirty }), which holds no value; an entry whose files+// are not read reads as an artifact with no local copy and no baseline — the SDK's diff answers no change for it — which is+// what a fresh run of the build used to find in its throwaway workspace anyway.+//+// Copies an earlier plugin version left on disk. This wrapper never deletes one on its own, and never hides one that may hold+// work: before the FIRST access (read, exists, write or delete) to an artifact's two keys, it reads that artifact's copy and+// metadata from the storage and lets the SDK go on without them only when they prove the copy is what the server last held —+// both files present, both JSON, and the copy structurally equal to the metadata's `snapshot`, which is the SDK's own test+// (VersionManager.isDirty: `!deepEqual(meta.snapshot, artifact)`; a copy with no metadata is a creation never sent). Anything+// else — a copy that differs from its snapshot, a copy with no snapshot, a snapshot with no copy (which the SDK's diff+// reports as a removal), a file that is not JSON, or a file that cannot be read at all (locked, denied) — is refused with+// LEGACY_COPY_CODE and a message that names the files and what to do, and quotes none of their content. The SDK used to+// report such a copy as an unsent change; hiding it would have made it read as clean. A refusal is not remembered: the next+// access checks again, so once the obstruction is gone (the file unlocked, or removed by the maker) the run goes on. Only a+// proven-clean (or absent) pair is remembered, for this wrapper.+// A clean copy left on disk is not read, so it changes no decision (an unchanged rebuild makes the same requests as before),+// but it still holds what it held: legacyCopyFolders names the folders holding such files, and lib/maker-sdk.js warns once per+// workspace folder per process so the maker can remove them (skills/app-builder/SKILL.md says how).+//+// The memory belongs to this one wrapper (one SDK instance): a second SDK over the same folder, or the next process, starts+// with none, as a new run of the build always did for its throwaway configuration workspace.++const fs = require('node:fs');++// The SDK's folder of each sensitive kind (vendor/cds-maker-sdk.cjs, WorkspaceManager's kind → folder map).+const SENSITIVE_FOLDERS = Object.freeze(['environment-variables', 'connection-references']);+const METADATA_FOLDER = '.metadata';+const LEGACY_COPY_CODE = 'WORKSPACE_LEGACY_CONFIGURATION_COPY';+const KIND_NAME = { 'environment-variables': 'environment variable', 'connection-references': 'connection reference' };+// The SDK's own deepEqual bound (vendor/cds-maker-sdk.cjs, `deepEqual exceeded the maximum supported depth of 512`).+const MAX_DEPTH = 512;++const sensitive = (key) => Array.isArray(key)+ && (SENSITIVE_FOLDERS.includes(key[0]) || (key[0] === METADATA_FOLDER && SENSITIVE_FOLDERS.includes(key[1])));+const memoryKey = (key) => key.join('/');+const underPrefix = (stored, prefix) => {+ const parts = stored.split('/');+ return prefix.length <= parts.length && prefix.every((part, i) => parts[i] === part);+};++// The artifact a sensitive key belongs to, as the SDK names its two files (WorkspaceManager artifactKey / metaKey):+// ['environment-variables', '<id>.json'] and ['.metadata', 'environment-variables', '<id>.meta.json']+// Any other sensitive key (a folder prefix) belongs to no single artifact.+function artifactOf(key) {+ if (key.length === 2 && SENSITIVE_FOLDERS.includes(key[0]) && /\.json$/i.test(key[1]) && !/\.meta\.json$/i.test(key[1])) {+ return { folder: key[0], id: key[1].slice(0, -'.json'.length) };+ }+ if (key.length === 3 && key[0] === METADATA_FOLDER && SENSITIVE_FOLDERS.includes(key[1]) && /\.meta\.json$/i.test(key[2])) {+ return { folder: key[1], id: key[2].slice(0, -'.meta.json'.length) };+ }+ return null;+}++// The SDK's structural equality of two parsed JSON documents (vendor/cds-maker-sdk.cjs `deepEqual`): same keys and equal+// values for objects, same length and equal items for arrays, `===` otherwise.+function sameJson(a, b, depth = 0) {+ if (a === b) return true;+ if (depth > MAX_DEPTH) throw new RangeError('too deep');+ if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object' || Array.isArray(a) !== Array.isArray(b)) return false;+ const ka = Object.keys(a);+ const kb = Object.keys(b);+ return ka.length === kb.length && ka.every((k) => Object.prototype.hasOwnProperty.call(b, k) && sameJson(a[k], b[k], depth + 1));+}++// Why the pair on disk is not provably what the server last held, or null when it is (or when neither file exists).+function unprovenReason(copyText, metaText) {+ if (copyText === null && metaText === null) return null;+ if (copyText === null) return 'its last-synced snapshot is there with no copy beside it (the SDK reports that as a local removal)';+ if (metaText === null) return 'the copy has no last-synced snapshot beside it (the SDK reports that as a creation never sent)';+ let copy;+ let meta;+ try {+ copy = JSON.parse(copyText);+ meta = JSON.parse(metaText);+ } catch {+ return 'one of its files is not valid JSON';+ }+ if (meta === null || typeof meta !== 'object' || !Object.prototype.hasOwnProperty.call(meta, 'snapshot')) return 'its metadata file holds no last-synced snapshot';+ try {+ return sameJson(meta.snapshot, copy) ? null : 'the copy differs from its last-synced snapshot (an edit that may never have been sent)';+ } catch {+ return 'the copy is too deeply nested to compare with its last-synced snapshot';+ }+}++/**+ * `storage` (an SDK WorkspaceStorage) with the sensitive configuration kinds kept in memory. Like output-redaction.js+ * guardWorkspaceStorage, every other member runs ON the storage (a storage may keep `#private` state) and the wrapper is a+ * Proxy over an empty child of it, so `pathFor`, `getRoot` and `instanceof` still hold. `prototype` names that parent+ * when `storage` is itself a wrapper (maker-sdk.js passes the caller's own storage under the token guard), so the+ * caller's storage stays the direct prototype of what the SDK is given. `refuse(code, message)` makes the error a legacy+ * copy is refused with (maker-sdk.js passes the SDK's SdkError, which the bundle rethrows as it is).+ * @template T+ * @param {T} storage+ * @param {{ prototype?: object, refuse?: (code: string, message: string) => Error }} [options]+ * @returns {T}+ */+function keepSensitiveConfigurationInMemory(storage, { prototype = storage, refuse = defaultRefuse } = {}) {+ if (storage === null || typeof storage !== 'object' || typeof storage.readText !== 'function' || typeof storage.writeTextAtomic !== 'function') return storage;+ const memory = new Map();+ const proven = new Set();+ const where = (key) => {+ try { return typeof storage.pathFor === 'function' ? storage.pathFor(key) : key.join('/'); } catch { return key.join('/'); }+ };+ // Before the first access to one artifact's keys: what an earlier version left at them is either proven clean (and from+ // then on not read) or refused. See the header.+ const checkLegacy = async (key) => {+ const at = artifactOf(key);+ if (!at) return;+ const name = `${at.folder}/${at.id}`;+ if (proven.has(name)) return;+ const copyKey = [at.folder, `${at.id}.json`];+ const metaKey = [METADATA_FOLDER, at.folder, `${at.id}.meta.json`];+ const files = `${where(copyKey)} and ${where(metaKey)}`;+ let reason;+ try {+ reason = unprovenReason(await storage.readText(copyKey), await storage.readText(metaKey));+ } catch (err) {+ reason = `its files could not be read (${(err && err.code) || 'unreadable'}: locked by another program, or access denied)`;+ }+ if (reason === null) {+ proven.add(name);+ return;+ }+ const kind = KIND_NAME[at.folder];+ throw refuse(LEGACY_COPY_CODE, `the workspace holds a copy of the ${kind} ${at.id} that an earlier plugin version wrote, and ${reason}: ${files}. `+ + 'This version keeps environment variables and connection references out of the workspace and reads no copy it cannot prove '+ + 'is what the environment last held, so it stops here rather than hide this one; the files were left as they are and nothing in them was sent. '+ + `If the copy holds a change you still want, make it in the App Spec or the deployment settings file (a build sends configuration from those, never from the workspace), or send it with the plugin version that wrote it. `+ + 'If the files are locked, close the program holding them. Then delete those two files (only them) and run again.');+ };+ const own = {+ async readText(key, ...rest) {+ if (!sensitive(key)) return storage.readText(key, ...rest);+ await checkLegacy(key);+ const k = memoryKey(key);+ return memory.has(k) ? memory.get(k) : null;+ },+ async writeTextAtomic(key, text, ...rest) {+ if (!sensitive(key)) return storage.writeTextAtomic(key, text, ...rest);+ await checkLegacy(key);+ memory.set(memoryKey(key), String(text));+ return undefined;+ },+ async deleteFile(key, ...rest) {+ if (!sensitive(key)) return storage.deleteFile(key, ...rest);+ await checkLegacy(key);+ memory.delete(memoryKey(key));+ // The SDK deletes its artifact's exact keys (deleteArtifact); a proven-clean copy an earlier version left there goes+ // with it, as it did before this wrapper. A failure is the storage's own and reaches the SDK unchanged.+ return storage.deleteFile(key, ...rest);+ },+ async deleteByPrefix(prefix, ...rest) {+ if (Array.isArray(prefix)) for (const k of [...memory.keys()]) if (underPrefix(k, prefix)) memory.delete(k);+ return storage.deleteByPrefix(prefix, ...rest);+ },+ };+ // `exists` is optional on a storage; the SDK falls back to readText when it is absent, so it is answered only when present.+ if (typeof storage.exists === 'function') {+ own.exists = async function exists(key, ...rest) {+ if (!sensitive(key)) return storage.exists(key, ...rest);+ await checkLegacy(key);+ return memory.has(memoryKey(key));+ };+ }+ const onStorage = new Map();+ return new Proxy(Object.create(prototype), {+ get(target, key) {+ if (Object.prototype.hasOwnProperty.call(own, key)) return own[key];+ const value = Reflect.get(storage, key, storage);+ if (typeof value !== 'function' || key === 'constructor') return value;+ if (!onStorage.has(value)) onStorage.set(value, function onTheStorage(...args) { return value.apply(storage, args); });+ return onStorage.get(value);+ },+ set(target, key, value) {+ return Reflect.set(storage, key, value, storage);+ },+ });+}++// Is `error` this wrapper's refusal of a copy an earlier version left? A caller that would read any failure of a diff as+// "changed" (lib/unsynced-edits.js fails open) rethrows this one, so the maker sees its own remedy.+const isLegacyCopyRefusal = (error) => Boolean(error) && error.code === LEGACY_COPY_CODE;++function defaultRefuse(code, message) {+ const err = new Error(message);+ err.code = code;+ return err;+}++// The sensitive folders of a file-system storage that hold `.json` files (the SDK's artifact and metadata files), as paths+// relative to its root, e.g. ['environment-variables', '.metadata/environment-variables']. Only names are read, never content.+// A storage with no `pathFor` (not file-backed) or a folder that cannot be listed answers nothing.+function legacyCopyFolders(storage) {+ if (!storage || typeof storage.pathFor !== 'function') return [];+ const found = [];+ for (const folder of SENSITIVE_FOLDERS) {+ for (const key of [[folder], [METADATA_FOLDER, folder]]) {+ try {+ const entries = fs.readdirSync(storage.pathFor(key), { withFileTypes: true });+ if (entries.some((e) => e.isFile() && /\.json$/i.test(e.name))) found.push(key.join('/'));+ } catch { /* absent or unlistable: nothing to name */ }+ }+ }+ return found;+}++// The one warning about legacyCopyFolders, worded without any content of those files.+function legacyCopyWarning(root, folders) {+ return `the workspace ${root} still holds environment-variable or connection-reference copies an earlier plugin version wrote, `+ + `in ${folders.join(', ')}. They may hold values, defaults, Key Vault secret references or connection ids. This version never `+ + 'uses them as configuration, never writes them and does not delete them for you (it reads them only to check that none holds a '+ + 'change you never sent): when no build is running, delete the .json files in those folders '+ + '(a change in one that you never sent goes into the App Spec or the deployment settings file first). '+ + 'See "Sensitive configuration in the workspace" in the app-builder skill.';+}++module.exports = { keepSensitiveConfigurationInMemory, legacyCopyFolders, legacyCopyWarning, isLegacyCopyRefusal, SENSITIVE_FOLDERS, LEGACY_COPY_CODE };diff --git a/plugins/model-apps/scripts/tests/bpf-security-roles.test.js b/plugins/model-apps/scripts/tests/bpf-security-roles.test.jsindex e3d110068..6bc445668 100644--- a/plugins/model-apps/scripts/tests/bpf-security-roles.test.js+++ b/plugins/model-apps/scripts/tests/bpf-security-roles.test.js@@ -628,3 +628,95 @@ test('#513 verify reads the deployed uniquename too, or build and verify disagreassert.ok(asked.includes(DEPLOYED), 'verify must ask about the DEPLOYED table');assert.strictEqual(asked.includes(bpfUniqueName('Ticket Handling')), false, 'and never about the derivation');});++test('#513 verify checks a DECLARED flow\'s grants on the table of the row its binding names, never on a namesake\'s', async () => {+ // The build grants a declared flow's roles on the backing table its settled row stores, read by that row's id (sdk-build.js), so verify+ // reads the same row: a same-named flow found by name has another table, and so may the display-name derivation. A binding the store+ // cannot settle (an unusable record, an unreadable store, a pending attempt that names no row), or a row read without its stored+ // table, leaves the grants unverified rather than proved on a table found by name or derived.+ const { verifySpec } = require('../lib/verify-spec.js');+ const BOUND = '11111111-2222-4333-8444-555555555555';+ const OWN = 'contoso_ticketprocess';+ const OTHER = 'contoso_namesake';+ // The display-name derivation: never the table of a declared flow whose row does not say (the build refuses to guess it).+ const DERIVED = bpfUniqueName(FLOW.name);+ const TABLES = [OWN, OTHER, DERIVED];+ const KEY = 'contoso_ticket/Ticket Handling';+ const filters = [];+ const asked = [];+ const read = ({ answer } = {}) => ({+ findTable: async () => null,+ findColumns: async () => [],+ sitemapXml: async () => '',+ queryRecords: async (set, o) => {+ const filter = String((o && o.filter) || '');+ if (set === 'businessunit') return [{ businessunitid: '44444444-4444-4444-4444-444444444444' }];+ if (set === 'role') return [{ roleid: 'role-1', name: 'Dispatcher', description: SDK_ROLE_MARKER }];+ if (set !== 'workflow') return [];+ filters.push(filter);+ if (filter === `workflowid eq ${BOUND}`) return answer || [{ workflowid: BOUND, statecode: 1, uniquename: OWN }];+ // A name read answers an Active namesake whose backing table is another.+ return /\bname eq\b/.test(filter) ? [{ workflowid: '77777777-7777-4777-8777-777777777777', statecode: 1, uniquename: OTHER }] : [];+ },+ entityPrivileges: async (t) => {+ asked.push(t);+ return TABLES.includes(t) ? BPF_ROLE_ACCESS.map((a) => ({ Name: `prv${a[0].toUpperCase()}${a.slice(1)}${t}`, PrivilegeId: `${t}-${a}`, PrivilegeType: a[0].toUpperCase() + a.slice(1) })) : [];+ },+ // The persona holds the grants on EVERY table, so only the table verify reads decides what it proved.+ rolePrivileges: async () => TABLES.flatMap((t) => BPF_ROLE_ACCESS.map((a) => ({ privilegeId: `${t}-${a}`, depth: 'Global' }))),+ });+ const manifest = (over) => ({ revision: 1, groups: [], pending: [], invalid: [], ...over });+ const run = async (reconcile, m, reader = read()) => {+ filters.length = 0;+ asked.length = 0;+ const r = await verifySpec(base({ ...reconcile, securityRoles: { personas: ['Dispatcher'] } }), reader, { managedManifest: m });+ return { r, roles: r.checks.filter((x) => x.kind === 'bpf-roles'), nameReads: filters.filter((f) => /\bname eq\b/.test(f)) };+ };+ const declared = { reconcile: 'declared' };++ // Bound: the grants are proved on the bound row's own table, and the flow is never read by name.+ const bound = await run(declared, manifest({ groups: [{ family: 'bpf', key: KEY, root: { kind: 'bpf', key: KEY, id: BOUND } }] }));+ assert.deepStrictEqual(bound.roles.map((c) => [c.present, c.detail]), [[true, `4 privilege(s) held on ${OWN}`]], JSON.stringify(bound.roles));+ assert.deepStrictEqual(bound.nameReads, []);+ assert.ok(asked.includes(OWN) && !asked.includes(OTHER), JSON.stringify(asked));++ // Unsettled: unverified, with no name read and no table read.+ for (const [what, m, why] of [+ ['an unreadable store', manifest({ revision: 0, invalid: [{ family: 'store', key: 'managed-bindings', code: 'managed-binding-store-unreadable' }] }), /is not settled \(managed-binding-store-unreadable\)/],+ ['an unusable record', manifest({ invalid: [{ family: 'bpf', key: KEY, reason: 'its record is not usable' }] }), /is not settled \(its record is not usable\)/],+ ['a pending attempt naming no row', manifest({ pending: [{ family: 'bpf', key: KEY, code: 'managed-settlement-pending', root: null }] }), /the store does not name its row/],+ ]) {+ const u = await run(declared, m);+ assert.deepStrictEqual(u.roles, [], `${what}: ${JSON.stringify(u.roles)}`);+ assert.ok(u.r.unverified.some((x) => x.startsWith('bpf-roles:Ticket Handling (') && why.test(x)), `${what}: ${JSON.stringify(u.r.unverified)}`);+ assert.deepStrictEqual(u.nameReads, [], what);+ assert.deepStrictEqual(asked.filter((t) => t === OWN || t === OTHER), [], what);+ }++ // The bound row's read answering another row is unverified; the bound row gone fails, as the presence check fails it.+ const boundM = manifest({ groups: [{ family: 'bpf', key: KEY, root: { kind: 'bpf', key: KEY, id: BOUND } }] });+ const other = await run(declared, boundM, read({ answer: [{ workflowid: '77777777-7777-4777-8777-777777777777', uniquename: OTHER }] }));+ assert.deepStrictEqual(other.roles, []);+ assert.ok(other.r.unverified.some((x) => x.startsWith('bpf-roles:Ticket Handling (') && /answered another row/.test(x)), JSON.stringify(other.r.unverified));+ const gone = await run(declared, boundM, read({ answer: [] }));+ assert.deepStrictEqual(gone.roles.map((c) => c.present), [false]);+ assert.match(gone.roles[0].detail, new RegExp(`its bound row ${BOUND} is not there`));+ assert.deepStrictEqual(gone.nameReads, []);++ // The bound row read without a usable stored name of its backing table: unverified, never checked on the display-name derivation+ // (an adopted or renamed flow keeps another table), as the build never grants on one it derives.+ for (const uniquename of [undefined, null, '', 'Not a table']) {+ const row = { workflowid: BOUND, statecode: 1, ...(uniquename === undefined ? {} : { uniquename }) };+ const blind = await run(declared, boundM, read({ answer: [row] }));+ assert.deepStrictEqual(blind.roles, [], `${JSON.stringify(uniquename)}: ${JSON.stringify(blind.roles)}`);+ assert.ok(blind.r.unverified.some((x) => x.startsWith('bpf-roles:Ticket Handling (') && /without the name of its backing table/.test(x)), JSON.stringify(blind.r.unverified));+ assert.deepStrictEqual(asked.filter((t) => TABLES.includes(t)), [], `${JSON.stringify(uniquename)}: no table is read`);+ }++ // Controls: a legacy flow is read by its name whatever the store holds, and so is a declared flow the store holds nothing for.+ for (const [reconcile, m] of [[{}, manifest({ invalid: [{ family: 'store', key: 'managed-bindings', code: 'managed-binding-store-unreadable' }] })], [declared, manifest({})]]) {+ const c = await run(reconcile, m);+ assert.deepStrictEqual(c.roles.map((x) => [x.present, x.detail]), [[true, `4 privilege(s) held on ${OTHER}`]], JSON.stringify(c.roles));+ assert.ok(c.nameReads.length >= 1);+ }+});diff --git a/plugins/model-apps/scripts/tests/changed-only-flow.test.js b/plugins/model-apps/scripts/tests/changed-only-flow.test.jsindex 28b827df0..4c96ab2fd 100644--- a/plugins/model-apps/scripts/tests/changed-only-flow.test.js+++ b/plugins/model-apps/scripts/tests/changed-only-flow.test.js@@ -1092,3 +1092,23 @@ test('run: a PROVEN absent app still certifies an eligible fresh baseline', asyn`a fresh create must still yield an eligible baseline; debt=${JSON.stringify(snap.debt)}`);} finally { rm(dir); }});++// #845: an edit of the earlier of two same-named declared views, made with a page edit. Aligned by name alone it was hidden by+// its later namesake, so the run was pages-only, skipped the views phase and recorded the edited spec as applied: the next+// run was a no-op and the edit was never made.+test('run: an edit of the earlier of two same-named views beside a page edit runs the FULL build, and only a page edit stays fast', async () => {+ const twins = (columns) => ({ ...baseSpec(), views: [+ { key: 'v1', entity: 'new_x', name: 'Twin', reconcile: 'declared', columns },+ { key: 'v2', entity: 'new_x', name: 'Twin', reconcile: 'declared', columns: ['new_name', 'createdon'] },+ ] });+ for (const [label, columns, decision] of [['earlier view edited', ['new_name', 'createdon'], 'full'], ['page only', ['new_name'], 'fast']]) {+ const dir = ws();+ try {+ seedEligible(dir, annotate(twins(['new_name']), 'v1'));+ const record = [];+ const r = await flow.runChangedOnlyApply({ spec: twins(columns), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { record, buildModelApp: stubBuild(record), readContent: readFor('v2') }) });+ assert.strictEqual(r.changedOnly.decision, decision, label);+ assert.deepStrictEqual(record[0].phases, decision === 'full' ? undefined : ['pages'], `${label}: a full build has no phase range`);+ } finally { rm(dir); }+ }+});diff --git a/plugins/model-apps/scripts/tests/classify-changes.test.js b/plugins/model-apps/scripts/tests/classify-changes.test.jsindex 356f4f3e2..4432f2fd8 100644--- a/plugins/model-apps/scripts/tests/classify-changes.test.js+++ b/plugins/model-apps/scripts/tests/classify-changes.test.js@@ -225,3 +225,90 @@ test('equalExcept ignores the named keys, order-independent', () => {assert.ok(C.equalExcept({ a: 1, b: 2, __x: 9 }, { b: 2, a: 1, __x: 5 }, ['__x']));assert.ok(!C.equalExcept({ a: 1, __x: 9 }, { a: 2, __x: 9 }, ['__x']));});++// #845: two declared views of one name on one table, each under its own key.+const twins = (s) => { s.views = [{ key: 'v1', entity: 'new_x', name: 'Twin', reconcile: 'declared', columns: ['new_name'] }, { key: 'v2', entity: 'new_x', name: 'Twin', reconcile: 'declared', columns: ['new_name', 'createdon'] }]; return s; };++test('#845: an edit of the EARLIER of two same-named views is seen — with a page edit it is never a pages-only change', () => {+ const prior = twins(spec());+ const cur = twins(spec());+ cur.views[0].columns.push('createdon'); // an append to v1, the view the later namesake used to hide+ cur.pages[0].__contentSha = 'psha2';+ const r = C.classifyChanges(cur, prior);+ assert.deepStrictEqual(r.fastChanges.map((c) => [c.shape, c.identity]), [['view', 'new_x|Twin (view key v1)'], ['page', 'overview']]);+ // A non-append edit of v1 is a full build with debt named by its key.+ const edited = twins(spec());+ edited.views[0].columns = ['createdon'];+ edited.pages[0].__contentSha = 'psha2';+ const e = C.classifyChanges(edited, prior);+ assert.strictEqual(e.verdict, 'full');+ // The debt is owed under the view's name and key, not its label (a view may be named like a label; see below).+ assert.deepStrictEqual(e.debt, [{ artifactType: 'view', identity: '["new_x|Twin","v1"]', reason: 'view-nonappend-edit' }]);+ assert.match(e.fullReasons.join('\n'), /view 'new_x\|Twin \(view key v1\)' changed beyond a pure column-append/);+});++test('#845 controls: the later namesake edit, a pages-only change, a second key added and a key removed', () => {+ const prior = twins(spec());+ const later = twins(spec());+ later.views[1].columns.push('modifiedon');+ later.pages[0].__contentSha = 'psha2';+ assert.deepStrictEqual(C.classifyChanges(later, prior).fastChanges.map((c) => [c.shape, c.identity]), [['view', 'new_x|Twin (view key v2)'], ['page', 'overview']]);+ const pagesOnly = twins(spec());+ pagesOnly.pages[0].__contentSha = 'psha2';+ const p = C.classifyChanges(pagesOnly, prior);+ assert.strictEqual(p.verdict, 'fast');+ assert.deepStrictEqual(p.fastChanges.map((c) => c.shape), ['page']);+ const one = spec();+ one.views = [prior.views[0]];+ const added = C.classifyChanges(prior, one);+ assert.strictEqual(added.verdict, 'full');+ assert.match(added.fullReasons[0], /1 new view\(s\) added/);+ assert.deepStrictEqual(added.debt, []);+ const removed = C.classifyChanges(one, prior);+ assert.deepStrictEqual(removed.debt, [{ artifactType: 'view', identity: '["new_x|Twin","v2"]', reason: 'view-removed' }]);+});++test('#845: two changed views keep two debt entries when one is named like the label of the other\'s key', () => {+ // 'Twin (view key v2)' is a legal view name of its own: a debt identity built from the label would make it and the keyed v2 one entry.+ const views = (s) => { s.views = [...twins(s).views, { key: 'third', entity: 'new_x', name: 'Twin (view key v2)', reconcile: 'declared', columns: ['new_name'] }]; return s; };+ const prior = views(spec());+ const cur = views(spec());+ cur.views[1].columns = ['createdon'];+ cur.views[2].columns = ['createdon'];+ cur.pages[0].__contentSha = 'psha2';+ const r = C.classifyChanges(cur, prior);+ assert.strictEqual(r.verdict, 'full');+ assert.deepStrictEqual(r.debt, [+ { artifactType: 'view', identity: '["new_x|Twin","v2"]', reason: 'view-nonappend-edit' },+ { artifactType: 'view', identity: 'new_x|Twin (view key v2)', reason: 'view-nonappend-edit' },+ ]);+ // The messages still name each view as a person reads it.+ assert.deepStrictEqual(r.fullReasons.filter((m) => /beyond a pure column-append/.test(m)).length, 2);+});++test('#845: same-named views without a key of their own each cannot be aligned — any change among them is a full build with debt', () => {+ const legacy = (s) => { s.views = [{ entity: 'new_x', name: 'Twin', columns: ['new_name'] }, { entity: 'new_x', name: 'Twin', columns: ['new_name', 'createdon'] }]; return s; };+ const prior = legacy(spec());+ const cur = legacy(spec());+ cur.views[0].columns.push('createdon');+ cur.pages[0].__contentSha = 'psha2';+ const r = C.classifyChanges(cur, prior);+ assert.strictEqual(r.verdict, 'full');+ assert.deepStrictEqual(r.debt, [{ artifactType: 'view', identity: 'new_x|Twin', reason: 'view-nonappend-edit' }]);+ // Unchanged, they are left alone: a page edit beside them is still a pages-only change.+ const still = legacy(spec());+ still.pages[0].__contentSha = 'psha2';+ assert.deepStrictEqual(C.classifyChanges(still, prior).fastChanges.map((c) => c.shape), ['page']);+});++test('a changed phase in which no change could be classified forces a full build, even beside a fast page edit', () => {+ const prior = spec();+ prior.views.push({ entity: 'new_x', name: 'Other', columns: ['new_name'] });+ const cur = spec();+ cur.views = [prior.views[1], prior.views[0]]; // the same views in another order: the slice differs, no view changed+ cur.pages[0].__contentSha = 'psha2';+ const r = C.classifyChanges(cur, prior);+ assert.strictEqual(r.verdict, 'full');+ assert.deepStrictEqual(r.fullReasons, ['views: changed, but no change in it could be classified — full build (fail-closed)']);+ assert.deepStrictEqual(r.debt, []);+});diff --git a/plugins/model-apps/scripts/tests/configuration-build-real-bundle.test.js b/plugins/model-apps/scripts/tests/configuration-build-real-bundle.test.jsindex 99d7bfdda..0fda70ffd 100644--- a/plugins/model-apps/scripts/tests/configuration-build-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/configuration-build-real-bundle.test.js@@ -631,6 +631,79 @@ test('protected configuration through the build command: a create whose answer wassert.deepEqual(org.unexpected, []);});+// #847: a create the service refused before carrying it out (a 400 with a Dataverse code) leaves nothing behind, so the+// build releases its attempt: the item can be corrected and built again, or dropped, with no approval and no dead end.+test('protected configuration through the build command: a Custom API create the service refused holds nothing, and the rebuild creates it once', async () => {+ let refuse = true;+ let sends = 0;+ const org = commandOrg({ intercept: (req) => {+ if (req.method !== 'POST' || req.path.split('?')[0] !== '/customapis') return undefined;+ sends += 1;+ return refuse ? { statusCode: 400, body: { error: { code: '0x80040265', message: 'refused' } } } : undefined;+ } });+ const first = await runCommand(protectedSpec(), { org });+ assert.match(String(first.thrown && first.thrown.message), /customApi contoso_Calc \(create-refused\) \(the service refused it \(0x80040265\): nothing was created or changed and nothing is left pending/);+ assert.equal(sends, 1);+ assert.equal(org.rows('customapis').length, 0);+ const store = () => openManagedBindings({ workspaceDir: path.join(first.appDir, '.maker-workspace'), environment: org.origin, appUniqueName: 'contoso_configprobe', solutionUniqueName: 'ContosoSol' });+ assert.equal(store().readGroup('customApi', 'contoso_calc').pending, null);++ const dropped = await runAgain(protectedSpec({ customApis: [] }), first);+ assert.equal(dropped.thrown && dropped.thrown.message, undefined, 'dropping it is not held');+ assert.equal(dropped.exitCode, 0, dropped.stderr.slice(-600));++ refuse = false;+ const done = await runAgain(protectedSpec(), first);+ assert.equal(done.thrown && done.thrown.message, undefined);+ assert.equal(done.exitCode, 0, done.stderr.slice(-600));+ assert.equal(sends, 2, 'sent once more, by the build that declares it again');+ assert.equal(org.rows('customapis').length, 1);+ assert.ok(store().readGroup('customApi', 'contoso_calc').committed);+ assert.deepEqual(org.unexpected, []);+});++test('protected configuration through the build command: a dropped item whose create answer was lost is let go only under its printed retire approval, and nothing is deleted', async () => {+ let org = null;+ let sends = 0;+ let replaying = false;+ org = commandOrg({ intercept: async (req) => {+ if (replaying || req.method !== 'POST' || req.path.split('?')[0] !== '/customapis') return undefined;+ sends += 1;+ replaying = true;+ try {+ await org.request({ url: `${org.origin}/api/data/v9.0${req.path}`, method: 'POST', headers: req.headers, body: JSON.stringify(req.body) });+ } finally {+ replaying = false;+ }+ return { statusCode: 503, body: { error: { code: '0x80040216', message: 'the answer was lost' } } };+ } });+ const first = await runCommand(protectedSpec(), { org });+ assert.match(String(first.thrown && first.thrown.message), /customApi contoso_Calc \(create-outcome-unknown\)/);+ let mark = org.requests.length;+ const held = await runAgain(protectedSpec({ customApis: [] }), first);+ assert.equal(held.thrown && held.thrown.code, 'managed-settlement-pending', held.thrown && held.thrown.message);+ assert.deepEqual(org.writes(mark), []);+ const flag = /--authorize '(retire:[^']+)'/.exec(held.thrown.message);+ assert.ok(flag, held.thrown.message);+ // While the App Spec still declares the item, its build settles it: the approval is refused before anything is read.+ mark = org.requests.length;+ const declared = await runAgain(protectedSpec(), first, [...DATA, ...authorize([flag[1]])]);+ assert.equal(declared.exitCode, 1, declared.stderr.slice(-600));+ assert.match(`${declared.stderr} ${JSON.stringify(declared.payload)}`, /stops tracking a configuration item the spec still declares/);+ assert.deepEqual(org.writes(mark), []);++ mark = org.requests.length;+ const done = await runAgain(protectedSpec({ customApis: [] }), first, [...DATA, ...authorize([flag[1]])]);+ assert.equal(done.thrown && done.thrown.message, undefined, 'the approved run did not halt');+ assert.equal(done.exitCode, 0, done.stderr.slice(-600));+ assert.ok(!org.writes(mark).some((w) => /customapi/i.test(w)), 'nothing of the Custom API is sent or deleted');+ assert.equal(org.rows('customapis').length, 1, 'the row it may have created stays');+ assert.match(`${done.stderr} ${JSON.stringify(done.payload)}`, /no longer tracks the unfinished attempt for customApi contoso_calc, which this App Spec no longer declares \(as approved/);+ assert.equal(sends, 1);+ const store = openManagedBindings({ workspaceDir: path.join(first.appDir, '.maker-workspace'), environment: org.origin, appUniqueName: 'contoso_configprobe', solutionUniqueName: 'ContosoSol' });+ assert.equal(store.readGroup('customApi', 'contoso_calc').pending, null);+ assert.deepEqual(org.unexpected, []);+});test('protected configuration through the build command: a later phase\u2019s transient failure runs the whole build again and the configuration rows stay where they are', async () => {let refused = 0;// The sample data's first create meets a customization lock, which the build retries whole; the second succeeds.diff --git a/plugins/model-apps/scripts/tests/configuration-protected.test.js b/plugins/model-apps/scripts/tests/configuration-protected.test.jsindex a94134d94..28372efdc 100644--- a/plugins/model-apps/scripts/tests/configuration-protected.test.js+++ b/plugins/model-apps/scripts/tests/configuration-protected.test.js@@ -4,6 +4,8 @@const test = require('node:test');const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');const { makeTempDir } = require('./helpers/temp-dirs.js');const { createConfigOrg } = require('./helpers/fake-config-org.js');const { validateAppSpec, CONFIGURATION_IDENTITY_MIN_VERSION } = require('../lib/app-spec.js');@@ -13,7 +15,7 @@ const { createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdkconst { configurationSendOnce } = require('../lib/configuration-transport.js');const { createDeferredManagedCreateGate } = require('../lib/managed-create-transport.js');const { createManagedCreateContext } = require('../lib/managed-create-context.js');-const { openManagedBindings, managedManifestView } = require('../lib/managed-bindings.js');+const { openManagedBindings, managedManifestView, storeFileName } = require('../lib/managed-bindings.js');const { readerFor } = require('../verify-model-app.js');const { createConfigurationRuntime } = require('../lib/configuration-build.js');const { readDeploymentBindings, configurationAuthorizationKeys } = require('../lib/configuration-artifacts.js');@@ -77,13 +79,16 @@ function configSpec(over = {}) {const api = (over) => ({ customApis: [{ ...API, ...over }] });const rule = (over) => ({ duplicateDetectionRules: [{ ...RULE, ...over }] });-async function harness({ hookup = true, intercept } = {}) {+// `storeSeed`: a binding store file as an earlier plugin version wrote it, put where this one opens it.+async function harness({ hookup = true, intercept, storeSeed } = {}) {const org = createConfigOrg({ tables: [{ logicalName: 'contact', attributes: ['emailaddress1', 'lastname'] }], solution: { uniqueName: SOL, version: '1.0.0.0', prefix: 'contoso' }, ...(intercept ? { intercept } : {}) });const gate = createDeferredManagedCreateGate();const httpClient = createAzHttpClient(org.origin, { getToken: () => 'test-token-0123456789abcdef', request: org.request, sleep: async () => {}, sendOnce: configurationSendOnce, workflowEffectGate: gate });const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(makeTempDir('cfg-protected-sdk-')), instanceUrl: org.origin, httpClient, solutionUniqueName: SOL });await sdk.initWorkspace();- const store = openManagedBindings({ workspaceDir: makeTempDir('cfg-protected-store-'), environment: org.origin, appUniqueName: 'contoso_configured', solutionUniqueName: SOL });+ const storeDir = makeTempDir('cfg-protected-store-');+ if (storeSeed) fs.writeFileSync(path.join(storeDir, storeFileName(storeSeed.environmentFingerprint, 'contoso_configured', SOL)), JSON.stringify(storeSeed, null, 2));+ const store = openManagedBindings({ workspaceDir: storeDir, environment: org.origin, appUniqueName: 'contoso_configured', solutionUniqueName: SOL });gate.bind(store);const ctx = createManagedCreateContext({ store, notFoundCode: B.NOT_FOUND_CODE });const protectedConfiguration = hookup ? P.createProtectedConfiguration({ store, gate, ctx, apiBase: `${org.origin}/api/data/v9.0` }) : undefined;@@ -322,12 +327,12 @@ test('a rule whose initial publication failed keeps it owed: the rerun never sentest('a rule whose create answer was lost is never re-created or published by a rerun, and is bound only under its exact approvals', async () => {let org = null;let lose = true;- // The service applies the create, and its answer is lost on the way back.+ // The service applies the create, and its answer is lost on the way back (a gateway's 503: no verdict on the request).const h = await harness({ intercept: async (req) => {if (!lose || req.method !== 'POST' || req.path.split('?')[0] !== '/duplicaterules') return undefined;lose = false;await org.request({ url: `${org.origin}/api/data/v9.0${req.path}`, method: 'POST', headers: req.headers, body: JSON.stringify(req.body) });- return { statusCode: 400, body: { error: { code: '0x80040216', message: 'the answer was lost' } } };+ return { statusCode: 503, body: { error: { code: '0x80040216', message: 'the answer was lost' } } };} });org = h.org;const first = await pass(h, configSpec());@@ -926,6 +931,27 @@ test('a bound protected item whose workspace copy differs from the server\'s isassert.deepEqual((await pass(reopen(h), spec)).sent, []);});+test('a workspace copy an earlier version left, which the SDK refuses, stops the preflight with its own code and remedy, never an overwrite approval that cannot clear it', async () => {+ const h = await harness();+ const spec = apiSpec();+ await created(h, spec);+ const bundle = require('../vendor/cds-maker-sdk.cjs');+ const { LEGACY_COPY_CODE } = require('../lib/workspace-configuration-memory.js');+ // The refusal the workspace overlay raises at the SDK's first touch of a legacy copy it cannot prove clean+ // (lib/workspace-configuration-memory.js): an overwrite fetch is refused the same way, so an overwrite approval+ // could never clear it; only the maker's removal of the two files does.+ const diff = h.sdk.diffArtifact.bind(h.sdk);+ h.sdk.diffArtifact = async (kind, ...rest) => {+ if (kind === 'customApi') throw new bundle.SdkError(LEGACY_COPY_CODE, 'customApis/<id>.json and its metadata were left by an earlier version; delete those two files');+ return diff(kind, ...rest);+ };+ const out = await pass(reopen(h), spec);+ assert.equal(out.halt && out.halt.code, LEGACY_COPY_CODE, out.halt && `${out.halt.code}: ${out.halt.message}`);+ assert.ok(out.halt.message.includes('delete those two files'), out.halt.message);+ assert.ok(!out.halt.message.includes('--authorize overwrite:'), out.halt.message);+ assert.deepEqual(out.sent, [], 'nothing is written');+});+// A protected edit the org refuses, with a local edit written into the shared workspace copy at some point of the// build's own send. `inject(h, id, sdk)` installs the edit; answers the harness, the root id and the edited App Spec.async function refusedSendWith(inject) {@@ -1032,7 +1058,9 @@ test('a local edit made after a failed protected send, while a build compares thtest('a failed protected send never removes its copy, and an approved replacement that cannot read the server\'s row keeps it and stops', async () => {let denyRead = false;const h = await harness({ intercept: ({ method, path }) => {- if (method === 'POST' && path.startsWith('/customapis')) return { statusCode: 400, body: { error: { code: '0x80040216', message: 'refused create' } } };+ // A 503 says nothing about whether the create was taken, so the attempt stays pending (a 400 with a Dataverse code is+ // a refusal that releases it: see the create-refused tests).+ if (method === 'POST' && path.startsWith('/customapis')) return { statusCode: 503, body: { error: { code: '0x80040216', message: 'the answer was lost' } } };if (denyRead && method === 'GET' && path.startsWith('/customapis(')) return { statusCode: 403, body: { error: { code: '0x80040220', message: 'read denied' } } };return undefined;} });@@ -2179,3 +2207,263 @@ test('an adopted connection reference edited by a maker right after the acceptan}assert.ok(replace && replace.length, 'the replacement approval was named');});++// ---------------------------------------------------------------------------------------------+// #847: a protected create the service refused before carrying it out (a 400 with a Dataverse error code: one operation,+// rolled back whole) leaves nothing behind, so it is released in the same run; one whose answer was lost (a 503) stays+// pending as before, and an App Spec that drops it settles it only under the exact `retire:` approval the build prints.+const KV = '/subscriptions/00000000-0000-4000-8000-000000000001/resourceGroups/rg/providers/Microsoft.KeyVault/vaults/vault-sample/secrets/key-sample';+const secretSpec = () => configSpec({ customApis: [], duplicateDetectionRules: [], environmentVariables: [{ schemaName: 'contoso_Key', type: 'secret' }] });+const noConfig = () => configSpec({ customApis: [], duplicateDetectionRules: [], environmentVariables: [] });+const secretValue = () => ({ configurationBindings: readDeploymentBindings({ EnvironmentVariables: [{ SchemaName: 'contoso_Key', Value: KV }] }, secretSpec()) });+const variableRows = (h) => [h.org.rows('environmentvariabledefinitions').length, h.org.rows('environmentvariablevalues').length];+const isVariableCreate = (r) => r.method === 'POST' && /^\/environmentvariable/.test(r.path);+// A later process with the maker's `--authorize retire:…` flags, read by the build's own parser against `spec`.+function retiring(h, flags, spec) {+ const read = configurationAuthorizationKeys(flags, spec);+ assert.deepEqual(read.problems, []);+ const ctx = createManagedCreateContext({ store: h.store, notFoundCode: B.NOT_FOUND_CODE });+ return { ...h, ctx, protectedConfiguration: P.createProtectedConfiguration({ store: h.store, gate: h.gate, ctx, apiBase: `${h.org.origin}/api/data/v9.0`, retirements: read.retire }) };+}+const retireFlagOf = (halt) => {+ const m = /--authorize '(retire:[^']+)'/.exec(halt.message);+ assert.ok(m, halt.message);+ return m[1];+};+async function refusedSecret() {+ let refuse = true;+ const h = await harness({ intercept: ({ method, path }) => (refuse && method === 'POST' && /^\/environmentvariable/.test(path)+ ? { statusCode: 400, body: { error: { code: '0x80072040', message: 'the Key Vault reference was refused' } } } : undefined) });+ const first = await pass(h, secretSpec(), secretValue());+ return { h, first, allow: () => { refuse = false; } };+}++test('a secret variable whose create the service refused stops with create-refused and leaves nothing pending: the rebuild with a value completes it', async () => {+ const { h, first, allow } = await refusedSecret();+ assert.equal(first.halt && first.halt.code, 'configuration-incomplete', first.halt && first.halt.message);+ assert.deepEqual(first.step.outcome.refused.map((r) => [r.kind, r.code, r.serviceCode]), [['environmentVariable', 'create-refused', '0x80072040']]);+ assert.deepEqual(first.step.outcome.unknown, []);+ assert.match(first.halt.message, /contoso_Key \(create-refused\) \(the service refused it \(0x80072040\): nothing was created or changed and nothing is left pending/);+ const group = h.store.readGroup('environmentVariable', 'contoso_key');+ assert.equal(group.pending, null, 'the attempt is released: no later build is held by it');+ assert.equal(group.committed, null);+ assert.deepEqual(variableRows(h), [0, 0]);+ // No secret reference is written to the store or shown to the maker.+ assert.ok(!fs.readFileSync(h.store.file, 'utf8').includes('vault-sample'), 'the store holds no Key Vault reference');+ assert.ok(!first.halt.message.includes('vault-sample'));++ allow();+ const done = await pass(reopen(h), secretSpec(), secretValue());+ assert.equal(done.halt, null, done.halt && `${done.halt.code}: ${done.halt.message}`);+ assert.equal(done.sent.filter((r) => r.method === 'POST' && r.path.startsWith('/environmentvariabledefinitions')).length, 1, 'created once');+ assert.deepEqual(variableRows(h), [1, 1]);+ assert.ok(committed(h, 'environmentVariable', 'contoso_key'));+ const rerun = await pass(reopen(h), secretSpec(), secretValue());+ assert.equal(rerun.halt, null);+ assert.deepEqual(rerun.sent, []);+});++test('a secret variable whose create the service refused no longer holds a build whose App Spec drops it', async () => {+ const { h, first } = await refusedSecret();+ assert.ok(first.halt);+ const out = await pass(reopen(h), noConfig());+ assert.equal(out.halt, null, out.halt && `${out.halt.code}: ${out.halt.message}`);+ assert.deepEqual(out.sent, []);+ assert.deepEqual(variableRows(h), [0, 0]);+});++test('a secret variable whose create answer was lost stays pending: never sent again, and dropped only under its exact retire approval', async () => {+ let org = null;+ let lose = true;+ const h = await harness({ intercept: async (req) => {+ if (!lose || !isVariableCreate(req)) return undefined;+ lose = false;+ await org.request({ url: `${org.origin}/api/data/v9.0${req.path}`, method: 'POST', headers: req.headers, body: JSON.stringify(req.body) });+ return { statusCode: 503, body: { error: { code: '0x80040216', message: 'the answer was lost' } } };+ } });+ org = h.org;+ const first = await pass(h, secretSpec(), secretValue());+ assert.ok(first.halt);+ assert.deepEqual(first.step.outcome.refused, [], 'a lost answer is never read as a refusal');+ assert.ok(h.store.readGroup('environmentVariable', 'contoso_key').pending, 'the outcome is unknown: the attempt stays');+ const landed = variableRows(h);+ assert.equal(landed[0], 1, 'the definition landed');+ const again = await pass(reopen(h), secretSpec(), { ...secretValue(), ...overwriteCopy('environmentVariable', 'contoso_key') });+ assert.ok(again.halt);+ assert.deepEqual(again.sent.filter(isVariableCreate), [], 'the create is not sent again');++ // Dropped from the App Spec: the build stops, names the exact approval, and sends nothing.+ const dropped = await pass(reopen(h), noConfig());+ assert.equal(dropped.halt && dropped.halt.code, 'managed-settlement-pending', dropped.halt && dropped.halt.message);+ assert.deepEqual(dropped.sent, []);+ const flag = retireFlagOf(dropped.halt);+ assert.match(flag, /^retire:environmentVariable:contoso_key@[0-9a-f-]{36}$/);+ // An approval for another attempt of the same item retires nothing.+ const other = await pass(retiring(h, [flag.replace(/@.*$/, '@00000000-0000-4000-8000-000000000009')], noConfig()), noConfig());+ assert.equal(other.halt && other.halt.code, 'managed-settlement-pending');+ assert.ok(h.store.readGroup('environmentVariable', 'contoso_key').pending);++ const warned = [];+ const out = await pass(retiring(h, [flag], noConfig()), noConfig(), { warn: (m) => warned.push(m) });+ assert.equal(out.halt, null, out.halt && `${out.halt.code}: ${out.halt.message}`);+ assert.deepEqual(out.sent, [], 'nothing is deleted or sent');+ assert.equal(h.store.readGroup('environmentVariable', 'contoso_key').pending, null);+ assert.deepEqual(variableRows(h), landed, 'the rows it may have created stay');+ assert.ok(warned.some((m) => /no longer tracks the unfinished attempt for environmentVariable contoso_key.*as approved/.test(m)), warned.join('\n'));++ // Declared again, the item is an unbound create whose derived id is taken: it stops, and nothing is created twice.+ const back = await pass(reopen(h), secretSpec(), secretValue());+ assert.equal(back.halt && back.halt.code, 'create-identity-conflict', back.halt && back.halt.message);+ assert.equal(back.halt.phase, 'preflight');+ assert.deepEqual(back.sent, []);+ assert.deepEqual(variableRows(h), landed);+});++// A create the service refused under 2.26.0, which recorded no refusal (no notStarted count): the attempt is pending in+// phase "sending" and only its own ids can complete it, so corrected settings alone still stop the build. The stop names+// the supported way out, with the exact approval: remove the item, run with the approval (nothing deleted or sent), restore+// it. The stores were written by the 2.26.0 modules (fixtures/managed-bindings-2.26-refused-secret.json says how).+const LEGACY = JSON.parse(fs.readFileSync(path.join(__dirname, 'fixtures', 'managed-bindings-2.26-refused-secret.json'), 'utf8'));+async function legacyRefused(which) {+ const seed = LEGACY[which];+ const h = await harness({ storeSeed: seed.store });+ for (const row of seed.landed) {+ const put = await h.org.request({ url: `${h.org.origin}/api/data/v9.0${row.path}`, method: 'POST', headers: { 'Content-Type': 'application/json', 'MSCRM.SolutionUniqueName': SOL }, body: JSON.stringify(row.body) });+ assert.ok(put.statusCode < 300, String(put.statusCode));+ }+ const token = seed.store.attempts[0].token;+ assert.equal(h.store.readGroup('environmentVariable', 'contoso_key').pending.token, token, 'the 2.26.0 store is read as written');+ return { h, token, flag: `retire:environmentVariable:contoso_key@${token}` };+}+function assertLegacyStop(out, flag) {+ assert.equal(out.halt && out.halt.code, 'create-completion-required', out.halt && out.halt.message);+ assert.equal(out.halt.phase, 'preflight');+ assert.deepEqual(out.sent, [], 'corrected settings alone send nothing for it');+ assert.match(out.halt.message, /remove this item \(and its deployment-settings entry\) from the App Spec/);+ assert.ok(out.halt.message.includes(`--authorize '${flag}'`), out.halt.message);+ assert.match(out.halt.message, /then restore them and run again/);+ assert.ok(!out.halt.message.includes('vault-sample'));+}++test('a secret create a 2.26.0 build left pending after the service refused it stops with the way out; removing it, retiring it and restoring it creates it once', async () => {+ const { h, flag } = await legacyRefused('refused');+ assertLegacyStop(await pass(reopen(h), secretSpec(), secretValue()), flag);++ const retired = await pass(retiring(h, [flag], noConfig()), noConfig());+ assert.equal(retired.halt, null, retired.halt && `${retired.halt.code}: ${retired.halt.message}`);+ assert.deepEqual(retired.sent, [], 'nothing is deleted or sent');+ assert.equal(h.store.readGroup('environmentVariable', 'contoso_key').pending, null);++ const restored = await pass(reopen(h), secretSpec(), secretValue());+ assert.equal(restored.halt, null, restored.halt && `${restored.halt.code}: ${restored.halt.message}`);+ assert.equal(restored.sent.filter((r) => r.method === 'POST' && r.path.startsWith('/environmentvariabledefinitions')).length, 1, 'created once');+ assert.deepEqual(variableRows(h), [1, 1]);+ assert.equal(committed(h, 'environmentVariable', 'contoso_key').records[0].id, LEGACY.refused.store.attempts[0].root.id, 'at the same derived id');+ assert.deepEqual((await pass(reopen(h), secretSpec(), secretValue())).sent, []);+});++test('a 2.26.0 pending secret create whose definition row landed: after the retirement the restored item stops on that row, and deleting it lets the build create the item', async () => {+ const { h, flag } = await legacyRefused('valueRefused');+ assert.deepEqual(variableRows(h), [1, 0]);+ assertLegacyStop(await pass(reopen(h), secretSpec(), secretValue()), flag);++ const retired = await pass(retiring(h, [flag], noConfig()), noConfig());+ assert.equal(retired.halt, null, retired.halt && `${retired.halt.code}: ${retired.halt.message}`);+ assert.deepEqual(retired.sent, []);+ assert.deepEqual(variableRows(h), [1, 0], 'the row it made stays');++ const id = LEGACY.valueRefused.store.attempts[0].root.id;+ const back = await pass(reopen(h), secretSpec(), secretValue());+ assert.equal(back.halt && back.halt.code, 'create-identity-conflict', back.halt && back.halt.message);+ assert.equal(back.halt.phase, 'preflight');+ assert.deepEqual(back.sent, []);+ assert.ok(back.halt.message.includes(id), back.halt.message);+ assert.match(back.halt.message, /delete that row in the environment, then run again/);++ const gone = await h.org.request({ url: `${h.org.origin}/api/data/v9.0/environmentvariabledefinitions(${id})`, method: 'DELETE', headers: {} });+ assert.ok(gone.statusCode < 300, String(gone.statusCode));+ const done = await pass(reopen(h), secretSpec(), secretValue());+ assert.equal(done.halt, null, done.halt && `${done.halt.code}: ${done.halt.message}`);+ assert.deepEqual(variableRows(h), [1, 1]);+ assert.equal(committed(h, 'environmentVariable', 'contoso_key').records[0].id, id);+});++test('the retire approval is read only for an item the App Spec no longer declares, and only in its exact shape', () => {+ const flag = 'retire:environmentVariable:contoso_key@3dedb827-fb3f-4577-a6a2-ec73e634807e';+ const ok = configurationAuthorizationKeys([flag], noConfig());+ assert.deepEqual(ok.problems, []);+ assert.deepEqual([...ok.retire], ['environmentVariable\u0000contoso_key\u00003dedb827-fb3f-4577-a6a2-ec73e634807e']);+ const declared = configurationAuthorizationKeys([flag], secretSpec());+ assert.deepEqual(declared.problems.map((p) => p.code), ['CONFIGURATION_RETIRE_DECLARED']);+ assert.equal(declared.retire.size, 0);+ for (const bad of ['retire:environmentVariable:contoso_key', 'retire:environmentVariable:contoso_key@not-a-token', 'retire:form:main@3dedb827-fb3f-4577-a6a2-ec73e634807e', 'retire::@3dedb827-fb3f-4577-a6a2-ec73e634807e']) {+ const read = configurationAuthorizationKeys([bad], noConfig());+ assert.deepEqual(read.problems.map((p) => p.code), ['CONFIGURATION_RETIRE_INVALID'], bad);+ assert.equal(read.retire.size, 0, bad);+ }+});++// The same refusal for every other protected kind: released in the same run, and the corrected App Spec creates it once.+test('a plain variable, a connection reference, a Custom API and a rule whose create the service refused are released and created once by the rebuild', async () => {+ const REF = { logicalName: 'contoso_sp', connectorId: DATA_SOURCE, name: 'SharePoint' };+ const refSettings = (s) => ({ configurationBindings: readDeploymentBindings({ ConnectionReferences: [{ LogicalName: 'contoso_sp', ConnectionId: 'conn-one' }] }, s),+ connections: async () => [{ connectionId: 'conn-one', connectorId: DATA_SOURCE }] });+ const only = (over) => configSpec({ environmentVariables: [], customApis: [], duplicateDetectionRules: [], ...over });+ const cases = [+ ['environmentVariable', 'contoso_apibase', 'environmentvariabledefinitions', only({ environmentVariables: [{ schemaName: 'contoso_ApiBase', type: 'string', defaultValue: 'https://api.contoso.com' }] }), () => ({})],+ ['connectionReference', 'contoso_sp', 'connectionreferences', only({ connectionReferences: [REF] }), refSettings],+ ['customApi', 'contoso_calc', 'customapis', only({ customApis: [API] }), () => ({})],+ ['duplicateRule', 'email', 'duplicaterules', only({ duplicateDetectionRules: [RULE] }), () => ({})],+ ];+ for (const [kind, key, table, spec, settings] of cases) {+ let refuse = true;+ const h = await harness({ intercept: ({ method, path }) => (refuse && method === 'POST' && path.split('?')[0] === `/${table}`+ ? { statusCode: 400, body: { error: { code: '0x80040265', message: 'refused' } } } : undefined) });+ const first = await pass(h, spec, settings(spec));+ assert.equal(first.halt && first.halt.code, 'configuration-incomplete', `${kind}: ${first.halt && first.halt.message}`);+ assert.deepEqual(first.step.outcome.refused.map((r) => [r.kind, r.code]), [[kind, 'create-refused']], kind);+ assert.equal(h.store.readGroup(kind, key).pending, null, `${kind}: released`);+ assert.equal(h.org.rows(table).length, 0, kind);+ // Dropped, it holds nothing; declared again, it is created once.+ assert.equal((await pass(reopen(h), noConfig())).halt, null, `${kind}: dropping it is not held`);+ refuse = false;+ const done = await pass(reopen(h), spec, settings(spec));+ assert.equal(done.halt, null, `${kind}: ${done.halt && `${done.halt.code}: ${done.halt.message}`}`);+ assert.equal(h.org.rows(table).length, 1, `${kind}: created once`);+ assert.ok(committed(h, kind, key), kind);+ }+});+test('the sweep lets go of an undeclared attempt the store proves never sent, with no approval; one that may have been sent stays', () => {+ const R = require('./helpers/managed-rows.js');+ const sealed = [+ { kind: 'customApi', key: R.API_KEY, id: R.API, sentFields: ['uniquename'], sentSha256: R.H('7') },+ { kind: 'customApiRequestParameter', key: R.REQ_KEY, id: R.REQ, sentFields: ['uniquename'], sentSha256: R.H('8') },+ ];+ const held = (store) => {+ const [token] = store.prepareAttemptSet([R.apiPlan()]);+ return store.markAttemptSetSending([{ token, expected: R.apiExpected() }], { claim: 'first', observed: true })[0];+ };+ const prepared = R.open(makeTempDir('cfg-sweep-'));+ prepared.prepareAttemptSet([R.apiPlan()]);+ assert.deepEqual(P.pendingSweep({ spec: noConfig(), store: prepared }), { halts: [], retired: [{ kind: 'customApi', key: R.API_KEY, how: 'unsent' }] });+ assert.equal(prepared.readGroup('customApi', R.API_KEY).pending, null);++ // Its one request refused unstarted, and the run stopped before it released the attempt.+ const refused = R.open(makeTempDir('cfg-sweep-'));+ const r = held(refused);+ refused.sealRowDispatch({ ...r, rows: sealed });+ refused.noteRowsNotStarted({ ...r, rows: sealed });+ assert.deepEqual(P.pendingSweep({ spec: noConfig(), store: refused }), { halts: [], retired: [{ kind: 'customApi', key: R.API_KEY, how: 'not-started' }] });+ assert.equal(refused.readGroup('customApi', R.API_KEY).pending, null);++ const sent = R.open(makeTempDir('cfg-sweep-'));+ const s = held(sent);+ sent.sealRowDispatch({ ...s, rows: sealed });+ const { halts, retired } = P.pendingSweep({ spec: noConfig(), store: sent });+ assert.deepEqual(retired, []);+ assert.deepEqual(halts.map((x) => [x.code, x.authorize]), [['managed-settlement-pending', [`retire:customApi:${R.API_KEY}@${s.token}`]]]);+ assert.ok(sent.readGroup('customApi', R.API_KEY).pending, 'kept until approved');+ // The approval names that attempt; under it the store stops tracking it.+ assert.deepEqual(P.pendingSweep({ spec: noConfig(), store: sent, retirements: [`customApi\u0000${R.API_KEY}\u0000${s.token}`] }), { halts: [], retired: [{ kind: 'customApi', key: R.API_KEY, how: 'approved' }] });+ assert.equal(sent.readGroup('customApi', R.API_KEY).pending, null);+});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/create-stable-identities.test.js b/plugins/model-apps/scripts/tests/create-stable-identities.test.jsindex f9e9b99d0..210283cad 100644--- a/plugins/model-apps/scripts/tests/create-stable-identities.test.js+++ b/plugins/model-apps/scripts/tests/create-stable-identities.test.js@@ -25,6 +25,8 @@ const { createFakeBuildOrg } = require('./helpers/fake-app-build-org.js');const { gatedClient } = require('./helpers/gated-fake-client.js');const { seedManagedDebt } = require('./helpers/managed-debt.js');const { verifySpec } = require('../lib/verify-spec.js');+const { appComponentsFor, declaredAppPins } = require('../lib/app-components.js');+const { indexArtifacts } = require('../lib/apply-snapshot-index.js');const dirs = [];test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });@@ -1465,3 +1467,152 @@ test('standalone discovery reads a workspace path that is a file, or lies underassert.deepEqual([found.absent, found.debt], [true, []], workspaceDir);}});++// --- #845: two declared views of one name on one table, each under its own key ------------------------------------------------------++// A reader over the fake org's saved queries that applies the filter verify sends, as the service does: by the row's id, or by its+// table and name (every row of that name, up to `top`, in the order the org holds them).+const savedQueryReader = (org, reads = []) => ({+ findTable: async () => ({ logicalName: 'contoso_item' }),+ findColumns: async () => [{ logicalName: 'contoso_code' }],+ sitemapXml: async () => '<SiteMap><Area><Group><SubArea Entity="contoso_item"/></Group></Area></SiteMap>',+ queryRecords: async (set, q) => {+ if (set !== 'savedquery') return [];+ reads.push(q.filter);+ const all = org.fake.rows('savedqueries').map((r) => r.data);+ const byId = /^savedqueryid eq ([0-9a-f-]{36})$/.exec(q.filter);+ if (byId) return all.filter((r) => r.savedqueryid === byId[1]);+ const byName = /^returnedtypecode eq '([^']*)' and name eq '([^']*)'$/.exec(q.filter);+ return byName ? all.filter((r) => r.returnedtypecode === byName[1] && r.name === byName[2]).slice(0, q.top || 50) : [];+ },+});+const twin = (key, columns) => ({ entity: 'contoso_item', name: 'Twin', key, reconcile: 'declared', columns });+const twinSpec = (views) => stableSpec({ minimumPluginVersion: '2.21.0', views, charts: [] });+const viewChecks = (r) => r.checks.filter((c) => c.kind === 'view' || c.kind === 'view-columns').map((c) => [c.kind, c.present, c.detail]);++test('#845: two same-named declared views under their own keys are both recorded as created, and each is verified against its own row', async () => {+ const org = createFakeBuildOrg({ entities: ENTITIES });+ const dir = newDir();+ const spec = twinSpec([twin('v1', ['contoso_name']), twin('v2', ['contoso_name', 'contoso_code'])]);+ assert.deepEqual(validateAppSpec(spec).errors, []);+ const built = await build(org, dir, spec);+ assert.equal(built.err, undefined, built.err && built.err.message);+ const rows = org.fake.rows('savedqueries').map((r) => r.data).filter((r) => r.name === 'Twin');+ assert.equal(rows.length, 2, 'the build made a row for each key');+ const s = createStableCreates({ spec, sdk: null, store: null, basePort: createPassthroughCreates() });+ const [id1, id2] = ['v1', 'v2'].map((k) => s.identityFor('view', k).id);+ assert.deepEqual(new Set(rows.map((r) => r.savedqueryid)), new Set([id1, id2]));+ // The record of created views holds both: the `entity|name` entry as before (the last of the pair), the other in its own list.+ assert.deepEqual(built.out.created.views, { 'contoso_item|Twin': id2 });+ assert.deepEqual(built.out.created.sameNamedViews, [{ entity: 'contoso_item', name: 'Twin', key: 'v1', id: id1 }]);+ assert.deepEqual(appComponentsFor(built.out.created).views, [id2, id1]);+ // The table is published once, as for one view.+ assert.equal(built.tablePublishes.filter((names) => names.includes('contoso_item')).length, 1);++ // Verify with the bindings of this workspace: each view is read by its bound id and held to its own columns.+ const managedManifest = readManagedManifest(workspaceArgs(org, dir));+ const reads = [];+ const r = await verifySpec(spec, savedQueryReader(org, reads), { managedManifest });+ assert.equal(r.ok, true, JSON.stringify(r.missing));+ assert.deepEqual(viewChecks(r), [['view', true, ''], ['view-columns', true, ''], ['view', true, ''], ['view-columns', true, '']]);+ assert.deepEqual(reads.sort(), [`savedqueryid eq ${id1}`, `savedqueryid eq ${id1}`, `savedqueryid eq ${id2}`, `savedqueryid eq ${id2}`].sort(), 'each view read by its bound id (and its managed check)');+ // A declaration that is not what its own row holds fails for that view only, named by its key.+ const drifted = await verifySpec(twinSpec([twin('v1', ['contoso_name']), twin('v2', ['contoso_name', 'contoso_kind'])]), savedQueryReader(org), { managedManifest });+ assert.deepEqual(drifted.missing.map((c) => [c.kind, c.name, c.detail]), [['view-columns', 'contoso_item.Twin', 'missing column(s): contoso_kind (view key v2)']]);++ // A downloaded spec pins each view by its viewId: read by that id without the bindings too.+ const pinned = twinSpec([{ ...twin('v1', ['contoso_name']), viewId: id1 }, { ...twin('v2', ['contoso_name', 'contoso_code']), viewId: id2 }]);+ const byPin = await verifySpec(pinned, savedQueryReader(org));+ assert.equal(byPin.ok, true, JSON.stringify(byPin.missing));+ assert.equal(byPin.checks.filter((c) => c.kind === 'view-columns' && c.present).length, 2);++ // Neither binding nor pin: the name finds a row, but which of the two it is cannot be told, so the content is unverified, not failed.+ const unbound = await verifySpec(spec, savedQueryReader(org));+ assert.equal(unbound.ok, true, JSON.stringify(unbound.missing));+ assert.deepEqual(viewChecks(unbound), [['view', true, ''], ['view', true, '']]);+ assert.deepEqual(unbound.unverified.filter((u) => u.startsWith('view')).length, 2);+});++test('#845: a bound or pinned view whose row is gone is missing, and its namesake is not taken in its place', async () => {+ const org = createFakeBuildOrg({ entities: ENTITIES });+ const dir = newDir();+ const spec = twinSpec([twin('v1', ['contoso_name']), twin('v2', ['contoso_name', 'contoso_code'])]);+ const built = await build(org, dir, spec);+ assert.equal(built.err, undefined, built.err && built.err.message);+ const managedManifest = readManagedManifest(workspaceArgs(org, dir));+ const id2 = built.out.created.views['contoso_item|Twin'];+ const reader = savedQueryReader(org);+ const without = { ...reader, queryRecords: async (set, q) => (q.filter === `savedqueryid eq ${id2}` ? [] : reader.queryRecords(set, q)) };+ const r = await verifySpec(spec, without, { managedManifest });+ assert.equal(r.ok, false);+ assert.deepEqual(r.missing.filter((c) => c.kind === 'view').map((c) => [c.name, c.detail]), [+ ['contoso_item.Twin', `the view its managed binding (v2) is bound to (${id2}) was not found on its table; a view of the same name is not taken in its place (view key v2)`],+ ]);+ // A pin that names another row than the binding is a conflict to correct, not a pass.+ const id1 = built.out.created.sameNamedViews.find((v) => v.key === 'v1').id;+ const crossed = await verifySpec(twinSpec([twin('v1', ['contoso_name']), { ...twin('v2', ['contoso_name', 'contoso_code']), viewId: id1 }]), reader, { managedManifest });+ assert.deepEqual(crossed.missing.map((c) => [c.kind, c.detail]), [+ ['view', `its viewId ${id1} is not the view its managed binding (v2) is bound to (${id2}); correct or remove the viewId (view key v2)`],+ ]);+ // An attempt still pending for the key proves nothing: unverified, never a pass or a failure.+ const open = { ...managedManifest, groups: managedManifest.groups.filter((g) => g.key !== 'v2'), pending: [{ family: 'view', key: 'v2', code: 'managed-settlement-pending' }] };+ const held = await verifySpec(spec, reader, { managedManifest: open });+ assert.ok(held.unverified.includes('view:contoso_item.Twin (its managed binding (v2) is not settled (managed-settlement-pending) — unverified, not proven correct)'));+ assert.deepEqual(viewChecks(held), [['view', true, ''], ['view-columns', true, '']], 'only the settled view is checked');+ // A binding store that cannot be read proves no binding either: each declared view is unverified, as a declared chart is,+ // never read by its name in place of the row the store may bind.+ const unreadable = { revision: 0, groups: [], pending: [], invalid: [{ family: 'store', key: 'managed-bindings', code: 'managed-binding-store-unreadable' }] };+ const blind = await verifySpec(spec, reader, { managedManifest: unreadable });+ assert.deepEqual(viewChecks(blind), [], 'no view is checked by its name');+ for (const key of ['v1', 'v2']) {+ assert.ok(blind.unverified.includes(`view:contoso_item.Twin (its managed binding (${key}) is not settled (managed-binding-store-unreadable) — unverified, not proven correct)`), JSON.stringify(blind.unverified));+ }+});++test('#845 control: a spec without same-named views records and verifies exactly as before', async () => {+ const org = createFakeBuildOrg({ entities: ENTITIES });+ const dir = newDir();+ const other = { entity: 'contoso_item', name: 'Other', reconcile: 'declared', columns: ['contoso_code'] };+ const spec = twinSpec([twin('v1', ['contoso_name']), other]);+ const built = await build(org, dir, spec);+ assert.equal(built.err, undefined, built.err && built.err.message);+ assert.deepEqual(Object.keys(built.out.created.views), ['contoso_item|Twin', 'contoso_item|Other']);+ assert.equal(built.out.created.sameNamedViews, undefined);+ assert.equal(built.tablePublishes.filter((names) => names.includes('contoso_item')).length, 1);+ // Without bindings, a declared view is read by its table and name, one row, as it always was.+ const reads = [];+ const r = await verifySpec(spec, savedQueryReader(org, reads));+ assert.equal(r.ok, true, JSON.stringify(r.missing));+ assert.deepEqual(viewChecks(r), [['view', true, ''], ['view-columns', true, ''], ['view', true, ''], ['view-columns', true, '']]);+ assert.deepEqual(reads, ["returnedtypecode eq 'contoso_item' and name eq 'Twin'", "returnedtypecode eq 'contoso_item' and name eq 'Other'"]);+ // An unkeyed legacy view of the same name as a declared one is read by its name too, and its content checked, as before.+ const legacyReads = [];+ const legacy = await verifySpec({ ...spec, views: [{ entity: 'contoso_item', name: 'Other', columns: ['contoso_code'] }, other] }, savedQueryReader(org, legacyReads));+ assert.equal(legacy.ok, true, JSON.stringify(legacy.missing));+ assert.equal(legacy.checks.filter((c) => c.kind === 'view-columns' && c.present).length, 2);+ assert.deepEqual(legacyReads, ["returnedtypecode eq 'contoso_item' and name eq 'Other'", "returnedtypecode eq 'contoso_item' and name eq 'Other'"]);+});+test('#845: a view named like another view plus a key keeps its own entry, and the same-named pair is still recorded in full', async () => {+ for (const thirdFirst of [true, false]) {+ // `Twin|v1` is a legal view name of its own; a record that joined `entity|name|key` would give its entry to the first Twin.+ const third = { ...twin('third', ['contoso_code']), name: 'Twin|v1' };+ const pair = [twin('v1', ['contoso_name']), twin('v2', ['contoso_name', 'contoso_code'])];+ const spec = twinSpec(thirdFirst ? [third, ...pair] : [...pair, third]);+ assert.deepEqual(validateAppSpec(spec).errors, []);+ const org = createFakeBuildOrg({ entities: ENTITIES });+ const built = await build(org, newDir(), spec);+ assert.equal(built.err, undefined, built.err && built.err.message);+ const s = createStableCreates({ spec, sdk: null, store: null, basePort: createPassthroughCreates() });+ const [id1, id2, own] = ['v1', 'v2', 'third'].map((k) => s.identityFor('view', k).id);+ assert.deepEqual(new Set(org.fake.rows('savedqueries').map((r) => r.data.savedqueryid)), new Set([id1, id2, own]), `thirdFirst=${thirdFirst}`);+ // The name entries are what they always were: `Twin|v1` is its own view, `Twin` the last of the pair.+ assert.deepEqual(built.out.created.views, { 'contoso_item|Twin|v1': own, 'contoso_item|Twin': id2 }, `thirdFirst=${thirdFirst}`);+ assert.equal(indexArtifacts(spec, built.out.created).views['contoso_item|Twin|v1'].viewId, own);+ assert.equal(indexArtifacts(spec, built.out.created).views['contoso_item|Twin'].viewId, id2);+ // The first Twin is recorded too, apart from the name entries, so the app's components and declared pins hold all three.+ assert.deepEqual(built.out.created.sameNamedViews, [{ entity: 'contoso_item', name: 'Twin', key: 'v1', id: id1 }]);+ assert.deepEqual(new Set(appComponentsFor(built.out.created).views), new Set([id1, id2, own]));+ assert.deepEqual(new Set(declaredAppPins(built.out.created).views), new Set([id1, id2, own]));+ assert.equal(appComponentsFor(built.out.created).views.length, 3);+ }+});diff --git a/plugins/model-apps/scripts/tests/download-managed-lifecycle.test.js b/plugins/model-apps/scripts/tests/download-managed-lifecycle.test.jsindex d183b2fa1..07d898b58 100644--- a/plugins/model-apps/scripts/tests/download-managed-lifecycle.test.js+++ b/plugins/model-apps/scripts/tests/download-managed-lifecycle.test.js@@ -8,6 +8,13 @@ const assert = require('node:assert/strict');const fs = require('node:fs');const os = require('node:os');const path = require('node:path');+// The `pac` process boundary, for the test of the download's own connections reader (below): list-connections.js takes+// spawnResultTree from process-runner.js as it loads, so the stand-in must be in place before anything loads it. It passes every+// call through unless that test has set `pacStandIn`, and then answers only `pac` with it.+const processRunner = require('../lib/process-runner.js');+const realSpawnResultTree = processRunner.spawnResultTree;+let pacStandIn = null;+processRunner.spawnResultTree = (command, args, options) => (pacStandIn && command === 'pac' ? pacStandIn(args, options) : realSpawnResultTree(command, args, options));const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');const { createLifecycleHarness, appUniqueName, publishesOf } = require('./helpers/lifecycle-harness.js');const { main } = require('../download-model-app.js');@@ -302,6 +309,110 @@ test('protected configuration restored by a managed download rebuilds completelyassert.deepEqual(org.unexpected, []);});+// The download's own connections reader — main's default when no `connections` is given, list-connections.js readConnections, the one a+// build proves a binding with — and not a stand-in for it. Only its boundaries stand in: the Azure CLI tokens (dataverse-auth.js), the+// SDK's connectivity client (maker-sdk.js createMakerSdk with `connectivity: true`) and the `pac` process. The SDK reads the connections;+// when its route is refused (here, no Power Apps token) pac reads them, pinned to the download's environment; any other failure of the+// read is no proof, so the reference is left out as `page-unready` and the download still succeeds. Two references one page names share+// one read, and the connection id is in nothing the download writes or prints, even in a failed read's message.+async function withDefaultReader(origin, run) {+ const auth = require('../lib/dataverse-auth.js');+ const makerSdk = require('../lib/maker-sdk.js');+ const saved = { getAuthTokenAsync: auth.getAuthTokenAsync, getPowerAppsTokenAsync: auth.getPowerAppsTokenAsync, createMakerSdk: makerSdk.createMakerSdk };+ const reader = { mode: 'sdk', listed: [], sdk: 0, pac: [] };+ auth.getAuthTokenAsync = async () => 'synthetic-dataverse-token';+ auth.getPowerAppsTokenAsync = async () => (reader.mode === 'pac' ? null : 'synthetic-power-apps-token');+ makerSdk.createMakerSdk = (options) => {+ if (!options || options.connectivity !== true) return saved.createMakerSdk(options);+ assert.equal(options.instanceUrl, origin);+ return {+ listConnections: async () => {+ reader.sdk += 1;+ if (reader.mode === 'throw') throw new Error(`listing failed after ${CONFIG_CANARY.connection}`);+ return reader.listed.map((c) => ({ ...c }));+ },+ };+ };+ pacStandIn = async (args, options) => {+ reader.pac.push(args);+ assert.deepEqual(options.stdio, ['ignore', 'pipe', 'pipe']);+ return { status: 0, stdout: JSON.stringify(reader.listed), stderr: '' };+ };+ try {+ return await run(reader);+ } finally {+ Object.assign(auth, { getAuthTokenAsync: saved.getAuthTokenAsync, getPowerAppsTokenAsync: saved.getPowerAppsTokenAsync });+ makerSdk.createMakerSdk = saved.createMakerSdk;+ pacStandIn = null;+ }+}+const leaksConnection = (dl) => [dl.said, JSON.stringify(dl.payload), ...walkFiles(dl.out).map((f) => fs.readFileSync(f, 'latin1'))].some((text) => text.includes(CONFIG_CANARY.connection));++test('with no connections given, a managed download reads them as a build does: through the SDK, through pac when the SDK route is refused, and any other failure leaves a page-named reference out', async () => {+ const spec = configuredSpec();+ spec.connectionReferences.push({ ...spec.connectionReferences[0], logicalName: 'contoso_sp2', name: 'SharePoint two' });+ spec.pages = [{+ key: 'preview', name: 'Preview', purpose: 'Preview items', dataSources: ['contoso_item'], source: { kind: 'tsx', codeFile: 'KitchenPage.tsx' },+ connectorBindings: spec.connectionReferences.map((x) => ({ logicalName: x.logicalName, connectorId: SP })),+ }];+ spec.appShell.areas[0].groups[0].subAreas.push({ page: 'preview', title: 'Preview' });+ const usable = [{ connectionId: CONFIG_CANARY.connection, connectorId: SP, displayName: 'SharePoint' }];+ const bindings = readDeploymentBindings({ ConnectionReferences: spec.connectionReferences.map((x) => ({ LogicalName: x.logicalName, ConnectionId: CONFIG_CANARY.connection, ConnectorId: SP })) }, spec);+ assert.deepEqual(bindings.errors, []);+ const app = await builtLifecycle(spec, { configuration: true }, { configurationBindings: bindings, connections: usable });+ const { org } = app;+ const origin = new URL(org.origin).origin;+ const referenceRows = () => JSON.stringify([...org.rowsOf('connectionreferences').values()].map((r) => r.data));+ const rowsBefore = referenceRows();+ const left = (dl) => dl.payload.managedConnectionReferences.omitted.map((o) => [o.key, o.code]);+ const unready = [['contoso_sp', 'page-unready'], ['contoso_sp2', 'page-unready']];+ await withDefaultReader(origin, async (reader) => {+ reader.listed = usable;+ const viaSdk = await app.download({ managed: true });+ assert.deepEqual(viaSdk.payload.managedConnectionReferences.restored, ['contoso_sp', 'contoso_sp2']);+ assert.deepEqual([reader.sdk, reader.pac.length], [1, 0], 'one SDK read serves both references');+ assert.equal(leaksConnection(viaSdk), false);++ reader.mode = 'pac';+ const viaPac = await app.download({ managed: true });+ assert.deepEqual(viaPac.payload.managedConnectionReferences.restored, ['contoso_sp', 'contoso_sp2']);+ assert.equal(reader.sdk, 1, 'a refused route makes no SDK read');+ assert.deepEqual(reader.pac, [['connection', 'list', '--environment', origin]]);+ assert.equal(leaksConnection(viaPac), false);++ reader.mode = 'throw';+ const failed = await app.download({ managed: true });+ assert.deepEqual(failed.payload.managedConnectionReferences.restored, []);+ assert.deepEqual(left(failed), unready);+ assert.equal(failed.spec.connectionReferences, undefined);+ assert.deepEqual([reader.sdk, reader.pac.length], [2, 1], 'one read for both references, and no pac for a failure that is not a refused route');+ assert.equal(leaksConnection(failed), false);++ reader.mode = 'sdk';+ reader.listed = [];+ const absent = await app.download({ managed: true });+ assert.deepEqual(left(absent), unready);+ assert.equal(reader.sdk, 3);++ const plain = await app.download({ managed: false });+ assert.equal(plain.spec.connectionReferences, undefined);+ assert.deepEqual([reader.sdk, reader.pac.length], [3, 1], 'a plain download reads no connections');+ });+ assert.equal(referenceRows(), rowsBefore);+ assert.deepEqual(org.unexpected, []);+});++test('the download reads no connections for references no page names', async () => {+ const app = await builtLifecycle(configuredSpec(), { configuration: true });+ await withDefaultReader(new URL(app.org.origin).origin, async (reader) => {+ reader.mode = 'throw';+ const managed = await app.download({ managed: true });+ assert.deepEqual(managed.payload.managedConnectionReferences.restored, ['contoso_sp']);+ assert.deepEqual([reader.sdk, reader.pac.length], [0, 0]);+ });+ assert.deepEqual(app.org.unexpected, []);+});+// A page that names a connection reference makes a rebuild gate the page on the reference's binding, proven against the environment's// connections (configuration-artifacts.js observe): the connection must be there and be one of the connector the reference names. A// connection id on the row is not that proof. So a managed download restores a reference a page names only when the same proof holdsdiff --git a/plugins/model-apps/scripts/tests/fixtures/managed-bindings-2.26-refused-secret.json b/plugins/model-apps/scripts/tests/fixtures/managed-bindings-2.26-refused-secret.jsonnew file mode 100644index 000000000..7f13b3801--- /dev/null+++ b/plugins/model-apps/scripts/tests/fixtures/managed-bindings-2.26-refused-secret.json@@ -0,0 +1,252 @@+{+ "about": "Binding stores written by the model-apps 2.26.0 modules (the real SDK, against tests/helpers/fake-config-org.js at its default origin) after a protected secret environment variable create was refused with HTTP 400 0x80072040. \"refused\": the definition POST was refused, so no row exists. \"valueRefused\": the definition POST landed (replayed from \"landed\") and the value POST was refused. Both leave the attempt pending in phase \"sending\" with no notStarted count, which 2.26.0 did not record.",+ "refused": {+ "store": {+ "schemaVersion": 2,+ "environmentFingerprint": "e18dcb8d70cd77ed3905a49454684aaf8edc4648e1861d5a311caa9937e07c15",+ "appUniqueName": "contoso_configured",+ "solutionUniqueName": "ContosoSol",+ "revision": 3,+ "groups": [],+ "attempts": [+ {+ "family": "environmentVariable",+ "key": "contoso_key",+ "token": "f7e8fed3-7227-460b-896a-bdcd81a01ca8",+ "baseGeneration": null,+ "phase": "sending",+ "root": {+ "kind": "environmentVariable",+ "key": "contoso_key",+ "id": "cec5ea81-bb49-5a8e-967e-7fd2034f7e20"+ },+ "knownScopes": [],+ "declarationSha256": "254318ddf4ed009841f4204dcb837aeb43b69ca2e8dbf27c259f6c7e746fa373",+ "expected": {+ "proofVersion": 1,+ "proofSchema": "configuration-rows-v1",+ "rootId": "cec5ea81-bb49-5a8e-967e-7fd2034f7e20",+ "baseProofSha256": null,+ "sentProjectionSha256": "78c15440bfb57b4ba1827fe9d226796538222611dbe238e9bcb269a470d5e6ce",+ "preservationSha256": "78950662d63cc1bfd15c0e1215589b83a9f51107c31a0553aa22e2dd8cb98411",+ "baseObservation": null,+ "children": [+ {+ "kind": "environmentVariableValue",+ "key": "[\"contoso_key\",\"value\"]",+ "namespaceParentId": "cec5ea81-bb49-5a8e-967e-7fd2034f7e20",+ "id": "4cbc4f35-3432-519d-984a-1527d6caaed1",+ "associationSha256": "de5eb232c8ce6265578a6a2e46028c92090e8fe9702280899d2bbcf9a289ad39"+ }+ ]+ },+ "acknowledgedRoot": false,+ "savedObservation": null,+ "publication": null,+ "completionReserve": {+ "bytes": 262144,+ "used": 1270+ },+ "rowProtocol": {+ "version": 1,+ "rows": [+ {+ "kind": "environmentVariable",+ "key": "contoso_key",+ "id": "cec5ea81-bb49-5a8e-967e-7fd2034f7e20",+ "parentId": null,+ "mode": "create",+ "expectedSha256": "94f53012cdef118a2fb9620c6b42ae63fe59ba12abee69f386df150d703e3b8d",+ "sensitiveInput": false,+ "sentFields": [+ "connectorId",+ "defaultValue",+ "description",+ "isRequired",+ "name",+ "parameterKey",+ "parentDefinitionId",+ "schemaName",+ "secretStore",+ "type",+ "valueSchema"+ ],+ "sentSha256": "f7b910f327f8f8d735afc1030eb0f02019f28e074d58984be0ca8fd7a00ae011",+ "dispatched": true+ },+ {+ "kind": "environmentVariableValue",+ "key": "[\"contoso_key\",\"value\"]",+ "id": "4cbc4f35-3432-519d-984a-1527d6caaed1",+ "parentId": "cec5ea81-bb49-5a8e-967e-7fd2034f7e20",+ "mode": "create",+ "expectedSha256": "b62e5dde04f3d9d71bc0991e721fc091643c41a1b86f82e435addd9cd639a9a7",+ "sensitiveInput": true,+ "sentFields": null,+ "sentSha256": null,+ "dispatched": false+ }+ ],+ "preserved": [],+ "completion": {+ "ruleState": null,+ "members": [+ {+ "kind": "environmentVariable",+ "id": "cec5ea81-bb49-5a8e-967e-7fd2034f7e20",+ "componentType": 380+ }+ ]+ },+ "effects": [+ {+ "kind": "membership",+ "id": "cec5ea81-bb49-5a8e-967e-7fd2034f7e20",+ "dispatched": false+ }+ ],+ "cohort": null+ },+ "sendWindow": {+ "possible": 1,+ "notStarted": 0,+ "epoch": 1+ }+ }+ ],+ "workflowEffects": []+ },+ "landed": []+ },+ "valueRefused": {+ "store": {+ "schemaVersion": 2,+ "environmentFingerprint": "e18dcb8d70cd77ed3905a49454684aaf8edc4648e1861d5a311caa9937e07c15",+ "appUniqueName": "contoso_configured",+ "solutionUniqueName": "ContosoSol",+ "revision": 4,+ "groups": [],+ "attempts": [+ {+ "family": "environmentVariable",+ "key": "contoso_key",+ "token": "f5af387b-b3fb-42d7-8341-cb1b581fe1ad",+ "baseGeneration": null,+ "phase": "sending",+ "root": {+ "kind": "environmentVariable",+ "key": "contoso_key",+ "id": "cec5ea81-bb49-5a8e-967e-7fd2034f7e20"+ },+ "knownScopes": [],+ "declarationSha256": "254318ddf4ed009841f4204dcb837aeb43b69ca2e8dbf27c259f6c7e746fa373",+ "expected": {+ "proofVersion": 1,+ "proofSchema": "configuration-rows-v1",+ "rootId": "cec5ea81-bb49-5a8e-967e-7fd2034f7e20",+ "baseProofSha256": null,+ "sentProjectionSha256": "78c15440bfb57b4ba1827fe9d226796538222611dbe238e9bcb269a470d5e6ce",+ "preservationSha256": "78950662d63cc1bfd15c0e1215589b83a9f51107c31a0553aa22e2dd8cb98411",+ "baseObservation": null,+ "children": [+ {+ "kind": "environmentVariableValue",+ "key": "[\"contoso_key\",\"value\"]",+ "namespaceParentId": "cec5ea81-bb49-5a8e-967e-7fd2034f7e20",+ "id": "4cbc4f35-3432-519d-984a-1527d6caaed1",+ "associationSha256": "de5eb232c8ce6265578a6a2e46028c92090e8fe9702280899d2bbcf9a289ad39"+ }+ ]+ },+ "acknowledgedRoot": false,+ "savedObservation": null,+ "publication": null,+ "completionReserve": {+ "bytes": 262144,+ "used": 1367+ },+ "rowProtocol": {+ "version": 1,+ "rows": [+ {+ "kind": "environmentVariable",+ "key": "contoso_key",+ "id": "cec5ea81-bb49-5a8e-967e-7fd2034f7e20",+ "parentId": null,+ "mode": "create",+ "expectedSha256": "94f53012cdef118a2fb9620c6b42ae63fe59ba12abee69f386df150d703e3b8d",+ "sensitiveInput": false,+ "sentFields": [+ "connectorId",+ "defaultValue",+ "description",+ "isRequired",+ "name",+ "parameterKey",+ "parentDefinitionId",+ "schemaName",+ "secretStore",+ "type",+ "valueSchema"+ ],+ "sentSha256": "f7b910f327f8f8d735afc1030eb0f02019f28e074d58984be0ca8fd7a00ae011",+ "dispatched": true+ },+ {+ "kind": "environmentVariableValue",+ "key": "[\"contoso_key\",\"value\"]",+ "id": "4cbc4f35-3432-519d-984a-1527d6caaed1",+ "parentId": "cec5ea81-bb49-5a8e-967e-7fd2034f7e20",+ "mode": "create",+ "expectedSha256": "b62e5dde04f3d9d71bc0991e721fc091643c41a1b86f82e435addd9cd639a9a7",+ "sensitiveInput": true,+ "sentFields": [+ "parentId"+ ],+ "sentSha256": "119bfdb4bbd1cabd2869c51403be2e3caa09b58b326f4e84be91df4c523bb009",+ "dispatched": true+ }+ ],+ "preserved": [],+ "completion": {+ "ruleState": null,+ "members": [+ {+ "kind": "environmentVariable",+ "id": "cec5ea81-bb49-5a8e-967e-7fd2034f7e20",+ "componentType": 380+ }+ ]+ },+ "effects": [+ {+ "kind": "membership",+ "id": "cec5ea81-bb49-5a8e-967e-7fd2034f7e20",+ "dispatched": false+ }+ ],+ "cohort": null+ },+ "sendWindow": {+ "possible": 2,+ "notStarted": 0,+ "epoch": 1+ }+ }+ ],+ "workflowEffects": []+ },+ "landed": [+ {+ "path": "/environmentvariabledefinitions?$select=environmentvariabledefinitionid",+ "body": {+ "schemaname": "contoso_Key",+ "type": 100000005,+ "displayname": "contoso_Key",+ "isrequired": false,+ "environmentvariabledefinitionid": "cec5ea81-bb49-5a8e-967e-7fd2034f7e20"+ }+ }+ ]+ }+}diff --git a/plugins/model-apps/scripts/tests/managed-bindings-rows.test.js b/plugins/model-apps/scripts/tests/managed-bindings-rows.test.jsindex c32f2efed..550d3c1d2 100644--- a/plugins/model-apps/scripts/tests/managed-bindings-rows.test.js+++ b/plugins/model-apps/scripts/tests/managed-bindings-rows.test.js@@ -129,6 +129,80 @@ test('retireProvenUnsentAttempt releases only a sending attempt that sent nothinassert.throws(() => store.sealRowDispatch({ token: held.token, epoch: held.epoch, rows: [SEALED[0]] }), 'the released run sends nothing more under it');});+// #847: a create the service refused before carrying it out (a 400 with a Dataverse code) un-seals exactly the rows that+// request carried, so the run can release the attempt; anything that does not match leaves the stricter state.+test('noteRowsNotStarted un-seals only the rows of the one refused request, at its epoch, and then the attempt is provably unsent', () => {+ const held = (store) => {+ const [token] = store.prepareAttemptSet([apiPlan()]);+ return store.markAttemptSetSending([{ token, expected: apiExpected() }], { claim: 'first', observed: true })[0];+ };+ const refused = [+ ['another epoch', ({ token, epoch }) => ({ token, epoch: epoch + 1, rows: SEALED })],+ ['a row under another id', ({ token, epoch }) => ({ token, epoch, rows: [{ ...SEALED[0], id: API2 }] })],+ ['a row sealed under another projection', ({ token, epoch }) => ({ token, epoch, rows: [{ ...SEALED[0], sentSha256: H('9') }] })],+ ['one row named twice', ({ token, epoch }) => ({ token, epoch, rows: [SEALED[0], SEALED[0]] })],+ ['no rows', ({ token, epoch }) => ({ token, epoch, rows: [] })],+ ];+ for (const [what, args] of refused) {+ const store = open(dirOf());+ const h = held(store);+ store.sealRowDispatch({ token: h.token, epoch: h.epoch, rows: SEALED });+ const before = text(store);+ assert.ok(codeOf(() => store.noteRowsNotStarted(args(h))), what);+ assert.equal(text(store), before, `${what}: nothing is written`);+ assert.equal(codeOf(() => store.retireProvenUnsentAttempt(h)), CODES.pending, `${what}: the attempt stays possibly sent`);+ }+ // A row never sealed is not un-sealed by a refusal of another request.+ const unsealed = open(dirOf());+ const u = held(unsealed);+ unsealed.sealRowDispatch({ token: u.token, epoch: u.epoch, rows: [SEALED[0]] });+ assert.equal(codeOf(() => unsealed.noteRowsNotStarted({ ...u, rows: SEALED })), CODES.requestMismatch);++ // Two requests sent, one refused: the other may have landed, so the attempt is kept.+ const two = open(dirOf());+ const t = held(two);+ two.sealRowDispatch({ token: t.token, epoch: t.epoch, rows: [SEALED[0]] });+ two.sealRowDispatch({ token: t.token, epoch: t.epoch, rows: [SEALED[1]] });+ two.noteRowsNotStarted({ ...t, rows: [SEALED[1]] });+ assert.equal(codeOf(() => two.retireProvenUnsentAttempt(t)), CODES.pending, 'the root request may have landed');++ const store = open(dirOf());+ const h = held(store);+ store.sealRowDispatch({ token: h.token, epoch: h.epoch, rows: SEALED });+ store.noteRowsNotStarted({ ...h, rows: SEALED });+ const p = store.readGroup('customApi', API_KEY).pending;+ assert.deepEqual(p.rowProtocol.rows.map((r) => [r.dispatched, r.sentSha256]), [[false, null], [false, null]]);+ assert.deepEqual([p.sendWindow.possible, p.sendWindow.notStarted], [0, 1]);+ assert.ok(codeOf(() => store.noteRowsNotStarted({ ...h, rows: SEALED })), 'one refusal is counted once');+ assert.deepEqual(store.retireProvenUnsentAttempt(h), { retired: true, effects: 0 });+ assert.ok(!store.readGroup('customApi', API_KEY).pending);+});++test('abandonAttempt stops tracking exactly the named configuration attempt, in any phase, and keeps every committed group', () => {+ const store = open(dirOf());+ const [{ token, epoch }] = sending(store);+ store.sealRowDispatch({ token, epoch, rows: SEALED });+ const before = text(store);+ assert.equal(codeOf(() => store.abandonAttempt({ token, family: 'customApi', key: 'contoso_other' })), CODES.notSettled, 'another key');+ assert.equal(codeOf(() => store.abandonAttempt({ token, family: 'environmentVariable', key: API_KEY })), CODES.notSettled, 'another family');+ assert.ok(codeOf(() => store.abandonAttempt({ token: crypto.randomUUID(), family: 'customApi', key: API_KEY })), 'an attempt the store does not hold');+ assert.equal(codeOf(() => store.abandonAttempt({ family: 'customApi', key: API_KEY })), CODES.notSettled, 'no token');+ assert.equal(text(store), before, 'a refusal writes nothing');+ assert.deepEqual(store.abandonAttempt({ token, family: 'customApi', key: API_KEY }), { retired: true, effects: 0 });+ assert.ok(!store.readGroup('customApi', API_KEY).pending, 'the possibly-sent attempt is no longer tracked');+ assert.throws(() => store.sealRowDispatch({ token, epoch, rows: [SEALED[0]] }), 'nothing more is sent under it');++ // A prepared attempt goes the same way; another family's committed group is untouched.+ const kept = open(dirOf());+ settleForm(kept);+ const groups = JSON.parse(text(kept)).groups;+ const [prepared] = kept.prepareAttemptSet([apiPlan()]);+ assert.equal(codeOf(() => kept.abandonAttempt({ token: prepared, family: 'form', key: API_KEY })), CODES.notSettled, 'only its own family');+ kept.abandonAttempt({ token: prepared, family: 'customApi', key: API_KEY });+ assert.ok(!kept.readGroup('customApi', API_KEY).pending);+ assert.deepEqual(JSON.parse(text(kept)).groups, groups, 'every committed group stays');+});+test('ownership is proved row by row: a root acknowledgement never mints a child, and a child adoption names it exactly', () => {const dir = dirOf();const store = open(dir);diff --git a/plugins/model-apps/scripts/tests/sdk-build-declared.test.js b/plugins/model-apps/scripts/tests/sdk-build-declared.test.jsindex 249856669..5dd219719 100644--- a/plugins/model-apps/scripts/tests/sdk-build-declared.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build-declared.test.js@@ -648,18 +648,19 @@ test('verify CLI still verifies a spec with two same-key declared views or chartassert.deepEqual([lenient.ok, lenient.warnings], [true, [sameKeyMessage('chart', 'By Kind')]]);});-test('the maker guidance states that declared views, and declared charts, need their own names on a table, and that a viewId pin does not count', () => {+test('the maker guidance states that declared charts, and declared views without their own keys, need their own names on a table, and that a viewId pin does not count', () => {// White space (line wrapping, a CRLF checkout) is not part of the rule.const read = (...parts) => fs.readFileSync(path.join(__dirname, '..', '..', ...parts), 'utf8').replace(/\s+/g, ' ');const reference = read('references', 'app-spec-schema-advanced.md');for (const rule of [- 'two declared views on one table need different names, and so do two declared charts',+ 'two declared charts on one table need different names',+ 'and so do two declared views unless each has its own `key`',"a chart's name is compared with its outer spaces trimmed",'it does not tell two same-named declared views apart','The same name on another table, or on a view and a chart, is fine.',]) assert.ok(reference.includes(rule), `the advanced reference says: ${rule}`);const skill = read('skills', 'app-builder', 'SKILL.md');- assert.ok(skill.includes('Two declared views on one table need different names, and so do two declared charts: a `viewId` pin does not tell them apart'), 'the skill says it too');+ assert.ok(skill.includes('Two declared charts on one table need different names, and so do two declared views unless each has its own `key`: a `viewId` pin does not tell them apart'), 'the skill says it too');});test('push preview: a declared view edit is not evaluated rather than previewed as unchanged; the apply writes it', async () => {diff --git a/plugins/model-apps/scripts/tests/verify-spec.test.js b/plugins/model-apps/scripts/tests/verify-spec.test.jsindex f85723778..fe5789922 100644--- a/plugins/model-apps/scripts/tests/verify-spec.test.js+++ b/plugins/model-apps/scripts/tests/verify-spec.test.js@@ -4038,4 +4038,60 @@ test('verifySpec charts: a declared chart with a managed binding is its bound ro// A legacy chart is found by its name, whatever the manifest holds.const legacy = await verifySpec(chartSpec({}), chartReader([chartRow()]), { managedManifest: manifest() });assert.ok(legacy.checks.some((c) => c.kind === 'chart' && c.present));+});++// A binding store that cannot be read holds no group, so every declared artifact would look unbound and be found by its name. A+// declared dashboard, business rule and process flow are then unresolved, as declared views and charts are: a namesake never passes.+test('verifySpec: an unreadable binding store, or an unusable group record, never lets a namesake pass for a declared dashboard, business rule or process flow', async () => {+ const NAMESAKE = '77777777-7777-4777-8777-777777777777';+ const store = { family: 'store', key: 'managed-bindings', reason: 'not valid JSON', code: 'managed-binding-store-unreadable' };+ const manifest = (invalid) => ({ revision: 0, groups: [], pending: [], invalid });+ const filters = [];+ // Every name read answers one Active row of that name: the namesake a name fallback would take.+ const read = {+ findTable: async () => null,+ findColumns: async () => [],+ sitemapXml: async () => '',+ queryRecords: async (set, q) => {+ filters.push(`${set}: ${(q && q.filter) || ''}`);+ if (set === 'systemform') return [{ formid: NAMESAKE, name: 'Twin' }];+ if (set === 'workflow') return [{ workflowid: NAMESAKE, statecode: 1 }];+ return [];+ },+ };+ const spec = (reconcile) => ({+ solution: { uniqueName: 's', publisherPrefix: 'new' }, app: { name: 'A' }, entities: [],+ dashboards: [{ name: 'Twin', ...reconcile }],+ businessRules: [{ name: 'Twin', entity: 'new_ticket', ...reconcile }],+ businessProcessFlows: [{ name: 'Twin', entity: 'new_ticket', ...reconcile }],+ });+ const namesOf = (r) => r.checks.filter((c) => ['dashboard', 'business-rule', 'business-process-flow'].includes(c.kind)).map((c) => [c.kind, c.present]);+ const nameReads = () => filters.filter((f) => /^(systemform|workflow): .*\bname eq\b/.test(f));+ for (const [what, invalid, why] of [+ ['an unreadable store', [store], 'managed-binding-store-unreadable'],+ ['an unusable group record', [+ { family: 'dashboard', key: 'twin', reason: 'its record is not usable' },+ { family: 'rule', key: 'new_ticket/Twin', reason: 'its record is not usable' },+ { family: 'bpf', key: 'new_ticket/Twin', reason: 'its record is not usable' },+ ], 'its record is not usable'],+ ]) {+ filters.length = 0;+ const r = await verifySpec(spec({ reconcile: 'declared' }), read, { managedManifest: manifest(invalid) });+ // The dashboard keeps its check, failed with the reason (as a pending one does); the workflows are unverified, never a pass.+ assert.deepStrictEqual(namesOf(r), [['dashboard', false]], `${what}: ${JSON.stringify(r.checks)}`);+ assert.strictEqual(r.checks.find((c) => c.kind === 'dashboard').detail, `its managed binding (twin) is not settled (${why}) — unverified, not proven correct`);+ for (const kind of ['business-rule', 'business-process-flow']) {+ assert.ok(r.unverified.includes(`${kind}:new_ticket.Twin (its managed binding (new_ticket/Twin) is not settled (${why}) — unverified, not proven correct)`), `${what}: ${JSON.stringify(r.unverified)}`);+ }+ assert.deepStrictEqual(nameReads(), [], `${what}: never read by name`);+ assert.strictEqual(r.ok, false);+ }+ // Controls: a legacy dashboard, rule and flow are found by their names whatever the store holds, and a declared one with no store+ // entry at all (nothing bound yet) keeps its name lookup as before.+ for (const [reconcile, m] of [[{}, manifest([store])], [{ reconcile: 'declared' }, manifest([])]]) {+ filters.length = 0;+ const r = await verifySpec(spec(reconcile), read, { managedManifest: m });+ assert.deepStrictEqual(namesOf(r), [['dashboard', true], ['business-rule', true], ['business-process-flow', true]], JSON.stringify(r.checks));+ assert.strictEqual(nameReads().length, 3);+ }});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/workspace-configuration-memory.test.js b/plugins/model-apps/scripts/tests/workspace-configuration-memory.test.jsnew file mode 100644index 000000000..45ba3305b--- /dev/null+++ b/plugins/model-apps/scripts/tests/workspace-configuration-memory.test.js@@ -0,0 +1,548 @@+'use strict';+// No environment-variable value, default, value schema, secret reference or connection id at rest in any SDK workspace (#846, #847):+// the SDK's copies of those two kinds live in memory (lib/workspace-configuration-memory.js, applied to every SDK lib/maker-sdk.js+// makes). Proved at the storage boundary with synthetic canaries — every value the build is given is a unique marker — by scanning+// every workspace file the build command made: at the moment each configuration request is sent, after a successful build with its+// own --verify (which reads every item back into the app folder's durable workspace), after a refused create, after a halt, after+// a process killed between two steps, and after a direct build of a connection reference. The only files allowed to hold a canary+// are the maker's own inputs: the App Spec (which declares the defaults and the value schema) and the settings file.+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { fork, spawn } = require('node:child_process');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { runCommand } = require('./helpers/configuration-command.js');+const { createConfigOrg } = require('./helpers/fake-config-org.js');+const { createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdk.js');+const { keepSensitiveConfigurationInMemory } = require('../lib/workspace-configuration-memory.js');+const { hasUnsyncedEdits } = require('../lib/unsynced-edits.js');+// The SDK as an earlier plugin version made it: the bundle with no overlay, so its copies land on disk (as 2.26's verify left them).+const bundle = require('../vendor/cds-maker-sdk.cjs');+const { createAzHttpClient } = require('../lib/sdk-http-client.js');+const { configurationSendOnce } = require('../lib/configuration-transport.js');+const { readDeploymentBindings } = require('../lib/configuration-artifacts.js');+const { buildModelApp } = require('../build-model-app.js');+const { STAGES } = require('../lib/stages.js');++const SOLUTION = 'ContosoSol';+const SP = '/providers/Microsoft.PowerApps/apis/shared_sharepointonline';+const CANARY = {+ value: 'canary-value-4c1d',+ siteValue: 'canary-site-3a9d',+ default: 'canary-default-8e2f',+ jsonDefault: 'canary-jsondefault-2b70',+ schema: 'canary-schema-5e1b',+ vault: 'canaryvault7d',+ connection: 'canary-conn-6f3e',+};+const KEY_VAULT = `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.KeyVault/vaults/${CANARY.vault}/secrets/apikey`;+const VARIABLES = [+ { schemaName: 'contoso_ApiBase', type: 'string', name: 'API base', defaultValue: `https://${CANARY.default}.contoso.example`, isRequired: true },+ { schemaName: 'contoso_Shape', type: 'json', defaultValue: `{"k":"${CANARY.jsonDefault}"}`, valueSchema: `{"type":"object","title":"${CANARY.schema}"}` },+ { schemaName: 'contoso_ApiKey', type: 'secret' },+ { schemaName: 'contoso_Site', type: 'dataSource', connectorId: SP, parameterKey: 'dataset' },+];+const SETTINGS = {+ EnvironmentVariables: [+ { SchemaName: 'contoso_ApiBase', Value: `https://${CANARY.value}.contoso.example` },+ { SchemaName: 'contoso_ApiKey', Value: KEY_VAULT },+ { SchemaName: 'contoso_Site', Value: `https://${CANARY.siteValue}.sharepoint.example/sites/a` },+ ],+};+const specOf = (extra = {}) => ({+ minimumPluginVersion: '2.25.0',+ solution: { uniqueName: SOLUTION, displayName: 'Contoso Sol', publisherPrefix: 'contoso' },+ app: { name: 'Config Probe', uniqueName: 'contoso_configprobe' },+ schemaVersion: 2,+ entities: [],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Links', subAreas: [{ url: 'https://contoso.example/help', title: 'Help' }] }] }] },+ environmentVariables: VARIABLES,+ ...extra,+});+const PROTECTED = { configurationIdentity: 'stable-v1' };+// The maker's own inputs, which hold what the maker wrote there: the App Spec declares the defaults and the value schema.+const INPUTS = new Set(['app-spec.json', 'settings.json']);+const CONFIGURATION_WRITE = /^\/(environmentvariable|connectionreference)/i;++const walk = (dir) => (fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : [path.join(dir, e.name)])) : []);+// Every file under `dirs` (an input excepted) that holds a canary, as `<file>: <canary names>`.+function canariesIn(dirs) {+ const found = [];+ for (const dir of dirs) {+ for (const file of walk(dir)) {+ if (INPUTS.has(path.basename(file))) continue;+ let text;+ try { text = fs.readFileSync(file, 'latin1'); } catch { continue; }+ const hits = Object.entries(CANARY).filter(([, c]) => text.includes(c)).map(([k]) => k);+ if (hits.length) found.push(`${path.relative(dir, file)}: ${hits.join(',')}`);+ }+ }+ return found;+}++function settingsFile(settings = SETTINGS) {+ const file = path.join(makeTempDir('ws-cfg-settings-'), 'settings.json');+ fs.writeFileSync(file, JSON.stringify(settings));+ return file;+}++// The build command over the strict org with the canary settings; every SDK workspace folder it makes is collected, and each+// configuration write is preceded by a scan of all of them (`atSend`).+async function command(spec, { org, appDir = path.join(makeTempDir('ws-cfg-'), 'app'), argv = [], settings = SETTINGS, refuse } = {}) {+ const dirs = [];+ const atSend = [];+ const scan = () => canariesIn([...dirs, appDir]);+ org = org || createConfigOrg({+ solution: { uniqueName: SOLUTION, version: '1.0.0.0', prefix: 'contoso' },+ intercept: (req) => {+ if (req.method === 'GET' || !CONFIGURATION_WRITE.test(req.path)) return undefined;+ atSend.push(...scan().map((hit) => `${req.method} ${req.path.split('?')[0]} -> ${hit}`));+ return refuse ? refuse(req) : undefined;+ },+ });+ const out = await runCommand(spec, {+ org, appDir, onStorage: (dir) => dirs.push(dir),+ argv: ['--stage', 'data', '--allow-destructive', '--deployment-settings', settingsFile(settings), ...argv],+ });+ return { ...out, org, appDir, dirs, atSend, scan };+}++// Copies an earlier plugin version left: its verify fetched each configuration item into the app folder's workspace with the SDK+// as it made it (no overlay), so the artifact and its last-synced snapshot are files. Answers that SDK and the ids it fetched.+const LEGACY_CODE = 'WORKSPACE_LEGACY_CONFIGURATION_COPY';+const httpOf = (org) => createAzHttpClient(org.origin, { getToken: () => 'test-token-0123456789abcdef', request: (req) => org.request(req), sleep: async () => {} });+async function earlierVersionFetched(org, ws) {+ const sdk = bundle.createMakerSdk({ workspaceStorage: bundle.createNodeWorkspaceStorage(ws), instanceUrl: org.origin, httpClient: httpOf(org) });+ await sdk.initWorkspace();+ const ids = org.rows('environmentvariabledefinitions').map((r) => r.environmentvariabledefinitionid);+ for (const id of ids) await sdk.fetchArtifact('environmentVariable', id, { overwrite: true });+ return { sdk, ids };+}+// Every file under the two sensitive folders (and their metadata folders) of `ws`, relative path → bytes (hex).+function sensitiveFiles(ws) {+ const out = {};+ for (const rel of ['environment-variables', 'connection-references', '.metadata/environment-variables', '.metadata/connection-references']) {+ for (const file of walk(path.join(ws, rel))) out[path.relative(ws, file).split(path.sep).join('/')] = fs.readFileSync(file).toString('hex');+ }+ return out;+}+// What this process writes to its real stderr while `fn` runs (lib/maker-sdk.js warns there, outside the CLI harness's own stderr).+async function withStderr(fn) {+ const write = process.stderr.write;+ const got = [];+ process.stderr.write = function capture(chunk) { got.push(String(chunk)); return true; };+ try {+ const result = await fn();+ return { result, text: got.join('') };+ } finally {+ process.stderr.write = write;+ }+}++test('a protected build with --verify leaves no value, default, schema or secret reference in any workspace file, at any send or after it', async () => {+ const out = await command(specOf(PROTECTED), { argv: ['--verify'] });+ assert.equal(out.thrown, undefined, out.thrown && out.thrown.message);+ assert.ok(!out.exitCode, out.stderr.slice(-900));+ assert.ok(out.org.rows('environmentvariablevalues').length >= 3, 'the values were sent');+ assert.match(out.stderr, /verify/i);+ assert.ok(out.dirs.some((d) => path.resolve(d).startsWith(path.resolve(out.appDir))), 'the durable workspace was opened');+ assert.deepEqual(out.atSend, [], 'no canary in a workspace file when a configuration request is sent');+ assert.deepEqual(out.scan(), [], 'no canary in a workspace file after the build and its verify');+ // The rebuild over the same app folder makes the same decision as before: nothing to write, verify reading every item back.+ const mark = out.org.requests.length;+ const again = await command(specOf(PROTECTED), { org: out.org, appDir: out.appDir, argv: ['--verify'] });+ assert.equal(again.thrown, undefined, again.thrown && again.thrown.message);+ assert.ok(!again.exitCode, again.stderr.slice(-900));+ assert.deepEqual(out.org.writes(mark), [], 'an unchanged rebuild writes nothing');+ assert.deepEqual(again.scan(), []);+ assert.deepEqual(out.org.unexpected, []);+});++test('a protected secret create the service refuses leaves no reference in any workspace file, at the send or after the halt', async () => {+ const out = await command(specOf({ ...PROTECTED, environmentVariables: [{ schemaName: 'contoso_ApiKey', type: 'secret' }] }), {+ settings: { EnvironmentVariables: [{ SchemaName: 'contoso_ApiKey', Value: KEY_VAULT }] },+ refuse: (req) => (req.method === 'POST' && req.path.split('?')[0] === '/environmentvariabledefinitions'+ ? { statusCode: 400, body: { error: { code: '0x80072040', message: 'the value is not a usable secret reference' } } } : undefined),+ });+ assert.ok(out.thrown && /create-refused/.test(out.thrown.message), out.thrown ? out.thrown.message : out.stderr.slice(-900));+ assert.ok(out.atSend.length === 0, `no copy at the send: ${out.atSend}`);+ assert.deepEqual(out.scan(), []);+ assert.ok(!JSON.stringify([out.payload, out.stderr, String(out.thrown && out.thrown.message)]).includes(CANARY.vault));+});++test('an unprotected build halted after its values were sent leaves none of them in any workspace file', async () => {+ // The secret's value write fails: the step halts after the other variables and their values were written.+ const out = await command(specOf(), {+ refuse: (req) => (req.method === 'POST' && req.path.split('?')[0] === '/environmentvariablevalues' && JSON.stringify(req.body || {}).includes(CANARY.vault)+ ? { statusCode: 500, body: { error: { code: '0x80040216', message: 'An unexpected error occurred.' } } } : undefined),+ });+ assert.ok(out.thrown || out.exitCode, 'the build halted');+ assert.ok(out.org.rows('environmentvariabledefinitions').length >= 1, 'something was written before the halt');+ assert.deepEqual(out.atSend, []);+ assert.deepEqual(out.scan(), []);+});++// The copies an earlier version's verify left (real SDK files: each artifact and its snapshot). They are proven to be what+// the environment last held, so they are not used as configuration and change no decision; they are neither rewritten nor deleted (this version+// never deletes a file it did not write); the build says, once and without any of their content, which folders hold them.+test('copies an earlier version\u2019s verify left in the app folder\u2019s workspace are never used as configuration or deleted: an ordinary apply makes the same decisions, keeps them byte for byte and warns once naming their folders, never their content', async () => {+ const appDir = path.join(makeTempDir('ws-cfg-legacy-'), 'app');+ const ws = path.join(appDir, '.maker-workspace');+ const first = await command(specOf(PROTECTED), { appDir });+ assert.equal(first.thrown, undefined, first.thrown && first.thrown.message);+ await earlierVersionFetched(first.org, ws);+ const before = sensitiveFiles(ws);+ assert.ok(Object.keys(before).length >= 8, Object.keys(before).join(' '));+ assert.ok(canariesIn([ws]).length > 0, 'the earlier version wrote values to disk');+ const mark = first.org.requests.length;+ const runs = await withStderr(async () => {+ const dry = await runCommand(specOf(PROTECTED), { org: first.org, appDir, apply: false, argv: ['--stage', 'data', '--allow-destructive'] });+ assert.ok(!dry.exitCode, dry.stderr.slice(-900));+ assert.deepEqual(sensitiveFiles(ws), before, 'a dry run leaves the folder as it is');+ const again = await command(specOf(PROTECTED), { org: first.org, appDir });+ assert.equal(again.thrown, undefined, again.thrown && again.thrown.message);+ assert.ok(!again.exitCode, again.stderr.slice(-900));+ return again;+ });+ assert.deepEqual(first.org.writes(mark), [], 'the copies changed no decision: an unchanged rebuild writes nothing');+ assert.deepEqual(sensitiveFiles(ws), before, 'an ordinary apply neither rewrites nor deletes them');+ const warnings = runs.text.split('\n').filter((l) => l.includes('still holds environment-variable or connection-reference copies'));+ assert.equal(warnings.length, 1, runs.text.slice(-1500));+ assert.ok(warnings[0].includes(ws), warnings[0]);+ assert.match(warnings[0], /environment-variables, \.metadata\/environment-variables/);+ assert.ok(!Object.values(CANARY).some((c) => runs.text.includes(c)), 'the warning quotes no content');+ // Its verify reads every item back over them: still the same decisions, and still the same files.+ const verified = await command(specOf(PROTECTED), { org: first.org, appDir, argv: ['--verify'] });+ assert.equal(verified.thrown, undefined, verified.thrown && verified.thrown.message);+ assert.ok(!verified.exitCode, verified.stderr.slice(-900));+ assert.deepEqual(first.org.writes(mark), []);+ assert.deepEqual(sensitiveFiles(ws), before);+ assert.deepEqual(first.org.unexpected, []);+});++// An edit an earlier version's SDK made and never sent. The SDK used to report it as a change; hiding it would read as clean.+test('a draft an earlier version left is never hidden or deleted: the SDK\u2019s first touch of it is refused, naming its files and quoting none of its content, and the run goes on once the maker removes it', async () => {+ const DRAFT = 'canary-draft-91c4';+ const first = await command(specOf());+ assert.equal(first.thrown, undefined, first.thrown && first.thrown.message);+ const ws = makeTempDir('ws-cfg-draft-');+ const earlier = await earlierVersionFetched(first.org, ws);+ const [draftId, otherId] = earlier.ids;+ await earlier.sdk.updateElement('environmentVariable', draftId, '/defaultValue', DRAFT);+ assert.equal(await hasUnsyncedEdits(earlier.sdk, 'environmentVariable', draftId), true, 'the earlier version reports the draft');+ fs.rmSync(path.join(ws, 'environment-variables', `${otherId}.json`));+ fs.rmSync(path.join(ws, '.metadata', 'environment-variables', `${otherId}.meta.json`));+ const before = sensitiveFiles(ws);++ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(ws), instanceUrl: first.org.origin, httpClient: httpOf(first.org) });+ await sdk.initWorkspace();+ assert.equal(await hasUnsyncedEdits(sdk, 'environmentVariable', draftId), true, 'the draft still reads as a change, never as clean');+ const refused = await sdk.diffArtifact('environmentVariable', draftId).then(() => null, (e) => e);+ assert.ok(refused, 'the first touch of the draft is refused');+ assert.equal(refused.code, LEGACY_CODE, refused.message);+ assert.ok(refused.message.includes(path.join(ws, 'environment-variables', `${draftId}.json`)), refused.message);+ assert.match(refused.message, /differs from its last-synced snapshot/);+ assert.ok(!refused.message.includes(DRAFT) && !Object.values(CANARY).some((c) => refused.message.includes(c)), 'no content is quoted');+ await assert.rejects(sdk.fetchArtifact('environmentVariable', draftId, { overwrite: true }), { code: LEGACY_CODE }, 'not even an overwrite replaces it');+ // Another item is untouched by it: fetched into memory, and the draft is still there byte for byte.+ assert.equal((await sdk.fetchArtifact('environmentVariable', otherId, { overwrite: true })).id, otherId);+ assert.deepEqual(sensitiveFiles(ws), before, 'nothing on disk was deleted or rewritten');+ // The maker removes the two files (after moving the change to the App Spec): the run goes on, with nothing left on disk.+ fs.rmSync(path.join(ws, 'environment-variables', `${draftId}.json`));+ fs.rmSync(path.join(ws, '.metadata', 'environment-variables', `${draftId}.meta.json`));+ assert.equal((await sdk.fetchArtifact('environmentVariable', draftId, { overwrite: true })).id, draftId);+ assert.deepEqual((await sdk.diffArtifact('environmentVariable', draftId)).changes, []);+ // Only the maker's deletion removed anything: the other clean copies are still there byte for byte, and nothing was written.+ const kept = { ...before };+ delete kept[`environment-variables/${draftId}.json`];+ delete kept[`.metadata/environment-variables/${draftId}.meta.json`];+ assert.deepEqual(sensitiveFiles(ws), kept);+});++// Through the command: the build's own verify meets such a draft in the app folder.+test('a build whose verify meets a draft an earlier version left stops with the refusal and keeps the draft; once the maker deletes it, the rebuild verifies', async () => {+ const appDir = path.join(makeTempDir('ws-cfg-draft-cli-'), 'app');+ const ws = path.join(appDir, '.maker-workspace');+ const first = await command(specOf(PROTECTED), { appDir });+ assert.equal(first.thrown, undefined, first.thrown && first.thrown.message);+ const earlier = await earlierVersionFetched(first.org, ws);+ const id = first.org.rows('environmentvariabledefinitions').find((r) => r.schemaname === 'contoso_ApiBase').environmentvariabledefinitionid;+ await earlier.sdk.updateElement('environmentVariable', id, '/defaultValue', 'canary-draft-0d2e');+ const before = sensitiveFiles(ws);+ const mark = first.org.requests.length;+ const stopped = await command(specOf(PROTECTED), { org: first.org, appDir, argv: ['--verify'] });+ const said = `${stopped.thrown ? stopped.thrown.message : ''}\n${stopped.stderr}\n${JSON.stringify(stopped.payload || {})}`;+ assert.ok(stopped.thrown || stopped.exitCode, 'the build does not pass over the draft');+ assert.ok(said.includes(LEGACY_CODE) || said.includes('an earlier plugin version wrote'), said.slice(-1500));+ assert.ok(!said.includes('canary-draft-0d2e'));+ assert.deepEqual(first.org.writes(mark), [], 'nothing was sent');+ assert.deepEqual(sensitiveFiles(ws), before, 'the draft is kept');+ fs.rmSync(path.join(ws, 'environment-variables', `${id}.json`));+ fs.rmSync(path.join(ws, '.metadata', 'environment-variables', `${id}.meta.json`));+ const again = await command(specOf(PROTECTED), { org: first.org, appDir, argv: ['--verify'] });+ assert.equal(again.thrown, undefined, again.thrown && again.thrown.message);+ assert.ok(!again.exitCode, again.stderr.slice(-900));+ assert.deepEqual(first.org.writes(mark), []);+});++// A --workspace: the build's configuration step works in its own throwaway workspace, so a draft an earlier+// version left in a --workspace is never read by it: an ordinary apply keeps it byte for byte (it used to be removed at the+// first write) and the build names its folder in the warning, never its content.+test('a build over a --workspace holding a draft an earlier version left keeps the draft byte for byte, sends nothing and names its folder', async () => {+ const ws = makeTempDir('ws-cfg-draft-ws-');+ const first = await command(specOf(PROTECTED), { argv: ['--workspace', ws] });+ assert.equal(first.thrown, undefined, first.thrown && first.thrown.message);+ const earlier = await earlierVersionFetched(first.org, ws);+ const id = first.org.rows('environmentvariabledefinitions').find((r) => r.schemaname === 'contoso_ApiBase').environmentvariabledefinitionid;+ await earlier.sdk.updateElement('environmentVariable', id, '/defaultValue', 'canary-draft-5be1');+ const before = sensitiveFiles(ws);+ const mark = first.org.requests.length;+ const run = await withStderr(() => command(specOf(PROTECTED), { org: first.org, argv: ['--workspace', ws] }));+ const again = run.result;+ assert.equal(again.thrown, undefined, again.thrown && again.thrown.message);+ assert.ok(!again.exitCode, again.stderr.slice(-900));+ assert.deepEqual(first.org.writes(mark), [], 'nothing was sent');+ assert.deepEqual(sensitiveFiles(ws), before, 'the draft is kept');+ assert.ok(run.text.includes('still holds environment-variable or connection-reference copies') && run.text.includes(ws), run.text.slice(-1500));+ assert.ok(!run.text.includes('canary-draft-5be1') && !Object.values(CANARY).some((c) => run.text.includes(c)), 'the warning quotes no content');+});++// A caller-supplied workspace is no proof that everything under it is the plugin's.+test('a file of the maker\u2019s own in a sensitive folder of a --workspace with no manifest is kept by a build', async () => {+ const ws = makeTempDir('ws-cfg-notes-');+ const note = path.join(ws, 'environment-variables', 'author-notes.txt');+ fs.mkdirSync(path.dirname(note), { recursive: true });+ fs.writeFileSync(note, 'notes of the maker\'s own');+ const out = await command(specOf(PROTECTED), { argv: ['--workspace', ws] });+ assert.equal(out.thrown, undefined, out.thrown && out.thrown.message);+ assert.ok(!out.exitCode, out.stderr.slice(-900));+ assert.ok(out.dirs.some((d) => path.resolve(d) === path.resolve(ws)), 'the build opened that workspace');+ assert.equal(fs.readFileSync(note, 'utf8'), 'notes of the maker\'s own');+});++test('a direct build of a connection reference and variables keeps the connection id and every value out of the SDK workspace', async () => {+ const org = createConfigOrg({ solution: { uniqueName: SOLUTION, version: '1.0.0.0', prefix: 'contoso' } });+ const atSend = [];+ const sdkDir = makeTempDir('ws-cfg-direct-sdk-');+ const request = async (req) => {+ if (String(req.method).toUpperCase() !== 'GET' && /\/(environmentvariable|connectionreference)/i.test(String(req.url))) atSend.push(...canariesIn([sdkDir]));+ return org.request(req);+ };+ const httpClient = createAzHttpClient(org.origin, { getToken: () => 'test-token-0123456789abcdef', request, sleep: async () => {}, sendOnce: (m, u) => configurationSendOnce(m, u) });+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(sdkDir), instanceUrl: org.origin, httpClient, solutionUniqueName: SOLUTION });+ await sdk.initWorkspace();+ const spec = specOf({ connectionReferences: [{ logicalName: 'contoso_sp', connectorId: SP }] });+ const bindings = readDeploymentBindings({ ...SETTINGS, ConnectionReferences: [{ LogicalName: 'contoso_sp', ConnectionId: CANARY.connection }] }, spec);+ assert.deepEqual(bindings.errors, []);+ const r = await buildModelApp(spec, { apply: true, env: org.origin, phases: STAGES.data, workspaceDir: makeTempDir('ws-cfg-direct-ws-'), retryDelayMs: 0, configurationBindings: bindings },+ { sdk, log: () => {}, warn: () => {}, connections: async () => [{ connectionId: CANARY.connection, connectorId: SP }] });+ assert.equal(r.ok, true, JSON.stringify(r.errors));+ assert.equal(org.rows('connectionreferences')[0].connectionid, CANARY.connection, 'the connection was bound');+ // The SDK still reads its in-run copy back: the server's connection id is what fetchArtifact answers.+ const [ref] = org.rows('connectionreferences');+ assert.equal((await sdk.fetchArtifact('connectionReference', ref.connectionreferenceid, { overwrite: true })).connectionId, CANARY.connection);+ assert.deepEqual(atSend, []);+ assert.deepEqual(canariesIn([sdkDir]), []);+});++// The build command in a separate OS process, killed (SIGKILL: no cleanup runs) while its first configuration create is on the wire.+// Its throwaway SDK workspace is made under the test's own temporary folder (TEMP/TMP), which is scanned after the process is gone.+test('a build process killed while a configuration create is on the wire leaves no canary in any file it made', async () => {+ const root = makeTempDir('ws-cfg-crash-');+ const appDir = path.join(root, 'app');+ const env = { ...process.env, TEMP: root, TMP: root, TMPDIR: root, POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1' };+ delete env.NODE_TEST_CONTEXT;+ const org = createConfigOrg({ solution: { uniqueName: SOLUTION, version: '1.0.0.0', prefix: 'contoso' } });+ fs.mkdirSync(appDir, { recursive: true });+ const settings = path.join(root, 'settings.json');+ fs.writeFileSync(settings, JSON.stringify(SETTINGS));+ const atKill = await new Promise((resolve, reject) => {+ const child = fork(path.join(__dirname, 'helpers', 'configuration-command-child.js'), [], { cwd: path.join(__dirname, '..'), env, stdio: 'ignore' });+ let found = null;+ child.on('message', async (m) => {+ if (!m.request) return;+ const at = String(m.req.url).replace(/^https:\/\/[^/]+\/api\/data\/v9\.\d/, '');+ if (found === null && String(m.req.method).toUpperCase() === 'POST' && /^\/environmentvariablevalues/i.test(at)) {+ found = canariesIn([root]);+ child.kill('SIGKILL');+ return;+ }+ try { child.send({ reply: m.request, answer: await org.request(m.req) }); } catch { /* the child is gone */ }+ });+ child.on('error', reject);+ child.on('exit', () => (found === null ? reject(new Error('the process ended before its first value was sent')) : resolve(found)));+ child.send({ start: { origin: org.origin, spec: specOf(PROTECTED), appDir, argv: ['--stage', 'data', '--allow-destructive', '--deployment-settings', settings] } });+ });+ assert.ok(org.rows('environmentvariabledefinitions').length >= 1, 'a definition was created before the kill');+ assert.deepEqual(atKill, [], 'no canary in any file while the value create was on the wire');+ assert.deepEqual(canariesIn([root]), [], 'none in any file the killed process left behind');+});++// The overlay itself, over a real file-system storage.+test('the overlay keeps the two sensitive kinds in memory and every other key on disk, and deletes on disk only what the SDK asks', async () => {+ const dir = makeTempDir('ws-cfg-unit-');+ const storage = createNodeWorkspaceStorage(dir);+ const deletes = [];+ const deleteFile = storage.deleteFile.bind(storage);+ const deleteByPrefix = storage.deleteByPrefix.bind(storage);+ storage.deleteFile = (key) => { deletes.push(['file', key.join('/')]); return deleteFile(key); };+ storage.deleteByPrefix = (prefix) => { deletes.push(['prefix', prefix.join('/')]); return deleteByPrefix(prefix); };+ const o = keepSensitiveConfigurationInMemory(storage);+ assert.ok(o instanceof storage.constructor, 'instanceof holds');+ assert.equal(o.getRoot(), dir);+ assert.equal(o.pathFor(['views', 'v.json']), storage.pathFor(['views', 'v.json']));+ await o.writeTextAtomic(['environment-variables', 'a.json'], 'A');+ await o.writeTextAtomic(['.metadata', 'connection-references', 'b.meta.json'], 'B');+ await o.writeTextAtomic(['views', 'v.json'], 'V');+ assert.deepEqual(deletes, [], 'a write deletes nothing');+ assert.equal(await o.readText(['environment-variables', 'a.json']), 'A');+ assert.equal(await o.exists(['.metadata', 'connection-references', 'b.meta.json']), true);+ assert.equal(fs.readFileSync(path.join(dir, 'views', 'v.json'), 'utf8'), 'V', 'another kind stays on disk');+ assert.deepEqual(walk(dir).map((f) => path.relative(dir, f)), [path.join('views', 'v.json')]);+ await o.deleteByPrefix(['.metadata']);+ assert.equal(await o.readText(['.metadata', 'connection-references', 'b.meta.json']), null);+ await o.deleteFile(['environment-variables', 'a.json']);+ assert.equal(await o.readText(['environment-variables', 'a.json']), null);+ assert.deepEqual(deletes, [['prefix', '.metadata'], ['file', 'environment-variables/a.json']], 'only what the SDK asked');+ // A second wrapper (the next process) starts with nothing.+ await o.writeTextAtomic(['environment-variables', 'c.json'], 'C');+ assert.equal(await keepSensitiveConfigurationInMemory(storage).readText(['environment-variables', 'c.json']), null);+});++// A copy that cannot be read is not proven clean, so it is refused (never hidden, never recorded as checked), nothing is+// deleted, and the next access after the obstruction is gone checks it again and goes on.+const CLEAN = { id: 'e1', defaultValue: CANARY.default };+function plantCleanPair(dir, id = 'e1') {+ fs.mkdirSync(path.join(dir, 'environment-variables'), { recursive: true });+ fs.mkdirSync(path.join(dir, '.metadata', 'environment-variables'), { recursive: true });+ fs.writeFileSync(path.join(dir, 'environment-variables', `${id}.json`), JSON.stringify(CLEAN));+ fs.writeFileSync(path.join(dir, '.metadata', 'environment-variables', `${id}.meta.json`), JSON.stringify({ etag: 'W/"1"', snapshot: CLEAN }));+}++test('a copy an earlier version left that cannot be read is refused rather than hidden, nothing is deleted, and a retry once it can be read goes on', async () => {+ const dir = makeTempDir('ws-cfg-denied-');+ plantCleanPair(dir);+ const before = sensitiveFiles(dir);+ const storage = createNodeWorkspaceStorage(dir);+ let denied = true;+ const reads = [];+ const deletes = [];+ const readText = storage.readText.bind(storage);+ storage.readText = async (key) => {+ reads.push(key.join('/'));+ if (denied && key[key.length - 1].startsWith('e1.')) throw Object.assign(new Error('EPERM: operation not permitted, open'), { code: 'EPERM' });+ return readText(key);+ };+ storage.deleteFile = async (key) => { deletes.push(key.join('/')); };+ storage.deleteByPrefix = async (prefix) => { deletes.push(prefix.join('/')); };+ const o = keepSensitiveConfigurationInMemory(storage);+ for (const touch of [() => o.readText(['environment-variables', 'e1.json']), () => o.exists(['environment-variables', 'e1.json']), () => o.writeTextAtomic(['.metadata', 'environment-variables', 'e1.meta.json'], '{}')]) {+ const err = await touch().then(() => null, (e) => e);+ assert.ok(err, 'refused, not hidden');+ assert.equal(err.code, LEGACY_CODE);+ assert.match(err.message, /could not be read \(EPERM/);+ assert.ok(!err.message.includes(CANARY.default));+ }+ // An unrelated write goes on, and nothing is deleted on the way.+ await o.writeTextAtomic(['views', 'v.json'], 'V');+ await o.writeTextAtomic(['environment-variables', 'e2.json'], '{}');+ assert.deepEqual(deletes, []);+ assert.deepEqual(sensitiveFiles(dir), before);+ // The obstruction is removed: the refusal was not remembered, the copy is checked again, proven clean and from then on not read.+ denied = false;+ const readsBefore = reads.length;+ assert.equal(await o.readText(['environment-variables', 'e1.json']), null);+ assert.ok(reads.length > readsBefore, 'checked again');+ assert.equal(await o.exists(['environment-variables', 'e1.json']), false);+ assert.deepEqual(deletes, []);+ assert.deepEqual(sensitiveFiles(dir), before);+});++// The same on a real Windows lock: another program (a child PowerShell) holds the copy open with no sharing (FileShare.None).+// The child's whole life is bounded, so a misbehaving holder can never hang the suite: it must report the lock within+// HOLDER_READY_MS and exit within HOLDER_EXIT_MS of its release, or it is killed and the test fails with the reason. Its end is+// captured from the moment it is spawned: a holder that ends on its own after reporting the lock has already emitted `exit`, so+// a listener added only when the test releases it would wait for an event that is gone.+const HOLDER_READY_MS = 60000;+const HOLDER_EXIT_MS = 15000;+function withinMs(promise, ms, message) {+ let timer;+ const late = new Promise((resolve, reject) => { timer = setTimeout(() => reject(new Error(message)), ms); });+ return Promise.race([promise, late]).finally(() => clearTimeout(timer));+}+async function holdLocked(file) {+ const quoted = file.replace(/'/g, "''");+ const ps = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',+ `$f = [System.IO.File]::Open('${quoted}', 'Open', 'ReadWrite', 'None'); [Console]::Out.WriteLine('locked'); [Console]::Out.Flush(); [void][Console]::In.ReadLine(); $f.Close()`],+ { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });+ // A release written after the holder has gone fails with EPIPE on its stdin; `ended` already records that it has gone.+ ps.stdin.on('error', () => {});+ const ended = new Promise((resolve) => {+ ps.once('exit', (code, signal) => resolve(`exit ${code === null ? signal : code}`));+ ps.once('error', (error) => resolve(`spawn error: ${error.message}`));+ });+ const stop = async () => {+ if (ps.exitCode === null && ps.signalCode === null) ps.kill();+ await withinMs(ended, HOLDER_EXIT_MS, 'the lock holder did not end after it was killed').catch(() => {});+ };+ let out = '';+ const locked = new Promise((resolve, reject) => {+ ps.stdout.on('data', (d) => { out += d; if (out.includes('locked')) resolve(); });+ ended.then((how) => reject(new Error(`the lock holder ended before it held the file (${how})`)));+ });+ try {+ await withinMs(locked, HOLDER_READY_MS, `the lock holder did not report the lock within ${HOLDER_READY_MS} ms`);+ } catch (error) {+ await stop();+ throw error;+ }+ let releasing = null;+ const release = () => releasing || (releasing = (async () => {+ if (!ps.stdin.destroyed && !ps.stdin.writableEnded) ps.stdin.end('\n');+ try {+ await withinMs(ended, HOLDER_EXIT_MS, `the lock holder did not exit within ${HOLDER_EXIT_MS} ms of its release`);+ } catch (error) {+ await stop();+ throw error;+ }+ })());+ release.pid = ps.pid;+ release.ended = ended;+ return release;+}++test('the lock holder releases cleanly even when it ended on its own after holding the file (Windows)', { skip: process.platform !== 'win32' && 'a FileShare.None lock is a Windows file-system feature' }, async () => {+ const dir = makeTempDir('ws-cfg-holder-');+ const file = path.join(dir, 'held.json');+ fs.writeFileSync(file, '{}');+ const release = await holdLocked(file);+ process.kill(release.pid);+ // The holder's exit has been delivered before the test releases it: the release must still settle, and settle once.+ await release.ended;+ await withinMs(release(), HOLDER_EXIT_MS + 5000, 'the release of a holder that had already ended did not settle');+ await release();+ assert.equal(fs.readFileSync(file, 'utf8'), '{}');+});++test('a copy locked by another program is refused while locked and checked again once released (Windows)', { skip: process.platform !== 'win32' && 'a FileShare.None lock is a Windows file-system feature' }, async () => {+ const dir = makeTempDir('ws-cfg-locked-');+ plantCleanPair(dir);+ const before = sensitiveFiles(dir);+ const o = keepSensitiveConfigurationInMemory(createNodeWorkspaceStorage(dir), { refuse: (code, message) => new bundle.SdkError(code, message) });+ const release = await holdLocked(path.join(dir, 'environment-variables', 'e1.json'));+ let err;+ try {+ err = await o.readText(['environment-variables', 'e1.json']).then(() => null, (e) => e);+ await o.writeTextAtomic(['views', 'v.json'], 'V');+ } finally {+ await release();+ }+ assert.ok(err, 'refused while locked');+ assert.equal(err.code, LEGACY_CODE);+ assert.ok(err instanceof bundle.SdkError);+ assert.match(err.message, /could not be read/);+ assert.deepEqual(sensitiveFiles(dir), before, 'nothing deleted');+ assert.equal(await o.readText(['environment-variables', 'e1.json']), null, 'released: checked again and proven clean');+ assert.deepEqual(sensitiveFiles(dir), before);+});diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex 03ced4b73..158375a76 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -158,8 +158,8 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfacesone existing view or chart the maker asks to change: a rebuild then applies its columns, filters, sortand joins (`linkEntities`) instead of only adding columns. Never set `title` on a new declared chart,and give a declared view its own name — not the stock `Active <plural>` or `Inactive <plural>`, which- every table already has, so changing one is an adoption. Two declared views on one table need different- names, and so do two declared charts: a `viewId` pin does not tell them apart, and the build refuses the+ every table already has, so changing one is an adoption. Two declared charts on one table need different+ names, and so do two declared views unless each has its own `key`: a `viewId` pin does not tell them apart, and the build refuses thepair (see Approvals in the advanced reference).For a new table you create, propose `entities[].quickFind.findColumns` (the primary name plus what auser types in the search box: a number, an email, a code) and confirm it with the maker; on an@@ -720,9 +720,21 @@ gates the final *bulk* publish**, which also carries the edits made to existingWithout it those edits — and always an existing app's sitemap re-sync — still publish their onetargeted artifact so the change takes effect (see *Notes & limits*).+**Sensitive configuration in the workspace.** An earlier plugin version wrote environment-variable and+connection-reference copies (which can hold values, defaults, Key Vault secret references and connection ids) into+the workspace's `environment-variables` and `connection-references` folders and their `.metadata` folders. This+version never deletes them for you. While such files remain, every command that opens that workspace prints one+`WARNING:` naming the folders (never their content). A copy the plugin cannot prove is what the environment last+held (an edit never sent, a file with no partner, a locked file) stops the step that needs it with+`WORKSPACE_LEGACY_CONFIGURATION_COPY`, naming its two files. To clear either: when no build is running, move any+change you still want into the App Spec or the deployment settings file (the build sends configuration only from+those), close any program holding the files, delete the `.json` files in those folders, and run again. Tell the user+what the warning or the stop names before deleting anything.+**Recovery from a failed or halted build: run the full build again.** The build is idempotent — everyphase re-uses what's already created and only fills the gaps. SDK metadata is persisted under-`<working-dir>/.maker-workspace/` (override with `--workspace`). There is no apply-safe+`<working-dir>/.maker-workspace/` (override with `--workspace`); environment-variable and connection-reference values,+secret references and connection ids are never written there. There is no apply-safe`--from <phase>` shortcut; a full rerun is the correct and safe recovery path — after a `WEB_RESOURCE_UNVERIFIED`halt too: a web resource was written but its publication could not be confirmed (often because another customizationheld the environment's lock), the build recorded it, and a rerun using the **same writable workspace** writes itdiff --git a/plugins/pcf/CHANGELOG.md b/plugins/pcf/CHANGELOG.mdindex fb4e675d3..21cccefde 100644--- a/plugins/pcf/CHANGELOG.md+++ b/plugins/pcf/CHANGELOG.md@@ -33,3 +33,5 @@ First preview release: ships the `/pcf:pcf` skill, matrix-pinned templates and r- A `.ts` file with hundreds of `<Type>value` casts is now analyzed instead of being treated as unparseable, which had reported every Pages call in it as unguarded.- A local object literal named like the context, such as `const ctx = { device: { captureImage() { return 1; } } }`, is no longer mistaken for the PCF context when only its own simple functions are called.- The pcf evals report a case with nothing graded as unscored, not passed; exit status unchanged.+- New projects' dependency lock moves minimatch from 9.0.9 to 11.0.8 (GHSA-g3hv-75wg-m249).+- Generated projects find their Jest tests when the project path contains a dot-folder, and run only the tests in the project's `__tests__` folder (#849).diff --git a/plugins/pcf/lock/standard/package-lock.json b/plugins/pcf/lock/standard/package-lock.jsonindex e42a74e3e..44882abf6 100644--- a/plugins/pcf/lock/standard/package-lock.json+++ b/plugins/pcf/lock/standard/package-lock.json@@ -2167,6 +2167,12 @@"url": "https://github.com/sponsors/nzakas"}},+ "node_modules/@isaacs/nonrecursive-glob-match": {+ "version": "1.1.0",+ "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==",+ "dev": true,+ "license": "BlueOak-1.0.0"+ },"node_modules/@istanbuljs/load-nyc-config": {"version": "1.1.0","integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==",@@ -3571,25 +3577,38 @@"typescript": ">=4.8.4 <6.0.0"}},+ "node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": {+ "version": "4.0.4",+ "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "18 || 20 || >=22"+ }+ },"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {- "version": "2.1.7",- "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==",+ "version": "5.0.13",+ "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==","dev": true,"license": "MIT","dependencies": {- "balanced-match": "^1.0.0"+ "balanced-match": "^4.0.2"+ },+ "engines": {+ "node": "20 || >=22"}},"node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {- "version": "9.0.9",- "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",+ "version": "11.0.8",+ "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==","dev": true,- "license": "ISC",+ "license": "BlueOak-1.0.0","dependencies": {- "brace-expansion": "^2.0.2"+ "@isaacs/nonrecursive-glob-match": "^1.1.0",+ "brace-expansion": "^5.0.12"},"engines": {- "node": ">=16 || 14 >=14.17"+ "node": "20 || >=22"},"funding": {"url": "https://github.com/sponsors/isaacs"diff --git a/plugins/pcf/lock/standard/package.json b/plugins/pcf/lock/standard/package.jsonindex 4ff1cd8f1..565ceaf97 100644--- a/plugins/pcf/lock/standard/package.json+++ b/plugins/pcf/lock/standard/package.json@@ -33,6 +33,9 @@},"overrides": {"argparse": "2.0.1",- "source-map-js": "1.2.2"+ "source-map-js": "1.2.2",+ "@typescript-eslint/typescript-estree": {+ "minimatch": "11.0.8"+ }}}diff --git a/plugins/pcf/lock/virtual/package-lock.json b/plugins/pcf/lock/virtual/package-lock.jsonindex 552249c92..ea113fc67 100644--- a/plugins/pcf/lock/virtual/package-lock.json+++ b/plugins/pcf/lock/virtual/package-lock.json@@ -3680,6 +3680,12 @@"url": "https://github.com/sponsors/nzakas"}},+ "node_modules/@isaacs/nonrecursive-glob-match": {+ "version": "1.1.0",+ "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==",+ "dev": true,+ "license": "BlueOak-1.0.0"+ },"node_modules/@istanbuljs/load-nyc-config": {"version": "1.1.0","integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==",@@ -5111,25 +5117,38 @@"typescript": ">=4.8.4 <6.0.0"}},+ "node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": {+ "version": "4.0.4",+ "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "18 || 20 || >=22"+ }+ },"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {- "version": "2.1.7",- "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==",+ "version": "5.0.13",+ "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==","dev": true,"license": "MIT","dependencies": {- "balanced-match": "^1.0.0"+ "balanced-match": "^4.0.2"+ },+ "engines": {+ "node": "20 || >=22"}},"node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {- "version": "9.0.9",- "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",+ "version": "11.0.8",+ "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==","dev": true,- "license": "ISC",+ "license": "BlueOak-1.0.0","dependencies": {- "brace-expansion": "^2.0.2"+ "@isaacs/nonrecursive-glob-match": "^1.1.0",+ "brace-expansion": "^5.0.12"},"engines": {- "node": ">=16 || 14 >=14.17"+ "node": "20 || >=22"},"funding": {"url": "https://github.com/sponsors/isaacs"diff --git a/plugins/pcf/lock/virtual/package.json b/plugins/pcf/lock/virtual/package.jsonindex 3bc87cd25..a54c971d9 100644--- a/plugins/pcf/lock/virtual/package.json+++ b/plugins/pcf/lock/virtual/package.json@@ -41,6 +41,9 @@},"overrides": {"argparse": "2.0.1",- "source-map-js": "1.2.2"+ "source-map-js": "1.2.2",+ "@typescript-eslint/typescript-estree": {+ "minimatch": "11.0.8"+ }}}diff --git a/plugins/pcf/scripts/tests/pcf-matrix.test.js b/plugins/pcf/scripts/tests/pcf-matrix.test.jsindex 1e54a2676..dc844e25f 100644--- a/plugins/pcf/scripts/tests/pcf-matrix.test.js+++ b/plugins/pcf/scripts/tests/pcf-matrix.test.js@@ -226,6 +226,21 @@ test('lock package.json files pin exact versions only', () => {}});+test('lockfiles resolve no minimatch release affected by GHSA-g3hv-75wg-m249', () => {+ // The advisory covers minimatch >= 7.0.0 < 11.0.1 (the fix exists only in 11), while+ // @typescript-eslint/typescript-estree still asks for ^9 or ^10, so the lock package.json pins its+ // copy with an override. minimatch 3.x, used by eslint and jest, is outside the affected range.+ for (const set of ['standard', 'virtual']) {+ const lock = JSON.parse(fs.readFileSync(path.join(ROOT, 'lock', set, 'package-lock.json'), 'utf8'));+ const copies = Object.entries(lock.packages).filter(([key]) => /(^|\/)node_modules\/minimatch$/.test(key));+ assert.ok(copies.length > 0, `${set}: no minimatch in the lockfile`);+ for (const [key, entry] of copies) {+ const affected = m.compareVersions(entry.version, '7.0.0') >= 0 && m.compareVersions(entry.version, '11.0.1') < 0;+ assert.equal(affected, false, `${set}: ${key} is ${entry.version}`);+ }+ }+});+test('no file outside the matrix hard-codes a pcf-scripts version', () => {const offenders = [];const walk = (d) => {diff --git a/plugins/pcf/scripts/tests/pcf-scaffold.test.js b/plugins/pcf/scripts/tests/pcf-scaffold.test.jsindex 8991c7551..1b6890c21 100644--- a/plugins/pcf/scripts/tests/pcf-scaffold.test.js+++ b/plugins/pcf/scripts/tests/pcf-scaffold.test.js@@ -726,6 +726,59 @@ test('rendered Jest setup suppresses only the pinned jsdom punycode deprecation'assert.match(config, /test\/pcf-jest-environment\.cjs/);});+test('rendered Jest config finds only the project __tests__ tests, wherever the project is (#849)', () => {+ const source = findFile(renderFieldPlan(), 'jest.config.cjs');+ const loaded = { exports: {} };+ new Function('module', 'exports', source)(loaded, loaded.exports);+ const config = loaded.exports;++ // This suite installs nothing, so it replays Jest 29's own discovery steps on the rendered config:+ // 1. jest-config resolves each `roots` entry with `<rootDir>` replaced by the project path, and+ // the haste map crawls only those directories;+ // 2. SearchSource drops a path any testPathIgnorePatterns RegExp matches (default+ // ["/node_modules/"]; on Windows jest-config rewrites "/" in it to "\\");+ // 3. SearchSource keeps a path a testRegex RegExp matches, tested against the absolute path.+ // A testMatch glob would need Jest's glob engine to replay, and it is what broke #849: Jest pastes+ // the absolute path into a glob that starts with <rootDir>, and on Windows a backslash before a+ // dot survives as a glob escape, so "C:\work\.repo" matched nothing.+ assert.equal(config.testMatch, undefined, 'Jest rejects a config that sets both testMatch and testRegex');+ assert.equal(typeof config.testRegex, 'string', 'the test pattern must be a RegExp, which never contains the project path');+ assert.doesNotMatch(config.testRegex, /<rootDir>/);+ const files = [+ '__tests__/Source.test.ts',+ '__tests__/helpers/Nested.test.ts',+ '__tests__/helpers/fixture.ts',+ 'Source/index.test.ts',+ 'out/__tests__/Output.test.ts',+ 'obj/__tests__/Object.test.ts',+ 'generated/__tests__/Generated.test.ts',+ 'node_modules/sample/__tests__/Dependency.test.ts',+ '__tests__/node_modules/sample/Dependency.test.ts',+ ];+ const shapes = [+ { pathApi: path.posix, rootDir: '/work/project' },+ { pathApi: path.posix, rootDir: '/home/runner/.cache/work/project' },+ { pathApi: path.win32, rootDir: 'D:\\work\\project' },+ { pathApi: path.win32, rootDir: 'D:\\work\\.repo\\project' },+ ];+ for (const { pathApi, rootDir } of shapes) {+ const roots = (config.roots || ['<rootDir>']).map((root) => pathApi.resolve(rootDir, pathApi.normalize(`./${root.replace(/^<rootDir>/, '')}`)));+ const ignore = (config.testPathIgnorePatterns || ['/node_modules/']).map((pattern) => new RegExp(pathApi === path.win32 ? pattern.replace(/\//g, '\\\\') : pattern));+ const testRegex = new RegExp(config.testRegex);+ const found = files+ .map((rel) => pathApi.join(rootDir, ...rel.split('/')))+ .filter((file) => roots.some((root) => file.startsWith(root + pathApi.sep)))+ .filter((file) => !ignore.some((pattern) => pattern.test(file)))+ .filter((file) => testRegex.test(file))+ .map((file) => pathApi.relative(rootDir, file).split(pathApi.sep).join('/'));+ assert.deepEqual(found, ['__tests__/Source.test.ts', '__tests__/helpers/Nested.test.ts'], rootDir);+ }++ assert.equal(config.testEnvironment, '<rootDir>/test/pcf-jest-environment.cjs');+ assert.deepEqual(config.setupFiles, ['<rootDir>/test/jest-setup.js']);+ assert.deepEqual(config.transform, { '^.+\\.tsx?$': ['ts-jest', { tsconfig: 'tsconfig.test.json' }] });+});+test('mockDataSet renders first-class loading, error and paging options', () => {const kit = findFile(renderFieldPlan(), path.join('test', 'pcf-context.ts'));diff --git a/plugins/pcf/shared/jest.config.cjs.tmpl b/plugins/pcf/shared/jest.config.cjs.tmplindex 6c2e671af..9085dbb96 100644--- a/plugins/pcf/shared/jest.config.cjs.tmpl+++ b/plugins/pcf/shared/jest.config.cjs.tmpl@@ -3,7 +3,15 @@module.exports = {clearMocks: true,testEnvironment: "<rootDir>/test/pcf-jest-environment.cjs",- testMatch: ["<rootDir>/__tests__/**/*.test.ts"],+ // Tests live in __tests__ at the project root, and only there: build output (out, obj,+ // generated) and node_modules can hold copies of test files that must not run.+ // roots is a directory path, so <rootDir> is safe in it. A testMatch glob that starts with+ // <rootDir> is not (#849): Jest pastes the absolute project path into the glob and, on Windows,+ // keeps a backslash before a dot as a glob escape, so a project under C:\work\.repo\ becomes+ // "C:/work\.repo/..." and matches no file. testRegex is a plain RegExp tested against each path+ // under roots, so the project's location never enters the pattern.+ roots: ["<rootDir>/__tests__"],+ testRegex: "\\.test\\.ts$",moduleNameMapper: {"\\.(css|scss)$": "<rootDir>/test/styleMock.js",},