Skip to content

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.

27.7 KB
Raw Blame
'use strict';
// REAL-BUNDLE contract tests for `setAppAiFeatures` (ADO 6603383 / 6560699).
//
// The plugin's build engine branches on the SHAPE of this result — `applied` is the only success
// bucket, and `notPersisted` / `unverified` / `failed` each have to reach the user. Every other test
// of that branching drives a hand-written mock, so if a re-vendored SDK changed the bucket semantics
// the mocks would stay green while the real bundle behaved differently. That is exactly how the
// original false PASS shipped, so these drive the REAL vendored bundle over a fake httpClient and
// assert the semantics the engine relies on.
//
// The SDK's own Jest suite cannot run here (its `canvas` native module is built for the Node-20 ABI),
// which makes this the only executable check of the shipped bundle's behavior on this path.
const test = require('node:test');
const assert = require('node:assert');
const os = require('node:os');
const path = require('node:path');
const fs = require('node:fs');

const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');

const APP = 'co_supportdesk';
const APP_ID = '11111111-1111-1111-1111-111111111111';
// The PER-APP setting for formFill. It doubles as its own "gate" in the SDK's AI_GATE map — which is
// precisely why the SDK no longer reads it as one (AB#6688904): the row it would consult is the row
// the write is about to set, so on a new app the platform default `0` read as "the environment
// forbids this" and pre-empted every write.
const SETTING = 'FormFillBarUXEnabled';
const DEF_ID = '22222222-2222-2222-2222-222222222222';

const tempDirs = [];
test.after(() => { for (const d of tempDirs) fs.rmSync(d, { recursive: true, force: true }); });

/**
 * A real SDK over a fake Dataverse. `opts`:
 *   overrideRows  - value[] returned by the /appsettings proof query. A FUNCTION is called with the
 *                   1-based attempt number so a test can model eventual consistency (empty, then
 *                   the row appears). An array is returned verbatim every attempt.
 *   effective     - what RetrieveSetting reports at APP scope (the environment-fallback value).
 *   gate          - what RetrieveSetting reports at ORG scope (the readiness gate).
 *   failProof     - throw from the /appsettings query (models missing read access).
 *   failWrite     - throw from POST /SaveSettingValue.
 */
async function freshSdk(opts = {}) {
  const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ai-real-'));
  tempDirs.push(dir);
  const calls = [];
  let proofAttempts = 0;
  const httpClient = {
    get: async (url) => {
      calls.push({ method: 'GET', url });
      // /RetrieveSetting(SettingName='X')            -> ORG scope (the readiness gate)
      // /RetrieveSetting(SettingName='X',AppUniqueName='Y') -> APP scope (effective, may fall back)
      if (url.includes('/RetrieveSetting(')) {
        const scoped = url.includes('AppUniqueName=');
        const value = scoped ? opts.effective : opts.gate;
        return { status: 200, headers: {}, body: { SettingDetail: { Value: value, DataType: 0 } } };
      }
      if (url.includes('/appmodules')) {
        return { status: 200, headers: {}, body: { value: opts.noApp ? [] : [{ appmoduleid: APP_ID }] } };
      }
      if (url.includes('/settingdefinitions')) {
        return { status: 200, headers: {}, body: { value: [{ settingdefinitionid: DEF_ID }] } };
      }
      if (url.includes('/appsettings')) {
        proofAttempts += 1;
        if (opts.failProof) throw new Error('403 forbidden');
        const rows = typeof opts.overrideRows === 'function' ? opts.overrideRows(proofAttempts) : (opts.overrideRows || []);
        return { status: 200, headers: {}, body: { value: rows } };
      }
      return { status: 200, headers: {}, body: {} };
    },
    post: async (url, body) => {
      calls.push({ method: 'POST', url, body });
      if (url.includes('/SaveSettingValue') && opts.failWrite) throw new Error('boom from SaveSettingValue');
      return { status: 204, headers: {}, body: {} };
    },
    patch: async () => ({ status: 204, headers: {}, body: {} }),
    delete: async () => ({ status: 204, headers: {}, body: {} }),
    put: async () => ({ status: 204, headers: {}, body: {} }),
  };
  const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://example.crm.dynamics.com', httpClient });
  await sdk.initWorkspace();
  return { sdk, calls, proofCount: () => proofAttempts };
}
// `verifyDelayMs: 0` keeps the retry budget instant — the real default backs off up to ~3s.
const FAST = { verifyDelayMs: 0 };

test('REAL BUNDLE: a proven app-scope override row is the only thing that yields `applied`', async () => {
  const { sdk } = await freshSdk({ gate: '2', effective: '2', overrideRows: [{ value: '2' }] });
  const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);
  assert.deepStrictEqual(r.applied, ['formFill']);
  assert.deepStrictEqual([r.notPersisted, r.unverified, r.failed], [[], [], []]);
  assert.strictEqual(r.outcomes[0].appOverrideExists, true);
});

test('REAL BUNDLE: an ENV-fallback match with NO override row is notPersisted, not applied', async () => {
  // The false PASS the plugin's verify oracle also had to fix: RetrieveSetting at app scope returns
  // the ENVIRONMENT value, so the write reads back as requested while `appsettings` holds no row.
  // The whole point is that the app-scope read MATCHES the request while no override row exists —
  // that is what makes the env-fallback read look like success. So `effective` must be the value the
  // request resolves to ('2' = enabled for this family); stubbing '1' would mean the read disagrees
  // with the request anyway, and the test would pass for the wrong reason.
  const { sdk } = await freshSdk({ gate: '2', effective: '2', overrideRows: [] });
  const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);
  assert.deepStrictEqual(r.applied, [], 'an env-fallback read must never count as applied');
  assert.deepStrictEqual(r.notPersisted, ['formFill']);
  assert.strictEqual(r.outcomes[0].status, 'notPersisted');
});

test('REAL BUNDLE: a write that becomes visible late is retried and reported applied', async () => {
  // Eventual consistency: an immediate read can miss a write that DID land. Reporting that as failed
  // produced a false `notPersisted` on first apply (a re-run then looked clean).
  const { sdk, proofCount } = await freshSdk({ gate: '2', effective: '2', overrideRows: (n) => (n >= 3 ? [{ value: '2' }] : []) });
  const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);
  assert.deepStrictEqual(r.applied, ['formFill'], 'the retry budget must absorb read lag');
  assert.strictEqual(proofCount(), 3, 'stops as soon as the override is observed');
});

test('REAL BUNDLE: an unreadable override row is `unverified`, never applied and never notPersisted', async () => {
  // The ORG GATE and the PER-APP setting use different encodings, which is easy to conflate: the
  // per-app form-fill value is 0=platform default / 1=disabled / 2=enabled. The gate value no longer
  // decides whether this path is reached at all — since AB#6688904 the write and the proof always
  // run — so `gate` here is inert and `'2'` is used purely so a fixture for a `formFill: true`
  // request does not read as "disabled".
  const { sdk } = await freshSdk({ gate: '2', effective: '2', failProof: true });
  const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);
  assert.deepStrictEqual(r.unverified, ['formFill']);
  assert.deepStrictEqual([r.applied, r.notPersisted], [[], []]);
  assert.strictEqual(r.outcomes[0].appOverrideExists, undefined, 'no stale existence flag when we could not look');
});

test('REAL BUNDLE: a throwing write lands in `failed` and does not abort the batch', async () => {
  const { sdk } = await freshSdk({ gate: '2', effective: '2', failWrite: true });
  const r = await sdk.setAppAiFeatures(APP, { formFill: true, nlChart: true }, FAST);
  assert.deepStrictEqual(r.failed.sort(), ['formFill', 'nlChart'], 'every feature still reports');
  assert.deepStrictEqual(r.applied, []);
  assert.match(r.outcomes[0].reason, /boom from SaveSettingValue/);
});

// AB#6688904 rewrote this contract, and the two tests below are the new pinning pair. The OLD
// behaviour — "an org gate that is off yields `skipped` and issues NO write" — is exactly the defect:
// the gate was read as a PRECONDITION, and for four of the seven features that "gate" is the very row
// the write is about to set, so a brand-new app (value `0`, the platform default) looked forbidden and
// the build shipped an app with no AI features while reporting success.
//
// The new contract is: always write, then verify, and read a gate only to EXPLAIN an absence. So the
// bucket now depends on whether the feature HAS an independent gate, which is what these two separate.
test('REAL BUNDLE: a gate that is off no longer pre-empts the write — it is issued, then explained as `skipped`', async () => {
  // `nlSearch` has a genuinely distinct gate (`EnableNLGridSearch`) from its per-app setting
  // (`NLGridSearchSetting`), so a gate-off diagnosis is meaningful for it.
  const { sdk, calls } = await freshSdk({ gate: '0', effective: '0', overrideRows: [] });
  const r = await sdk.setAppAiFeatures(APP, { nlSearch: true }, FAST);
  assert.deepStrictEqual(r.skipped, ['nlSearch'], 'an absent override plus a gate reading off is `skipped`');
  const writes = calls.filter((c) => c.method === 'POST' && c.url.includes('SaveSettingValue'));
  assert.strictEqual(writes.length, 1, 'the write MUST be attempted — pre-empting it was the bug');
  // The engine defers `skipped` to its post-publish re-issue on the strength of this: the outcome is
  // evidence about one attempt, not a verdict that the app can never hold the setting.
  assert.strictEqual(r.outcomes[0].appOverrideExists, false, 'skipped now carries a real verification result');
});

test('REAL BUNDLE: a SELF-GATED feature has no gate to blame — an absent override is notPersisted, never skipped', async () => {
  // `formFill` reads `FormFillBarUXEnabled` for BOTH its gate and its per-app value. `0` there is the
  // platform default on a new app, not an admin saying no, so there is nothing to diagnose with and
  // the honest bucket is `notPersisted`. Reporting `skipped` here would re-tell the AB#6688904 story.
  const { sdk, calls } = await freshSdk({ gate: '0', effective: '0', overrideRows: [] });
  const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);
  assert.deepStrictEqual(r.skipped, [], 'a self-gated feature can never be `skipped`');
  assert.deepStrictEqual(r.notPersisted, ['formFill']);
  assert.strictEqual(calls.filter((c) => c.method === 'POST' && c.url.includes('SaveSettingValue')).length, 1);
});

test('REAL BUNDLE: disabling is never gated — it writes even when the org gate is off', async () => {
  const { sdk, calls } = await freshSdk({ gate: '0', effective: '1', overrideRows: [{ value: '1' }] });
  const r = await sdk.setAppAiFeatures(APP, { formFill: false }, FAST);
  assert.deepStrictEqual(r.applied, ['formFill'], 'an explicit disable must always be applied');
  const write = calls.find((c) => c.method === 'POST' && c.url.includes('SaveSettingValue'));
  assert.strictEqual(write.body.Value, '1', "'1' is DISABLED for this family; '0' would mean platform default");
});

test('REAL BUNDLE: an explicit integer value (2 = on for everyone) is written verbatim', async () => {
  // The plugin's spec schema allows this precisely because the SDK does; a boolean-only contract made
  // the platform's documented `2` inexpressible (ADO 6560699).
  const { sdk, calls } = await freshSdk({ gate: '2', effective: '2', overrideRows: [{ value: '2' }] });
  const r = await sdk.setAppAiFeatures(APP, { formFill: 2 }, FAST);
  assert.deepStrictEqual(r.applied, ['formFill']);
  assert.strictEqual(calls.find((c) => c.method === 'POST' && c.url.includes('SaveSettingValue')).body.Value, '2');
});

test('REAL BUNDLE: an out-of-range or non-numeric value throws BEFORE any write is issued', async () => {
  // The plugin's validateAppSpec bound mirrors this, so a spec never reaches a half-applied batch.
  for (const bad of [-1, 1.5, 1000001, 'off']) {
    const { sdk, calls } = await freshSdk({ gate: '1', effective: '1', overrideRows: [{ value: '1' }] });
    await assert.rejects(() => sdk.setAppAiFeatures(APP, { formFill: bad }, FAST), /must be a boolean or an integer/, `expected ${bad} to be rejected`);
    assert.strictEqual(calls.filter((c) => c.method === 'POST').length, 0, `no write may be issued for ${bad}`);
  }
});

test('REAL BUNDLE: an empty appUniqueName throws rather than writing at ORGANIZATION scope', async () => {
  // Silently omitting AppUniqueName changes the feature for the WHOLE environment. The plugin always
  // passes appUniqueName(spec), but this is the backstop that makes a regression there loud.
  const { sdk, calls } = await freshSdk({ gate: '1', effective: '1', overrideRows: [{ value: '1' }] });
  await assert.rejects(() => sdk.setAppAiFeatures('', { formFill: true }, FAST), /non-empty appUniqueName/);
  assert.strictEqual(calls.filter((c) => c.method === 'POST').length, 0);
});

test('REAL BUNDLE: the override proof is scoped to THIS app and THIS setting', async () => {
  // '2' (enabled), not '1' (disabled), for a `formFill: true` request — see the note above on the
  // gate vs per-app encodings. Measured to behave identically; this only removes the contradiction
  // between what the fixture says and what the request asks for.
  const { sdk, calls } = await freshSdk({ gate: '2', effective: '2', overrideRows: [{ value: '2' }] });
  await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);
  const proof = calls.find((c) => c.url.includes('/appsettings'));
  assert.ok(proof, 'the override row must actually be queried');
  // GUID lookup values are compared UNQUOTED in an OData $filter.
  assert.ok(proof.url.includes(`_parentappmoduleid_value%20eq%20${APP_ID}`) || proof.url.includes(`_parentappmoduleid_value eq ${APP_ID}`), `app not scoped: ${proof.url}`);
  assert.ok(proof.url.includes(DEF_ID), `setting not scoped: ${proof.url}`);
  // ...and the app id came from THIS app's unique name.
  assert.ok(calls.some((c) => c.url.includes('/appmodules') && c.url.includes(APP)), 'app module resolved by unique name');
});

// --- pre-publish verification via an explicitly supplied appModuleId -------------------------
// A freshly created appmodule is NOT readable until it is PUBLISHED: Dataverse omits it from list
// queries and 404s the by-id retrieve. Because verification proves the app-scope override ROW —
// which is keyed by appmoduleid — the by-NAME lookup is the single piece that fails pre-publish, so
// every feature landed in `unverified` even when the write succeeded. The build hits exactly this:
// its ai-features phase runs moments after app-shell created the app, long before publish.
// `appModuleId` skips that lookup; the `appsettings` proof query itself works fine before publish.

test('REAL BUNDLE: a supplied appModuleId proves the override PRE-PUBLISH (app not yet listable)', async () => {
  // `noApp: true` models the pre-publish reality: the by-name appmodule query returns NO rows.
  // Without appModuleId this is unverifiable; with it, the proof succeeds.
  const { sdk } = await freshSdk({ noApp: true, gate: '2', effective: '2', overrideRows: [{ value: '2' }] });
  const r = await sdk.setAppAiFeatures(APP, { formFill: true }, { ...FAST, appModuleId: APP_ID });
  assert.deepStrictEqual(r.applied, ['formFill'], `expected applied, got ${JSON.stringify(r)}`);
  assert.deepStrictEqual([r.notPersisted, r.unverified, r.failed], [[], [], []]);
  assert.strictEqual(r.outcomes[0].appOverrideExists, true);
});

test('REAL BUNDLE: WITHOUT appModuleId the same pre-publish app cannot be proven (regression witness)', async () => {
  // The behaviour the build worked around. Kept so a future SDK change that makes the by-name
  // lookup work pre-publish is noticed here rather than silently making the option pointless.
  const { sdk } = await freshSdk({ noApp: true, gate: '1', effective: '1', overrideRows: [{ value: '1' }] });
  const r = await sdk.setAppAiFeatures(APP, { formFill: true }, FAST);
  assert.deepStrictEqual(r.applied, [], `a pre-publish app must not be provable by name: ${JSON.stringify(r)}`);
  assert.ok(
    (r.unverified || []).includes('formFill') || (r.failed || []).includes('formFill'),
    `expected a non-success bucket, got ${JSON.stringify(r)}`
  );
});

test('REAL BUNDLE: a supplied appModuleId that DISAGREES with the published app is rejected, not trusted', async () => {
  // Fail-closed identity check: if the app IS readable by name and resolves to a different id, the
  // caller's id is stale/wrong and writing under it would configure the wrong app.
  const { sdk } = await freshSdk({ gate: '1', effective: '1', overrideRows: [{ value: '1' }] });
  await assert.rejects(
    () => sdk.setAppAiFeatures(APP, { formFill: true }, { ...FAST, appModuleId: '99999999-9999-9999-9999-999999999999' }),
    /INVALID_ARGUMENT|different|mismatch/i
  );
});

test('REAL BUNDLE: a malformed appModuleId is rejected up front', async () => {
  const { sdk } = await freshSdk({ gate: '1', effective: '1', overrideRows: [{ value: '1' }] });
  await assert.rejects(() => sdk.setAppAiFeatures(APP, { formFill: true }, { ...FAST, appModuleId: 'not-a-guid' }));
});

// The boolean spelling is NOT a flat 1/0, and the schema doc once said it was. That inaccuracy caused
// a real incident: `appFeatures: { nlSearch: false, nlChart: false }` was written believing it meant
// "leave alone", and it changed two features a live app was inheriting as on.
//
// Every per-app AI setting is a tri-state: most are 0 = Default, 1 = Off, 2 = On, while NL charts are
// 0 = Off, 1 = Auto, 2 = On (the platform's own settings UI). The vendored SDK's boolean mapping knows
// only the form-fill family, so `true` reached grid search and M365 as '1' — Off — and charts as
// '1' — Auto (AB#6714731). The build therefore encodes every flag itself (`encodeAiFlags`) and hands
// the SDK explicit values, which it writes verbatim.
//
// Pinned against the real bundle for every feature in BOTH directions, so a re-vendor that starts
// re-mapping explicit values fails here instead of silently writing the wrong state.
test('REAL BUNDLE: every feature\u2019s encoded On/Off value is written verbatim and proven', async () => {
  const { AI_APP_SETTING, AI_SETTING_CODEC, encodeAiFlags } = require('../lib/ai-app-settings.js');
  const features = Object.keys(AI_APP_SETTING);
  assert.deepStrictEqual(Object.keys(AI_SETTING_CODEC).sort(), [...features].sort(), 'every per-app setting has a codec entry');
  for (const feature of features) {
    for (const [flag, expected] of [[true, AI_SETTING_CODEC[feature].enabled], [false, AI_SETTING_CODEC[feature].disabled]]) {
      const encoded = encodeAiFlags({ [feature]: flag });
      assert.strictEqual(encoded[feature], expected, `${feature}=${flag}: encoded value`);
      const { sdk, calls } = await freshSdk({ gate: '2', effective: '2', overrideRows: [{ appsettingid: 'a1', value: expected }] });
      const r = await sdk.setAppAiFeatures(APP, encoded, { appModuleId: APP_ID, verifyAttempts: 1, verifyDelayMs: 1 });
      const save = calls.find((c) => c.method === 'POST' && /SaveSettingValue/i.test(c.url));
      assert.ok(save, `${feature}=${flag}: a SaveSettingValue must be issued`);
      assert.strictEqual(save.body.SettingName, AI_APP_SETTING[feature], `${feature}: setting name`);
      assert.strictEqual(String(save.body.Value), expected, `${feature}=${flag} must write ${expected}`);
      assert.deepStrictEqual(r.applied, [feature], `${feature}=${flag}: the SDK proves the override holding ${expected}`);
    }
  }
  // The absolute values, so an edit to the codec cannot drift unnoticed.
  assert.deepStrictEqual(encodeAiFlags({ formFill: true, nlSearch: true, nlChart: true, m365: true }), { formFill: '2', nlSearch: '2', nlChart: '2', m365: '2' });
  assert.deepStrictEqual(encodeAiFlags({ formFill: false, nlSearch: false, nlChart: false, m365: false }), { formFill: '1', nlSearch: '1', nlChart: '0', m365: '1' });
});

// Why the build encodes at all: the SDK's own boolean mapping, as vendored. If a re-vendor makes this
// fail because the SDK now maps these features correctly, delete this test — the build's own encoding
// stays correct, because an explicit value passes through verbatim.
test('REAL BUNDLE (known SDK gap): a raw boolean `true` still writes 1 for grid search, charts and M365', async () => {
  for (const [feature, setting] of [['nlSearch', 'NLGridSearchSetting'], ['nlChart', 'NLChartDataVisualizationSetting'], ['m365', 'm365copilotmodelappenabled']]) {
    const { sdk, calls } = await freshSdk({ gate: '2', effective: '2', overrideRows: [{ appsettingid: 'a1', value: '1' }] });
    await sdk.setAppAiFeatures(APP, { [feature]: true }, { appModuleId: APP_ID, verifyAttempts: 1, verifyDelayMs: 1 });
    const save = calls.find((c) => c.method === 'POST' && /SaveSettingValue/i.test(c.url));
    assert.strictEqual(save.body.SettingName, setting);
    assert.strictEqual(String(save.body.Value), '1', `${feature}: the SDK maps true to '1' (Off, or Auto for charts), which is why the build never passes it a boolean`);
  }
});

test('REAL BUNDLE: an encoded OFF that did not persist is not blamed on an org gate that governs turning it ON', async () => {
  // The same gap from the other side: the SDK reads any non-zero value as enabling, so an absent
  // override for grid search Off ('1') with its gate off comes back `skipped`, telling an admin to
  // enable the feature. The build re-buckets it before anything reads the result.
  const { encodeAiFlags, rebucketNonEnablingSkips } = require('../lib/ai-app-settings.js');
  const encoded = encodeAiFlags({ nlSearch: false });
  const { sdk } = await freshSdk({ gate: '0', effective: '0', overrideRows: [] });
  const r = await sdk.setAppAiFeatures(APP, encoded, FAST);
  assert.deepStrictEqual(r.skipped, ['nlSearch'], 'the SDK still labels it skipped (if this fails, the SDK gap closed)');
  rebucketNonEnablingSkips(r, encoded);
  assert.deepStrictEqual([r.skipped, r.notPersisted], [[], ['nlSearch']]);
  assert.strictEqual(r.outcomes[0].status, 'notPersisted');
  assert.doesNotMatch(r.outcomes[0].reason, /must enable/);
  assert.match(r.outcomes[0].reason, /holding '1'/);
  // An enabling request keeps the SDK's verdict and its admin-action reason.
  const on = encodeAiFlags({ nlSearch: true });
  const { sdk: sdk2 } = await freshSdk({ gate: '0', effective: '0', overrideRows: [] });
  const r2 = rebucketNonEnablingSkips(await sdk2.setAppAiFeatures(APP, on, FAST), on);
  assert.deepStrictEqual(r2.skipped, ['nlSearch']);
  assert.match(r2.outcomes[0].reason, /must enable/);
});

test('REAL BUNDLE: disabling is NOT gated — a false is written even when the org gate is off', async () => {
  // This asymmetry is why an incorrect `false` is the more damaging mistake: it always lands.
  const { sdk, calls } = await freshSdk({ gate: '0', effective: '0', overrideRows: [{ appsettingid: 'a1', value: '1' }] });
  await sdk.setAppAiFeatures(APP, { formFill: false }, { appModuleId: APP_ID, verifyAttempts: 1, verifyDelayMs: 1 });
  const save = calls.find((c) => c.method === 'POST' && /SaveSettingValue/i.test(c.url));
  assert.ok(save, 'a disable must be written even with the gate off');
  assert.strictEqual(String(save.body.Value), '1', 'and 1 means DISABLED, not platform default');
});

// --- an override that is saved but not yet published ---------------------------------------------------
// A write lands in the app's UNPUBLISHED layer (`componentstate` 1). The proof used to read only the published
// `appsettings` projection, so a feature on a freshly created app came back `notPersisted` and the build wrote it
// again after a publish. The bundle now reads the unpublished layer too and answers `applied` with
// `pendingPublish: true` — which the build must NOT count as in force (rebucketPendingPublish), or a build without
// `--publish` reports rows that no runtime serves and `--verify` (which reads the published layer) contradicts it.

test('REAL BUNDLE: an override still in the unpublished layer is `applied` with pendingPublish — and the proof reads that layer', async () => {
  const { sdk, calls } = await freshSdk({ gate: '2', effective: '2', overrideRows: [{ value: '2', componentstate: 1 }] });
  const r = await sdk.setAppAiFeatures(APP, { formFill: true }, { ...FAST, appModuleId: APP_ID });
  assert.deepStrictEqual(r.applied, ['formFill']);
  assert.strictEqual(r.outcomes[0].status, 'applied');
  assert.strictEqual(r.outcomes[0].pendingPublish, true, 'saved, taking effect when the app is published');
  const proof = calls.find((c) => c.method === 'GET' && c.url.includes('/appsettings'));
  assert.match(decodeURIComponent(proof.url), /appsettings\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublishedMultiple\(\)/, 'the proof reads the unpublished-aware function, not the published collection');
});

test('REAL BUNDLE: a row already in force carries no pendingPublish', async () => {
  for (const rows of [[{ value: '2', componentstate: 0 }], [{ value: '2' }]]) {
    const { sdk } = await freshSdk({ gate: '2', effective: '2', overrideRows: rows });
    const r = await sdk.setAppAiFeatures(APP, { formFill: true }, { ...FAST, appModuleId: APP_ID });
    assert.deepStrictEqual(r.applied, ['formFill']);
    assert.strictEqual(r.outcomes[0].pendingPublish, undefined, JSON.stringify(rows));
  }
});

test('REAL BUNDLE: the build files a pendingPublish outcome outside `applied`, and a settled one stays where it is', async () => {
  const { rebucketPendingPublish } = require('../lib/ai-app-settings.js');
  const { sdk } = await freshSdk({ gate: '2', effective: '2', overrideRows: [{ value: '2', componentstate: 1 }] });
  const pending = rebucketPendingPublish(await sdk.setAppAiFeatures(APP, { formFill: true }, { ...FAST, appModuleId: APP_ID }));
  assert.deepStrictEqual([pending.applied, pending.pendingPublish], [[], ['formFill']]);
  assert.strictEqual(pending.outcomes[0].status, 'pendingPublish');
  assert.match(pending.outcomes[0].reason, /not in force until the app is published/);

  const { sdk: settled } = await freshSdk({ gate: '2', effective: '2', overrideRows: [{ value: '2' }] });
  const r = rebucketPendingPublish(await settled.setAppAiFeatures(APP, { formFill: true }, { ...FAST, appModuleId: APP_ID }));
  assert.deepStrictEqual(r.applied, ['formFill']);
  assert.strictEqual(r.pendingPublish, undefined, 'no bucket is invented for a result with nothing pending');
});

test('rebucketPendingPublish moves only the flagged features, once, and tolerates results with no detail', () => {
  const { rebucketPendingPublish } = require('../lib/ai-app-settings.js');
  const result = {
    applied: ['formFill', 'nlSearch', 'm365'], skipped: [], notPersisted: [], unverified: [], failed: [],
    outcomes: [
      { feature: 'formFill', status: 'applied', appOverrideExists: true },
      { feature: 'nlSearch', status: 'applied', appOverrideExists: true, pendingPublish: true },
      { feature: 'm365', status: 'applied', appOverrideExists: true, pendingPublish: true },
    ],
  };
  rebucketPendingPublish(result);
  assert.deepStrictEqual(result.applied, ['formFill']);
  assert.deepStrictEqual(result.pendingPublish, ['nlSearch', 'm365']);
  assert.deepStrictEqual(result.outcomes.map((o) => o.status), ['applied', 'pendingPublish', 'pendingPublish']);
  // Idempotent: a second pass finds nothing still reading `applied`.
  rebucketPendingPublish(result);
  assert.deepStrictEqual(result.pendingPublish, ['nlSearch', 'm365']);
  // A result with no per-feature detail (an older SDK shape) is returned untouched.
  const bare = { applied: ['formFill'] };
  assert.strictEqual(rebucketPendingPublish(bare), bare);
  assert.deepStrictEqual(bare, { applied: ['formFill'] });
  assert.strictEqual(rebucketPendingPublish(undefined), undefined);
});