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.

228 KB
Raw Blame
'use strict';
// Publication of managed forms and dashboards: the holds, quarantines and publication debt of the managed settlement
// (lib/managed-feature-contract.js, lib/managed-bindings.js) on the run's publication barrier (lib/publication-barrier.js),
// through the plugin's real HTTP client and the barrier's real transport gate, counting the PublishXml requests that
// reach the wire. A table publish ships everything saved on the table, and a dashboard publish everything saved on the
// dashboard, so a scope whose managed change is not proved must not be published by anyone in the run — a sibling's
// success included — and a publish whose outcome is unknown is never sent a second time.
const test = require('node:test');
const assert = require('node:assert/strict');
const crypto = require('node:crypto');
const fs = require('node:fs');
const { makeTempDir } = require('./helpers/temp-dirs.js');
const { createManagedWire, sdkOver } = require('./helpers/managed-wire.js');
const { openManagedContext, openManagedBindings, CODES, COMPLETION_BASE_BYTES, publicationRiskApproval, publicationRemedy } = require('../lib/managed-bindings.js');
const { runManagedFeature, publishManagedScope, confirmUncertainPublication, createAttemptSendObserver, notStartedAnswer, existingRowDispatches, rowsCreatedByAttempt, withWorkflowEffect, editSwitchRequired, WORKFLOW_EFFECT_FULFILLED, PUBLICATION_UNCONFIRMED, PUBLICATION_UNVERIFIED, CREATION_RECORD_UNSETTLED, LAYER_READER_MISSING, PUBLICATION_SETTLE_DELAYS_MS } = require('../lib/managed-feature-contract.js');
const { createPublicationBarrier } = require('../lib/publication-barrier.js');
const { readSystemFormPublication, readSystemFormLayers, readSystemFormRootPresence, systemFormLayerSha256, systemFormRootLayerSha256 } = require('../lib/systemform-published.js');
const { publishTablesXml } = require('../lib/table-publish.js');
const { createWorkflowEffectGate, requestBodySha256 } = require('../lib/workflow-effect-context.js');
const { postPublishXml } = require('../lib/publish-xml.js');
const { environmentFingerprint } = require('../lib/page-ownership-records.js');
const { canonicalJson } = require('../lib/reconcile-common.js');

const ENV = 'https://contoso.crm.dynamics.com';
const APP = 'contoso_app';
const SOL = 'contoso_solution';
const FP = environmentFingerprint(ENV);
const H = (c) => c.repeat(64);
const sha = (v) => crypto.createHash('sha256').update(canonicalJson(v)).digest('hex');
const layerHash = (row) => sha({ name: row.name, description: row.description, formxml: row.formxml });
// A dashboard's publication hash also covers its root type and table (the shared dashboard layer reader), so a
// dashboard group records it from a read of those fields.
const familyLayerHash = (family, row) => (family === 'dashboard' ? systemFormRootLayerSha256(row) : layerHash(row));
const MAIN = '11111111-1111-4111-8111-111111111111';
const QUICK = '12121212-1212-4121-8121-121212121212';
const DASH = '22222222-2222-4222-8222-222222222222';
const DASH2 = '23232323-2323-4232-8232-232323232323';
const UNRELATED = '29292929-2929-4292-8292-292929292929';
const ACCOUNT = { type: 'table', table: 'account' };
const dashScope = (id) => ({ type: 'dashboard', id });
const rec = (kind, key, id) => ({ formatVersion: 1, appUniqueName: APP, environmentFingerprint: FP, kind, key, id, intentSha256: H('a'), origin: 'created' });
const expected = (rootId) => ({ proofVersion: 1, proofSchema: 'form-v1', rootId, baseProofSha256: null, sentProjectionSha256: H('b'), preservationSha256: H('c'), baseObservation: null, children: [] });
const PROOF = { savedSha256: H('1'), semanticSha256: H('2'), preservationSha256: H('3'), expectedChildrenSha256: null };
const codeOf = async (p) => { try { await p; } catch (e) { return e.code; } return null; };

// What the build's managedStop does: answer a never-retry halt, never throw it.
const halts = [];
const halt = (phase, label, code, { cause } = {}) => { const e = Object.assign(new Error(`${label}: ${code}`), { phase, code, cause, retry: 'never' }); halts.push(e); return e; };

function context(dir, barrier) {
  return openManagedContext({ workspaceDir: dir, environment: ENV, appUniqueName: APP, solutionUniqueName: SOL, barrier });
}

const consumer = (family) => (family === 'dashboard' ? { declaration: {}, tiles: {}, seedIds: [] } : { declaration: {}, children: {}, proofSchema: 'form-v1' });
const familyScope = (family, id) => (family === 'dashboard' ? dashScope(id) : ACCOUNT);

// The ports of one managed form or dashboard over the wire: the change writes the saved layer; the proof reads it back.
function ports(wire, sdk, { family = 'form', key, id, formxml, fail = {} }) {
  const scope = familyScope(family, id);
  const step = (name, fn) => async (...a) => { if (fail[name]) throw fail[name]; return fn(...a); };
  return {
    phase: family === 'dashboard' ? 'dashboards' : 'forms', family, key, knownScopes: [scope], knownIds: [id], halt,
    preflight: step('preflight', async () => undefined),
    resolve: step('resolve', async () => ({})),
    plan: step('plan', async () => {
      const current = wire.saved.get(id);
      if (current && current.formxml === formxml) return { noop: true };
      return { root: { kind: family, key, id }, expected: expected(id), declarationSha256: H('e'), publication: { scope, state: 'owed' } };
    }),
    apply: step('apply', async () => {
      if (!wire.saved.has(id)) wire.putForm({ formid: id, name: key, objecttypecode: family === 'dashboard' ? 'none' : 'account', type: family === 'dashboard' ? 0 : 2, formxml });
      else await sdk.dataverse.patch(`/systemforms(${id})`, { formxml });
      return { sent: true };
    }),
    prove: step('prove', async () => {
      const read = await readSystemFormPublication(sdk.dataverse, id, { rootFields: family === 'dashboard' });
      if (read.saved.formxml !== formxml) throw Object.assign(new Error('the saved form is not the declared one'), { code: 'create-completion-required' });
      return {
        savedProof: { savedSha256: familyLayerHash(family, read.saved) }, acknowledgedRoot: true, records: [rec(family, key, id)], proof: PROOF, consumerState: consumer(family),
        publication: read.state === 'equal' ? { scope, state: 'not-needed', desiredSha256: null, dispatchToken: null } : { scope, state: 'owed', desiredSha256: familyLayerHash(family, read.saved), dispatchToken: null },
      };
    }),
    ensureMembership: step('membership', async () => undefined),
  };
}

const readLayersOf = (sdk) => async (group) => {
  const r = await readSystemFormPublication(sdk.dataverse, group.root.id);
  return { savedSha256: layerHash(r.saved), publishedSha256: r.published ? layerHash(r.published) : H('0') };
};
const publishForms = (sdk, store, barrier, groups) => publishManagedScope({
  store, barrier, scope: ACCOUNT, groups, client: sdk.dataverse, path: 'managed forms of account',
  publish: async () => { const r = await publishTablesXml(sdk.dataverse, ['account']); if (!r.ok) throw Object.assign(new Error(r.reason), { code: 'publish-failed' }); },
});
const publishDashboard = (sdk, store, barrier, family, key, id) => publishManagedScope({
  store, barrier, scope: dashScope(id), groups: [{ family, key }], client: sdk.dataverse, path: `managed dashboard ${key}`,
  publish: async () => { await sdk.fetchArtifact('dashboard', id); await sdk.publishArtifact('dashboard', id); },
});

async function setup(wireOptions) {
  const wire = createManagedWire(wireOptions);
  const barrier = createPublicationBarrier();
  const { sdk } = await sdkOver(wire, { barrier });
  const dir = makeTempDir('mp-');
  const { store } = context(dir, barrier);
  return { wire, barrier, sdk, dir, store };
}

test('holds and quarantine: a hold ends only with its own token; a quarantine ends with nothing; a registered scope is not withheld', () => {
  const b = createPublicationBarrier();
  b.registerKnown([ACCOUNT, dashScope(DASH)], [MAIN, DASH]);
  assert.equal(b.active, false, 'a known scope is not a block');
  b.hold('attempt-a', [ACCOUNT], [MAIN], 'form a');
  b.hold('attempt-b', [ACCOUNT], [QUICK], 'form b');
  assert.equal(b.release('attempt-b'), true);
  assert.equal(b.allowScope(ACCOUNT, 'sibling'), false, 'a sibling\'s release does not end another attempt\'s hold');
  assert.equal(b.release('attempt-a'), true);
  assert.equal(b.allowScope(ACCOUNT, 'after'), true);
  b.quarantine([dashScope(DASH)], [DASH], 'dashboard sales (proof failed)');
  for (const t of ['attempt-a', 'attempt-b', 'anything']) b.release(t);
  assert.equal(b.allowScope(dashScope(DASH), 'later'), false);
  assert.equal(b.allowTarget(['dashboard', DASH], 'app'), false);
  assert.equal(b.allowScope(dashScope(UNRELATED), 'later'), true, 'an unrelated dashboard stays eligible');
  assert.deepEqual(b.withheld().map((w) => [w.dashboard, w.blockedBy]), [[DASH, ['dashboard sales (proof failed)']]]);
});

test('a send permit lets one publish through its own hold only: once, recorded at the send, never past another hold or block', async () => {
  const b = createPublicationBarrier();
  const sent = [];
  const gate = b.gateRequest(async (req) => { sent.push(req.body); return { statusCode: 204, headers: {}, body: '' }; });
  const pub = (tables) => gate({ url: `${ENV}/api/data/v9.0/PublishXml`, method: 'POST', headers: {}, body: JSON.stringify({ ParameterXml: `<importexportxml><entities>${tables.map((t) => `<entity>${t}</entity>`).join('')}</entities></importexportxml>` }) });
  b.hold('own', [ACCOUNT], [MAIN], 'form main (its publish is being sent)');
  const events = [];
  const permit = { token: 'own', scope: ACCOUNT, onDispatch: () => events.push('dispatch'), onWithheld: () => events.push('withheld') };
  await pub(['account']);
  assert.equal(sent.length, 0, 'outside the permit the hold withholds the table');
  await b.withSendPermit(permit, async () => {
    assert.equal((await pub(['account'])).statusCode, 204);
    assert.equal((await pub(['account'])).statusCode, 409, 'a second publish under one permit is not sent');
  });
  assert.deepEqual(events, ['dispatch']);
  assert.equal(sent.length, 1);

  const refused = [];
  await assert.rejects(b.withSendPermit({ ...permit, onDispatch: () => { throw Object.assign(new Error('disk full'), { code: 'store-write' }); } }, () => pub(['account'])), { code: 'store-write' });
  assert.equal(sent.length, 1, 'a dispatch that cannot be recorded is not sent');

  b.hold('sibling', [ACCOUNT], [QUICK], 'form quick (being saved)');
  await b.withSendPermit({ ...permit, onDispatch: () => refused.push('dispatch'), onWithheld: () => refused.push('withheld') }, async () => {
    await pub(['account']);
  });
  assert.deepEqual(refused, ['withheld']);
  assert.equal(sent.length, 1);
  assert.equal(b.allowScope(ACCOUNT, 'after'), false, 'a permit releases nothing');
});

test('an unchanged managed form whose solution membership fails quarantines its table: an earlier sibling view\'s owed table publish sends nothing', async () => {
  const s = await setup();
  s.wire.putForm({ formid: MAIN, name: 'Main', objecttypecode: 'account', type: 2, formxml: '<form v="1"/>' }, { publishedToo: true });
  // A declared view settled earlier in the run and owes the publish of account.
  const owedTables = ['account'];
  const p = ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>', fail: { membership: Object.assign(new Error('AddSolutionComponent failed'), { code: 'membership-failed' }) } });
  assert.equal(await codeOf(runManagedFeature({ ...p, store: s.store, barrier: s.barrier })), 'membership-failed');
  const mark = s.wire.log.length;
  await publishTablesXml(s.sdk.dataverse, owedTables);
  await publishTablesXml(s.sdk.dataverse, s.barrier.allowTables(owedTables, 'the publish phase'));
  assert.equal(s.wire.publishes('account').length, 0, 'zero overlapping table publishes');
  assert.ok(s.wire.log.length >= mark);
  assert.equal(s.barrier.checkAppWrite({ held: new Set(['account']), existingApp: true }).ok, false, 'and no app publish that holds the table');
  await publishTablesXml(s.sdk.dataverse, ['contact']);
  assert.equal(s.wire.publishes('contact').length, 1, 'an unrelated table still publishes');
});

test('publication debt: saved equals the declaration and the published layer is stale — one scoped publish, no content write; the next run publishes nothing', async () => {
  const s = await setup();
  s.wire.putForm({ formid: MAIN, name: 'Main', objecttypecode: 'account', type: 2, formxml: '<form v="1"/>' }, { publishedToo: true });
  s.wire.saved.get(MAIN).formxml = '<form v="2"/>';
  const p = ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' });
  // The group was committed with the debt by an earlier run that stopped before publishing.
  const t = s.store.prepareAttempt({ family: 'form', key: 'account/main', baseGeneration: null, root: { kind: 'form', key: 'account/main', id: MAIN }, knownScopes: [ACCOUNT], declarationSha256: H('e'), publication: { scope: ACCOUNT, state: 'owed' } });
  s.store.markSending(t, expected(MAIN));
  s.store.noteSaved(t, { proof: null, acknowledgedRoot: true });
  s.store.commitGroup({ token: t, baseGeneration: null, records: [rec('form', 'account/main', MAIN)], proof: PROOF, consumerState: consumer('form'), publication: { scope: ACCOUNT, state: 'owed', desiredSha256: layerHash(s.wire.saved.get(MAIN)), dispatchToken: null } });

  const r = await runManagedFeature({ ...p, store: s.store, barrier: s.barrier });
  assert.deepEqual(r.result, { noop: true });
  const out = await publishForms(s.sdk, s.store, s.barrier, [{ family: 'form', key: 'account/main' }]);
  assert.equal(out.sent, true);
  assert.equal(s.wire.publishes('account').length, 1);
  assert.deepEqual(s.wire.writes().filter((w) => !/PublishXml/.test(w.path)), [], 'no content write');
  assert.equal(s.store.readGroup('form', 'account/main').committed.publication.state, 'confirmed');

  const next = await setup();
  next.wire.saved.set(MAIN, s.wire.saved.get(MAIN));
  next.wire.published.set(MAIN, s.wire.published.get(MAIN));
  const again = context(s.dir, next.barrier).store;
  await runManagedFeature({ ...ports(next.wire, next.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' }), store: again, barrier: next.barrier });
  assert.deepEqual(await publishForms(next.sdk, again, next.barrier, [{ family: 'form', key: 'account/main' }]), { sent: false, withheld: false, confirmed: [] });
  assert.equal(next.wire.publishes().length, 0, 'the identical next run publishes nothing');
});

test('a first publish whose answer is lost is never sent a second time, in this run or the next', async () => {
  const s = await setup();
  const p = ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' });
  await runManagedFeature({ ...p, store: s.store, barrier: s.barrier });
  s.wire.script((e) => /PublishXml/.test(e.path), { statusCode: 503, body: { error: { code: '0x80040216', message: 'gateway' } }, unapplied: true });
  assert.equal(await codeOf(publishForms(s.sdk, s.store, s.barrier, [{ family: 'form', key: 'account/main' }])), PUBLICATION_UNCONFIRMED);
  assert.equal(s.wire.publishes('account').length, 1, 'the client sends a publish once');
  assert.equal(await codeOf(publishForms(s.sdk, s.store, s.barrier, [{ family: 'form', key: 'account/main' }])), PUBLICATION_UNCONFIRMED);
  assert.equal(s.wire.publishes('account').length, 1);

  // The next run: the store's uncertain publish withholds the table from every path, and the debt is never re-sent.
  const nextBarrier = createPublicationBarrier();
  const next = context(s.dir, nextBarrier);
  assert.deepEqual(next.debt.map((d) => d.kind), ['uncertain']);
  const { sdk } = await sdkOver(s.wire, { barrier: nextBarrier });
  assert.equal(await codeOf(publishForms(sdk, next.store, nextBarrier, [{ family: 'form', key: 'account/main' }])), PUBLICATION_UNCONFIRMED);
  await publishTablesXml(sdk.dataverse, ['account']);
  assert.equal(s.wire.publishes('account').length, 1, 'no second publish');
});

const publishAll = (s) => s.barrier.gateRequest(s.wire.request)({ url: `${ENV}/api/data/v9.0/PublishAllXml`, method: 'POST', headers: {}, body: '{}' });
// An earlier run committed `formxml` on MAIN and stopped before publishing it: the group owes its publish.
function commitOwedForm(s, formxml) {
  const t = s.store.prepareAttempt({ family: 'form', key: 'account/main', baseGeneration: null, root: { kind: 'form', key: 'account/main', id: MAIN }, knownScopes: [ACCOUNT], declarationSha256: H('e'), publication: { scope: ACCOUNT, state: 'owed' } });
  s.store.markSending(t, expected(MAIN));
  s.store.noteSaved(t, { proof: null, acknowledgedRoot: true });
  const desired = layerHash({ ...s.wire.saved.get(MAIN), formxml });
  s.store.commitGroup({ token: t, baseGeneration: null, records: [rec('form', 'account/main', MAIN)], proof: PROOF, consumerState: consumer('form'), publication: { scope: ACCOUNT, state: 'owed', desiredSha256: desired, dispatchToken: null } });
}

test('a publish whose answer is lost withholds its table for the rest of the run: no sibling table publish, publish-all or app write overlaps it; another table still publishes', async () => {
  const s = await setup();
  await runManagedFeature({ ...ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: s.store, barrier: s.barrier });
  s.wire.script((e) => /PublishXml/.test(e.path), { statusCode: 503, body: { error: { code: '0x80040216', message: 'gateway' } }, unapplied: true });
  assert.equal(await codeOf(publishForms(s.sdk, s.store, s.barrier, [{ family: 'form', key: 'account/main' }])), PUBLICATION_UNCONFIRMED);
  assert.equal(s.wire.publishes('account').length, 1);
  assert.equal(s.barrier.allowScope(ACCOUNT, 'a sibling view'), false, 'the table is withheld, not merely released');
  assert.deepEqual(s.barrier.allowTables(['account', 'contact'], 'the publish phase'), ['contact']);
  await publishTablesXml(s.sdk.dataverse, ['account']);
  await publishAll(s);
  assert.equal(s.wire.publishes('account').length, 1, 'no sibling path publishes over the unconfirmed send');
  assert.equal(s.wire.log.filter((e) => /PublishAllXml/.test(e.path)).length, 0);
  assert.equal(s.barrier.checkAppWrite({ held: new Set(['account']), existingApp: true }).ok, false);
  await publishTablesXml(s.sdk.dataverse, ['contact']);
  assert.equal(s.wire.publishes('contact').length, 1, 'an unrelated table still publishes');
  assert.equal(s.store.readGroup('form', 'account/main').committed.publication.state, 'unconfirmed');
});

test('a scope a sibling holds at the moment of the send is not published and consumes nothing: the debt stays owed and is paid once the sibling releases it', async () => {
  const s = await setup();
  await runManagedFeature({ ...ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: s.store, barrier: s.barrier });
  const groups = [{ family: 'form', key: 'account/main' }];
  const out = await publishManagedScope({
    store: s.store, barrier: s.barrier, scope: ACCOUNT, groups, client: s.sdk.dataverse, path: 'managed forms of account',
    publish: async () => {
      // A sibling form starts saving on the table between the barrier's check and the send.
      s.barrier.hold('sibling', [ACCOUNT], [QUICK], 'form quick (being saved)');
      const r = await publishTablesXml(s.sdk.dataverse, ['account']);
      if (!r.ok) throw Object.assign(new Error(r.reason), { code: 'publish-failed' });
    },
  });
  assert.deepEqual(out, { sent: false, withheld: true, confirmed: [] });
  assert.equal(s.wire.publishes('account').length, 0, 'nothing overlaps the sibling\'s unproved change');
  assert.equal(s.store.readGroup('form', 'account/main').committed.publication.state, 'owed', 'the debt is not consumed');
  assert.equal(s.barrier.allowScope(ACCOUNT, 'after'), false, 'the sibling\'s hold stands');
  s.barrier.release('sibling');
  assert.equal((await publishForms(s.sdk, s.store, s.barrier, groups)).sent, true);
  assert.equal(s.wire.publishes('account').length, 1);
  assert.equal(s.store.readGroup('form', 'account/main').committed.publication.state, 'confirmed');
});

test('owed publication whose saved layer has drifted is not published: nothing is sent, the debt stays owed and the table is withheld; an equal saved layer publishes once', async () => {
  const s = await setup();
  s.wire.putForm({ formid: MAIN, name: 'Main', objecttypecode: 'account', type: 2, formxml: '<form v="1"/>' }, { publishedToo: true });
  commitOwedForm(s, '<form v="2"/>');
  // Someone else's change is saved on the form: publishing the table would put it live under this debt.
  s.wire.saved.get(MAIN).formxml = '<form foreign="1"/>';
  const drift = await publishForms(s.sdk, s.store, s.barrier, [{ family: 'form', key: 'account/main' }]).then(() => null, (e) => e);
  assert.equal(drift && drift.code, 'create-completion-required');
  // The stop says what it found (a saved change the build did not make, not published) and what the maker does about it.
  assert.match(drift.message, /managed form "account\/main" has a saved change this build did not make and that is not published/);
  assert.match(drift.message, /the publish of its table account was not sent: it would put that change live\. In the maker, publish that change if it should be kept, or undo it there and save, then run the build again/);
  assert.equal(s.wire.publishes().length, 0);
  assert.equal(s.wire.published.get(MAIN).formxml, '<form v="1"/>', 'the foreign change was not published');
  assert.equal(s.store.readGroup('form', 'account/main').committed.publication.state, 'owed');
  await publishTablesXml(s.sdk.dataverse, ['account']);
  assert.equal(s.wire.publishes().length, 0, 'the table is withheld for the rest of the run');

  const c = await setup();
  c.wire.putForm({ formid: MAIN, name: 'Main', objecttypecode: 'account', type: 2, formxml: '<form v="1"/>' }, { publishedToo: true });
  commitOwedForm(c, '<form v="2"/>');
  c.wire.saved.get(MAIN).formxml = '<form v="2"/>';
  assert.equal((await publishForms(c.sdk, c.store, c.barrier, [{ family: 'form', key: 'account/main' }])).sent, true);
  assert.equal(c.wire.publishes('account').length, 1);
  assert.equal(c.wire.published.get(MAIN).formxml, '<form v="2"/>');
});

test('a drifted saved layer someone else already published is not called unpublished, and the stop names the next build as the way on', async () => {
  const s = await setup();
  s.wire.putForm({ formid: MAIN, name: 'Main', objecttypecode: 'account', type: 2, formxml: '<form foreign="1"/>' }, { publishedToo: true });
  commitOwedForm(s, '<form v="2"/>');
  const drift = await publishForms(s.sdk, s.store, s.barrier, [{ family: 'form', key: 'account/main' }]).then(() => null, (e) => e);
  assert.equal(drift && drift.code, 'create-completion-required');
  assert.doesNotMatch(drift.message, /not published|In the maker/);
  assert.match(drift.message, /has a saved change this build did not make \(its saved layer is not the one its managed group proved\)/);
  assert.match(drift.message, /Run the build again: it reads the saved layer afresh and names any change it would overwrite/);
  assert.equal(s.wire.publishes().length, 0);
});
const formRow = (id, formxml, table = 'account') => ({ formid: id, name: 'Main', objecttypecode: table, type: 2, formxml });
// A form an earlier run committed on `account`: `publishedXml` is live, `savedXml` is saved, and the group's publication
// is `state` — 'owed' (desired = the saved layer it committed) or 'not-needed' (saved equalled published at the commit).
function committedForm(s, { id, key, publishedXml, savedXml, state = 'owed', origin = 'created' }) {
  s.wire.putForm(formRow(id, publishedXml), { publishedToo: true });
  s.wire.saved.get(id).formxml = savedXml;
  const t = s.store.prepareAttempt({ family: 'form', key, baseGeneration: null, root: { kind: 'form', key, id }, knownScopes: [ACCOUNT], declarationSha256: H('e'), publication: { scope: ACCOUNT, state: 'owed' } });
  s.store.markSending(t, expected(id));
  s.store.noteSaved(t, { proof: null, acknowledgedRoot: origin === 'created' });
  const publication = state === 'owed'
    ? { scope: ACCOUNT, state: 'owed', desiredSha256: layerHash(s.wire.saved.get(id)), dispatchToken: null }
    : { scope: ACCOUNT, state: 'not-needed', desiredSha256: null, dispatchToken: null };
  s.store.commitGroup({ token: t, baseGeneration: null, records: [{ ...rec('form', key, id), origin }], proof: PROOF, consumerState: consumer('form'), publication, adoptionApproved: origin === 'adopted' });
}
const MAIN_G = { family: 'form', key: 'account/main' };
const QUICK_G = { family: 'form', key: 'account/quick' };
const storeWriteFailure = () => Object.assign(new Error('no space left on the device'), { code: 'ENOSPC' });

test('a publish that was sent fails closed when its settlement is not recorded: a failed confirm write, a partial confirmation of two groups, or a failed outcome write withholds the table for the rest of the run', async () => {
  // The one confirmation write fails after the read-back proved the publish.
  const a = await setup();
  committedForm(a, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
  a.store.confirmPublished = () => { throw storeWriteFailure(); };
  assert.equal(await codeOf(publishForms(a.sdk, a.store, a.barrier, [MAIN_G])), 'ENOSPC');
  assert.equal(a.wire.publishes('account').length, 1);
  assert.equal(a.barrier.allowScope(ACCOUNT, 'a sibling view'), false, 'the table is blocked, not merely released');
  await publishTablesXml(a.sdk.dataverse, ['account']);
  assert.equal(a.wire.publishes('account').length, 1, 'no sibling publishes over the unrecorded send');
  await publishTablesXml(a.sdk.dataverse, ['contact']);
  assert.equal(a.wire.publishes('contact').length, 1, 'an unrelated table still publishes');

  // Two groups published by one send, confirmed for only the first: the store refuses a confirmation that does not
  // name every group of the dispatch, so nothing of it is settled.
  const b = await setup();
  committedForm(b, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
  committedForm(b, { id: QUICK, key: 'account/quick', publishedXml: '<form q="1"/>', savedXml: '<form q="2"/>' });
  const realConfirm = b.store.confirmPublished;
  b.store.confirmPublished = (args) => { realConfirm({ ...args, groups: args.groups.slice(0, 1) }); throw storeWriteFailure(); };
  assert.equal(await codeOf(publishForms(b.sdk, b.store, b.barrier, [MAIN_G, QUICK_G])), 'managed-publication-unconfirmed');
  assert.equal(b.wire.publishes('account').length, 1);
  assert.equal(b.barrier.allowScope(ACCOUNT, 'a sibling view'), false, 'a partial confirmation withholds the table');
  await publishTablesXml(b.sdk.dataverse, ['account']);
  assert.equal(b.wire.publishes('account').length, 1);
  assert.deepEqual([MAIN_G, QUICK_G].map((g) => b.store.readGroup(g.family, g.key).committed.publication.state), ['dispatching', 'dispatching']);
  assert.ok(context(b.dir, createPublicationBarrier()).debt.some((d) => d.key === 'account/quick' && d.kind === 'uncertain'), 'the next run still withholds it');

  // A send that ended definitely-not-started, whose outcome cannot be written: the store still says dispatching.
  const c = await setup();
  committedForm(c, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
  c.store.notePublishOutcome = () => { throw storeWriteFailure(); };
  const refusedConnection = (s) => publishManagedScope({
    store: s.store, barrier: s.barrier, scope: ACCOUNT, groups: [MAIN_G], client: s.sdk.dataverse,
    publish: async () => { await publishTablesXml(s.sdk.dataverse, ['account']); throw Object.assign(new Error('connection refused before the request was written'), { code: 'ECONNREFUSED', definiteNoStart: true }); },
  });
  c.wire.script((e) => /PublishXml/.test(e.path), { statusCode: 503, body: {}, unapplied: true });
  assert.equal(await codeOf(refusedConnection(c)), 'ENOSPC');
  assert.equal(c.barrier.allowScope(ACCOUNT, 'a sibling view'), false, 'not proved unsent in the store: withheld');

  // The same with a store that records it: proved unsent, so the scope is released and the debt is paid once later.
  const d = await setup();
  committedForm(d, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
  d.wire.script((e) => /PublishXml/.test(e.path), { statusCode: 503, body: {}, unapplied: true });
  assert.equal(await codeOf(refusedConnection(d)), 'ECONNREFUSED');
  assert.equal(d.barrier.allowScope(ACCOUNT, 'a sibling view'), true, 'a definitely-unsent exit releases');
  assert.deepEqual(d.store.readGroup('form', 'account/main').committed.publication, { ...d.store.readGroup('form', 'account/main').committed.publication, state: 'owed', dispatchToken: null });
  d.wire.log.length = 0;
  assert.equal((await publishForms(d.sdk, d.store, d.barrier, [MAIN_G])).sent, true);
  assert.equal(d.wire.publishes('account').length, 1);
});

test('a pre-send read of the layers that fails or answers no proof withholds the table for the run: nothing is sent and no sibling publishes it', async () => {
  for (const form of [async () => { throw new Error('socket hang up'); }, async () => ({ savedSha256: H('9') })]) {
    const s = await setup();
    committedForm(s, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
    const out = codeOf(publishManagedScope({ store: s.store, barrier: s.barrier, scope: ACCOUNT, groups: [MAIN_G], client: s.sdk.dataverse, readers: { form }, publish: () => publishTablesXml(s.sdk.dataverse, ['account']) }));
    assert.equal(await out, PUBLICATION_UNVERIFIED);
    assert.equal(s.wire.publishes().length, 0);
    assert.equal(s.barrier.allowScope(ACCOUNT, 'a sibling view'), false, 'the unread table is fenced');
    await publishTablesXml(s.sdk.dataverse, ['account']);
    assert.equal(s.wire.publishes('account').length, 0, 'no sibling publishes the unread saved layer');
    assert.equal(s.store.readGroup('form', 'account/main').committed.publication.state, 'owed', 'the debt is not consumed');
  }
});

test('a table publish is sent only while every managed form of the table has the saved layer its group proved: a drifted sibling, already published or not passed, stops it; unrelated scopes stay eligible', async () => {
  // Both groups passed; MAIN's debt is already live, but someone saved over it since.
  const a = await setup();
  committedForm(a, { id: MAIN, key: 'account/main', publishedXml: '<form v="2"/>', savedXml: '<form v="2"/>' });
  committedForm(a, { id: QUICK, key: 'account/quick', publishedXml: '<form q="1"/>', savedXml: '<form q="2"/>' });
  a.wire.saved.get(MAIN).formxml = '<form foreign="true"/>';
  assert.equal(await codeOf(publishForms(a.sdk, a.store, a.barrier, [MAIN_G, QUICK_G])), 'create-completion-required');
  assert.equal(a.wire.publishes().length, 0);
  assert.equal(a.wire.published.get(MAIN).formxml, '<form v="2"/>', 'the foreign save is not put live');
  assert.equal(a.barrier.allowScope(ACCOUNT, 'a sibling view'), false);
  assert.equal(a.store.readGroup('form', 'account/quick').committed.publication.state, 'owed');

  // The caller passes only QUICK; MAIN settled earlier (nothing owed) and has a foreign save since.
  const b = await setup();
  committedForm(b, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="1"/>', state: 'not-needed' });
  committedForm(b, { id: QUICK, key: 'account/quick', publishedXml: '<form q="1"/>', savedXml: '<form q="2"/>' });
  b.wire.saved.get(MAIN).formxml = '<form foreign="true"/>';
  assert.equal(await codeOf(publishForms(b.sdk, b.store, b.barrier, [QUICK_G])), 'create-completion-required');
  assert.equal(b.wire.publishes().length, 0);
  assert.equal(b.wire.published.get(MAIN).formxml, '<form v="1"/>');

  // Controls: a settled sibling whose saved layer is still its published one, and a drifted form of another table.
  const c = await setup();
  committedForm(c, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="1"/>', state: 'not-needed' });
  committedForm(c, { id: QUICK, key: 'account/quick', publishedXml: '<form q="1"/>', savedXml: '<form q="2"/>' });
  c.wire.putForm(formRow(UNRELATED, '<form c="1"/>', 'contact'), { publishedToo: true });
  c.wire.saved.get(UNRELATED).formxml = '<form c="foreign"/>';
  assert.deepEqual(await publishForms(c.sdk, c.store, c.barrier, [QUICK_G]), { sent: true, withheld: false, confirmed: [QUICK_G] });
  assert.equal(c.wire.publishes('account').length, 1, 'one send');
  assert.equal(c.wire.published.get(QUICK).formxml, '<form q="2"/>');
  assert.equal(c.barrier.allowScope({ type: 'table', table: 'contact' }, 'the publish phase'), true, 'an unrelated scope stays eligible');
});

test('a send permit sends only a request whose whole publish target set is the permit\'s one scope: a publish of everything, another scope, an extra scope or an unreadable request is refused unsent', async () => {
  const b = createPublicationBarrier();
  const sent = [];
  const gate = b.gateRequest(async (req) => { sent.push(req); return { statusCode: 204, headers: {}, body: '' }; });
  const post = (action, body) => ({ url: `${ENV}/api/data/v9.0/${action}`, method: 'POST', headers: {}, body });
  const xml = (inner) => post('PublishXml', JSON.stringify({ ParameterXml: `<importexportxml>${inner}</importexportxml>` }));
  const entities = (...t) => `<entities>${t.map((x) => `<entity>${x}</entity>`).join('')}</entities>`;
  b.hold('own', [ACCOUNT], [MAIN], 'form main (its publish is being sent)');
  b.hold('dash', [dashScope(DASH)], [DASH], 'dashboard sales (its publish is being sent)');
  const refusedFor = async (scope, token, req) => {
    const events = [];
    const answer = await b.withSendPermit({ token, scope, onDispatch: () => events.push('dispatch'), onWithheld: () => events.push('withheld'), onRefused: () => events.push('refused') }, () => gate(req));
    return { status: answer.statusCode, events };
  };
  const refusals = [
    [ACCOUNT, 'own', xml(entities('account', 'contact'))],
    [ACCOUNT, 'own', xml(entities('contact'))],
    [ACCOUNT, 'own', post('PublishAllXml', '{}')],
    [ACCOUNT, 'own', post('$batch', '--b\r\nPOST PublishXml\r\n\r\n{"ParameterXml":"<importexportxml><entities><entity>account</entity></entities></importexportxml>"}\r\n--b--')],
    [ACCOUNT, 'own', post('PublishXml', 'not json')],
    [ACCOUNT, 'own', xml(`${entities('account')}<appmodules><appmodule>{0a0a0a0a-0000-4000-8000-000000000001}</appmodule></appmodules>`)],
    [ACCOUNT, 'own', xml(`${entities('account')}<dashboards><dashboard>${DASH}</dashboard></dashboards>`)],
    [ACCOUNT, 'own', xml('')],
    [dashScope(DASH), 'dash', xml(entities('account'))],
    [dashScope(DASH), 'dash', xml(`<dashboards><dashboard>${DASH}</dashboard><dashboard>${DASH2}</dashboard></dashboards>`)],
    // An empty target leaf, in every spelling, and a structure that does not close as it opens.
    [ACCOUNT, 'own', xml(`${entities('account')}`.replace('</entities>', '<entity/></entities>'))],
    [ACCOUNT, 'own', xml(`${entities('account')}`.replace('</entities>', '<entity /></entities>'))],
    [ACCOUNT, 'own', xml(`${entities('account')}`.replace('</entities>', '<entity>\n</entity></entities>'))],
    [dashScope(DASH), 'dash', xml(`<dashboards><dashboard>${DASH}</dashboard><dashboard/></dashboards>`)],
    [ACCOUNT, 'own', xml('<entities><entity>account</entity></dashboards>')],
    [ACCOUNT, 'own', post('PublishXml', JSON.stringify({ ParameterXml: '<importexportxml><entities><entity>account</entity></entities>' }))],
    // The supported subset: no namespace, no attribute, and a target tag written exactly `<entity>` / `<dashboard>`.
    [ACCOUNT, 'own', xml('<entities><entity >account</entity></entities>')],
    [ACCOUNT, 'own', xml('<entities><x:entity xmlns:x="urn:x">account</x:entity></entities>')],
    [ACCOUNT, 'own', post('PublishXml', JSON.stringify({ ParameterXml: '<importexportxml xmlns="urn:x"><entities><entity>account</entity></entities></importexportxml>' }))],
  ];
  for (const [scope, token, req] of refusals) {
    assert.deepEqual(await refusedFor(scope, token, req), { status: 409, events: ['refused'] }, `refused: ${req.url} ${req.body}`);
  }
  assert.equal(sent.length, 0, 'nothing of a refused request is sent');

  // The permit's own scope, written as the SDK and the table publish write it, is sent once each.
  const own = await refusedFor(ACCOUNT, 'own', xml(`<entities><entity> Account </entity></entities><nodes/>`));
  assert.deepEqual(own, { status: 204, events: ['dispatch'] });
  const dash = await refusedFor(dashScope(DASH), 'dash', xml(`<dashboards><dashboard>{${DASH.toUpperCase()}}</dashboard></dashboards>`));
  assert.deepEqual(dash, { status: 204, events: ['dispatch'] });
  assert.equal(sent.length, 2);

  // Outside a permit nothing changes: with nothing withheld, a two-table publish goes as it came.
  b.release('own');
  b.release('dash');
  const plain = xml(entities('account', 'contact'));
  await gate(plain);
  assert.equal(sent[2], plain);
});

test('a managed publish whose request names more than its own scope is refused unsent: the debt stays owed, nothing is blocked, and a correct publish pays it once', async () => {
  const s = await setup();
  committedForm(s, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
  s.wire.putForm(formRow(UNRELATED, '<form c="1"/>', 'contact'), { publishedToo: true });
  s.wire.saved.get(UNRELATED).formxml = '<form c="2"/>';
  const broad = publishManagedScope({
    store: s.store, barrier: s.barrier, scope: ACCOUNT, groups: [MAIN_G], client: s.sdk.dataverse,
    publish: () => publishTablesXml(s.sdk.dataverse, ['account', 'contact']),
  });
  assert.equal(await codeOf(broad), 'managed-publication-refused');
  assert.equal(s.wire.publishes().length, 0);
  assert.equal(s.wire.published.get(UNRELATED).formxml, '<form c="1"/>');
  const pub = s.store.readGroup('form', 'account/main').committed.publication;
  assert.deepEqual([pub.state, pub.dispatchToken], ['owed', null], 'no token is used');
  assert.equal(s.barrier.allowScope(ACCOUNT, 'after'), true, 'definitely unsent: released, not blocked');
  assert.equal((await publishForms(s.sdk, s.store, s.barrier, [MAIN_G])).sent, true);
  assert.equal(s.wire.publishes('account').length, 1);
  assert.equal(s.wire.publishes('contact').length, 0);
});

test('a managed publish whose ParameterXml has an empty target leaf or a malformed structure is refused unsent: no dispatch, debt owed, no token used', async () => {
  const bodies = {
    selfClosingEntity: '<importexportxml><entities><entity>account</entity><entity/></entities></importexportxml>',
    selfClosingWhitespaceEntity: '<importexportxml><entities><entity>account</entity><entity /></entities></importexportxml>',
    selfClosingDashboard: '<importexportxml><entities><entity>account</entity></entities><dashboards><dashboard/></dashboards></importexportxml>',
    malformed: '<importexportxml><entities><entity>account</entity></dashboards></importexportxml>',
    pairedEmptyEntity: '<importexportxml><entities><entity>account</entity><entity>  </entity></entities></importexportxml>',
    leafOutsideItsList: '<importexportxml><entity>account</entity></importexportxml>',
    leafInTheOtherList: '<importexportxml><dashboards><entity>account</entity></dashboards></importexportxml>',
    nonEmptyContainer: '<importexportxml><entities><entity>account</entity></entities><nodes>x</nodes></importexportxml>',
    commentInLeaf: '<importexportxml><entities><entity>account<!-- contact --></entity></entities></importexportxml>',
    textAroundRoot: 'x<importexportxml><entities><entity>account</entity></entities></importexportxml>',
  };
  for (const [name, body] of Object.entries(bodies)) {
    const s = await setup();
    committedForm(s, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
    const out = publishManagedScope({
      store: s.store, barrier: s.barrier, scope: ACCOUNT, groups: [MAIN_G], client: s.sdk.dataverse,
      publish: () => postPublishXml(s.sdk.dataverse, body),
    });
    assert.equal(await codeOf(out), 'managed-publication-refused', name);
    assert.equal(s.wire.publishes().length, 0, `${name}: nothing is sent`);
    const pub = s.store.readGroup('form', 'account/main').committed.publication;
    assert.deepEqual([pub.state, pub.dispatchToken], ['owed', null], `${name}: the debt stays owed and no token is used`);
    assert.equal(s.barrier.allowScope(ACCOUNT, 'after'), true, `${name}: definitely unsent, so not blocked`);
  }
  // Controls: the scoped table request with a harmless empty container, and a scoped dashboard request, each send once.
  const t = await setup();
  committedForm(t, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
  const table = await publishManagedScope({
    store: t.store, barrier: t.barrier, scope: ACCOUNT, groups: [MAIN_G], client: t.sdk.dataverse,
    publish: () => postPublishXml(t.sdk.dataverse, '<importexportxml><entities><entity>account</entity></entities><nodes/><nodes /><entities></entities></importexportxml>'),
  });
  assert.equal(table.sent, true);
  assert.equal(t.wire.publishes().length, 1);
});

test('the layers of every covered group are read by its family\'s reader: a covered group of a family with no reader fences the scope, never skipped', async () => {
  const VIEW = '31313131-3131-4313-8313-313131313131';
  const viewGroup = (s) => {
    const t = s.store.prepareAttempt({ family: 'view', key: 'account/active', baseGeneration: null, root: { kind: 'view', key: 'account/active', id: VIEW }, knownScopes: [ACCOUNT], declarationSha256: H('e') });
    s.store.markSending(t, { ...expected(VIEW), proofSchema: 'view-v1' });
    s.store.noteSaved(t, { proof: null, acknowledgedRoot: true });
    s.store.commitGroup({ token: t, baseGeneration: null, records: [rec('view', 'account/active', VIEW)], proof: PROOF, consumerState: { baseline: {} }, publication: { scope: ACCOUNT, state: 'not-needed', desiredSha256: null, dispatchToken: null }, proofSchema: 'view-v1' });
  };
  // A form debt on a table that also holds a committed view group: the shared readers have no view reader here.
  const s = await setup();
  committedForm(s, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
  viewGroup(s);
  const read = [];
  const formOnly = { form: async (client, group) => { read.push(group.family); return readSystemFormLayers(client, group); } };
  const missing = publishManagedScope({ store: s.store, barrier: s.barrier, scope: ACCOUNT, groups: [MAIN_G], client: s.sdk.dataverse, readers: formOnly, publish: () => publishTablesXml(s.sdk.dataverse, ['account']) });
  assert.equal(await codeOf(missing), LAYER_READER_MISSING);
  assert.deepEqual(read, [], 'nothing is read for a scope that cannot be read whole');
  assert.equal(s.wire.publishes().length, 0);
  assert.equal(s.barrier.allowScope(ACCOUNT, 'a sibling'), false, 'the scope is fenced for the run');
  assert.equal(s.store.readGroup('form', 'account/main').committed.publication.state, 'owed');

  // With a view reader, each covered group goes to its own family's reader, and the form publish is sent once.
  const v = await setup();
  committedForm(v, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
  viewGroup(v);
  const calls = [];
  const readers = {
    form: async (client, group) => { calls.push(`form ${group.root.id}`); return readSystemFormLayers(client, group); },
    view: async (client, group) => { calls.push(`view ${group.root.id}`); return { savedSha256: H('7'), publishedSha256: H('7') }; },
  };
  const out = await publishManagedScope({ store: v.store, barrier: v.barrier, scope: ACCOUNT, groups: [MAIN_G], client: v.sdk.dataverse, readers, publish: () => publishTablesXml(v.sdk.dataverse, ['account']) });
  assert.equal(out.sent, true);
  assert.deepEqual(calls, [`form ${MAIN}`, `view ${VIEW}`, `form ${MAIN}`], 'before the send every covered group; after it the debt');
  assert.equal(v.wire.publishes('account').length, 1);

  // A caller-supplied reader function is not accepted: a family's reader is shared, never reimplemented per caller.
  const r = await setup();
  committedForm(r, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
  assert.equal(await codeOf(publishManagedScope({ store: r.store, barrier: r.barrier, scope: ACCOUNT, groups: [MAIN_G], readLayers: readLayersOf(r.sdk), publish: () => publishTablesXml(r.sdk.dataverse, ['account']) })), CODES.notSettled);
  assert.equal(r.wire.publishes().length, 0);
});

test('a table\'s managed views and charts are read by the shared readers before a form publish of the table: equal layers send once, an unpublished saved layer fences the table', async () => {
  const VIEW = '31313131-3131-4313-8313-313131313131';
  const CHART = '32323232-3232-4323-8323-323232323232';
  const committedQuery = (s, family, key, id) => {
    const t = s.store.prepareAttempt({ family, key, baseGeneration: null, root: { kind: family, key, id }, knownScopes: [ACCOUNT], declarationSha256: H('e') });
    s.store.markSending(t, { ...expected(id), proofSchema: `${family}-v1` });
    s.store.noteSaved(t, { proof: null, acknowledgedRoot: true });
    s.store.commitGroup({ token: t, baseGeneration: null, records: [rec(family, key, id)], proof: PROOF, consumerState: { baseline: {} }, publication: { scope: ACCOUNT, state: 'not-needed', desiredSha256: null, dispatchToken: null }, proofSchema: `${family}-v1` });
  };
  const view = { savedqueryid: VIEW, name: 'Active', returnedtypecode: 'account', fetchxml: '<fetch v="1"/>', layoutxml: '<grid/>' };
  const chart = { savedqueryvisualizationid: CHART, name: 'By owner', primaryentitytypecode: 'account', datadescription: '<datadefinition/>', presentationdescription: '<Chart/>' };
  const arrange = async ({ viewEdited = false, chartPublished = true } = {}) => {
    const s = await setup();
    committedForm(s, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
    // viewEdited: the view's published layer is an older definition; its saved layer holds an edit not yet published.
    if (viewEdited) s.wire.putQuery('savedqueries', 'savedqueryid', { ...view, fetchxml: '<fetch v="0"/>' }, { publishedToo: true });
    s.wire.putQuery('savedqueries', 'savedqueryid', view, { publishedToo: !viewEdited });
    s.wire.putQuery('savedqueryvisualizations', 'savedqueryvisualizationid', chart, { publishedToo: chartPublished });
    committedQuery(s, 'view', 'account/active', VIEW);
    committedQuery(s, 'chart', 'account/by owner', CHART);
    return s;
  };
  const publish = (s) => publishManagedScope({ store: s.store, barrier: s.barrier, scope: ACCOUNT, groups: [MAIN_G], client: s.sdk.dataverse, publish: () => publishTablesXml(s.sdk.dataverse, ['account']) });
  const readPaths = (s) => s.wire.log.filter((e) => e.method === 'GET' && /^savedquer/i.test(e.path)).map((e) => e.path);

  // Saved equals published on both: the form publish is sent once, after each was read in both layers by the shared map.
  const s = await arrange();
  assert.equal((await publish(s)).sent, true);
  assert.equal(s.wire.publishes('account').length, 1);
  assert.deepEqual(readPaths(s), [
    `savedqueries(${VIEW})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`, `savedqueries(${VIEW})`,
    `savedqueryvisualizations(${CHART})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`, `savedqueryvisualizations(${CHART})`,
  ]);

  // A chart saved and never published (or a view edit saved and not published) would go live with the form: nothing is sent.
  for (const variant of [{ chartPublished: false }, { viewEdited: true }]) {
    const u = await arrange(variant);
    assert.equal(await codeOf(publish(u)), CODES.completion, JSON.stringify(variant));
    assert.equal(u.wire.publishes().length, 0);
    assert.equal(u.barrier.allowScope(ACCOUNT, 'a sibling'), false, 'the table is fenced for the run');
    assert.equal(u.store.readGroup('form', 'account/main').committed.publication.state, 'owed');
  }
});

test('a dashboard known only by its retained id, with no scope given, is quarantined when its creation record is not settled: no path publishes it', async () => {
  const s = await setup();
  s.wire.putForm({ formid: DASH, name: 'Sales', objecttypecode: 'none', type: 0, formxml: '<form d="1"/>' });
  s.wire.putForm({ formid: UNRELATED, name: 'Other', objecttypecode: 'none', type: 0, formxml: '<form o="1"/>' });
  let downstream = 0;
  const later = async () => { downstream += 1; };
  const code = await codeOf(runManagedFeature({
    phase: 'dashboards', family: 'dashboard', key: 'sales', knownScopes: [], knownIds: [DASH], store: s.store, barrier: s.barrier, halt,
    preflight: async () => undefined,
    resolve: async () => { throw Object.assign(new Error('the retained creation is not settled'), { code: CREATION_RECORD_UNSETTLED }); },
    plan: later, apply: later, prove: later, ensureMembership: later,
  }));
  assert.equal(code, CREATION_RECORD_UNSETTLED);
  assert.equal(downstream, 0);
  assert.equal(s.barrier.active, true);
  await s.sdk.fetchArtifact('dashboard', DASH);
  await s.sdk.publishArtifact('dashboard', DASH);
  await s.barrier.gateRequest(s.wire.request)({ url: `${ENV}/api/data/v9.0/PublishXml`, method: 'POST', headers: {}, body: JSON.stringify({ ParameterXml: `<importexportxml><dashboards><dashboard>${DASH}</dashboard></dashboards></importexportxml>` }) });
  assert.equal(s.wire.publishes(DASH).length, 0, 'zero sends that name the dashboard');
  assert.equal(s.barrier.checkAppWrite({ held: new Set(), existingApp: true, heldDashboards: [DASH] }).ok, false);
  await s.sdk.fetchArtifact('dashboard', UNRELATED);
  await s.sdk.publishArtifact('dashboard', UNRELATED);
  assert.equal(s.wire.publishes(UNRELATED).length, 1, 'an unrelated dashboard still publishes');
});

test('a successful create and a successful recovery of a pending attempt each send one scoped publish; a true no-op sends none', async () => {
  const s = await setup();
  const p = ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' });
  assert.equal((await runManagedFeature({ ...p, store: s.store, barrier: s.barrier })).result.committed, true);
  await publishForms(s.sdk, s.store, s.barrier, [{ family: 'form', key: 'account/main' }]);
  assert.equal(s.wire.publishes('account').length, 1);

  // A true no-op: saved equals the declaration, published equals saved, nothing pending.
  const noop = await runManagedFeature({ ...p, store: s.store, barrier: s.barrier });
  assert.deepEqual(noop.result, { noop: true });
  await publishForms(s.sdk, s.store, s.barrier, [{ family: 'form', key: 'account/main' }]);
  assert.equal(s.wire.publishes('account').length, 1);

  // A run that dies after the service accepted the change, before the commit.
  const crash = Object.assign(new Error('the process ended'), { code: 'crash' });
  const p2 = ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>', fail: { prove: crash } });
  const realApply = p2.apply;
  let applied = 0;
  p2.apply = async (...a) => { applied += 1; return realApply(...a); };
  assert.equal(await codeOf(runManagedFeature({ ...p2, store: s.store, barrier: s.barrier })), 'crash');
  assert.equal(applied, 1);

  const b = createPublicationBarrier();
  const recovered = context(s.dir, b);
  assert.deepEqual(recovered.debt.map((d) => d.kind), ['hold']);
  const { sdk } = await sdkOver(s.wire, { barrier: b });
  const p3 = ports(s.wire, sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' });
  const r = await runManagedFeature({ ...p3, store: recovered.store, barrier: b });
  assert.deepEqual(r.result, { committed: true, recovered: true });
  assert.equal(b.active, false, 'the recovered attempt released its own hold');
  await publishForms(sdk, recovered.store, b, [{ family: 'form', key: 'account/main' }]);
  assert.equal(s.wire.publishes('account').length, 2, 'exactly one more publish, for the recovered change');
  assert.equal(s.wire.published.get(MAIN).formxml, '<form v="2"/>');
});

test('a plan\'s completionBytes reaches the attempt\'s completion reservation; without one the store\'s default is held', async () => {
  const s = await setup();
  const crash = Object.assign(new Error('the process ended'), { code: 'crash' });
  const sized = ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>', fail: { apply: crash } });
  const plan = sized.plan;
  sized.plan = async (...a) => ({ ...(await plan(...a)), completionBytes: 3 * (1 << 20) });
  assert.equal(await codeOf(runManagedFeature({ ...sized, store: s.store, barrier: s.barrier })), 'crash');
  assert.equal(s.store.readGroup('form', 'account/main').pending.completionReserve.bytes, 3 * (1 << 20));

  const plain = ports(s.wire, s.sdk, { key: 'account/quick', id: QUICK, formxml: '<form v="1"/>', fail: { apply: crash } });
  assert.equal(await codeOf(runManagedFeature({ ...plain, store: s.store, barrier: s.barrier })), 'crash');
  assert.equal(s.store.readGroup('form', 'account/quick').pending.completionReserve.bytes, COMPLETION_BASE_BYTES);
});

// A prepared attempt reused under its own token (samePreparedIntent) is sized by today's plan, not the one that prepared
// it: markSending enlarges and admits the reservation before anything is sent, or refuses with the store as it was.
async function reusedWithEstimate(fillerBytes, wanted) {
  const s = await setup();
  committedForm(s, { id: QUICK, key: 'account/filler', publishedXml: '<form/>', savedXml: '<form/>' });
  const p = ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' });
  const intent = await p.plan({});
  s.store.prepareAttempt({ family: p.family, key: p.key, root: intent.root, declarationSha256: intent.declarationSha256, publication: intent.publication, knownScopes: p.knownScopes });
  const initial = s.store.readGroup(p.family, p.key).pending;
  const filler = s.store.readGroup('form', 'account/filler').committed;
  const fill = s.store.prepareAttempt({ family: 'form', key: filler.key, root: filler.root, baseGeneration: filler.generation, declarationSha256: H('e'), knownScopes: [ACCOUNT] });
  s.store.markSending(fill, expected(QUICK));
  s.store.noteSaved(fill, { proof: null, acknowledgedRoot: false });
  s.store.commitGroup({ token: fill, baseGeneration: filler.generation, records: filler.records, proof: filler.proof, consumerState: { ...filler.consumerState, declaration: { ...filler.consumerState.declaration, description: 'z'.repeat(fillerBytes) } }, publication: filler.publication });
  p.plan = async () => ({ ...intent, completionBytes: wanted });
  return { s, p, initial };
}

test('capacity: a changed completion estimate on an otherwise identical prepared plan is honored before dispatch', async () => {
  const { s, p, initial } = await reusedWithEstimate(27 * (1 << 20), 6 * (1 << 20));
  assert.equal(initial.completionReserve.bytes, COMPLETION_BASE_BYTES);
  const before = fs.readFileSync(s.store.file);
  const mark = s.wire.writes().length;
  assert.equal(await codeOf(runManagedFeature({ ...p, store: s.store, barrier: s.barrier, client: s.sdk.dataverse })), CODES.storeFull);
  assert.equal(s.wire.writes().length - mark, 0, 'nothing is sent when the larger estimate cannot be admitted');
  assert.ok(before.equals(fs.readFileSync(s.store.file)), 'the refused enlargement keeps the attempt, its token, its bytes and its hold');
  const kept = s.store.readGroup(p.family, p.key).pending;
  assert.equal(kept.token, initial.token);
  assert.equal(kept.phase, 'prepared');
});

test('capacity: a reused prepared attempt with room takes the larger estimate before its send', async () => {
  const { s, p, initial } = await reusedWithEstimate(1 << 20, 3 * (1 << 20));
  const crash = Object.assign(new Error('the process ended'), { code: 'crash' });
  let held = null;
  p.apply = async () => { held = s.store.readGroup(p.family, p.key).pending.completionReserve.bytes; throw crash; };
  assert.equal(await codeOf(runManagedFeature({ ...p, store: s.store, barrier: s.barrier, client: s.sdk.dataverse })), 'crash');
  assert.equal(held, 3 * (1 << 20), 'the reservation was enlarged before the send');
  assert.equal(s.store.readGroup(p.family, p.key).pending.token, initial.token);
});

test('capacity: a malformed completion estimate is refused on the reuse path, not skipped', async () => {
  for (const wanted of [-1, 1.5, 'big', 64 * (1 << 20)]) {
    const { s, p, initial } = await reusedWithEstimate(0, wanted);
    const before = fs.readFileSync(s.store.file);
    const mark = s.wire.writes().length;
    let refusal = null;
    try { await runManagedFeature({ ...p, store: s.store, barrier: s.barrier, client: s.sdk.dataverse }); } catch (e) { refusal = e; }
    assert.equal(refusal && refusal.code, CODES.notSettled, String(wanted));
    assert.match(refusal.cause.message, /plan `completionBytes`/, 'refused where the plan answered it, before anything is prepared or claimed');
    assert.equal(s.wire.writes().length - mark, 0);
    assert.ok(before.equals(fs.readFileSync(s.store.file)));
    assert.equal(s.store.readGroup(p.family, p.key).pending.token, initial.token);
  }
});

test('two forms on one table, one fails its proof: the other\'s success does not release the table', async () => {
  const s = await setup();
  const bad = ports(s.wire, s.sdk, { key: 'account/quick', id: QUICK, formxml: '<form q="1"/>', fail: { prove: Object.assign(new Error('read back differs'), { code: 'create-completion-required' }) } });
  const good = ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' });
  assert.equal(await codeOf(runManagedFeature({ ...bad, store: s.store, barrier: s.barrier })), 'create-completion-required');
  assert.equal((await runManagedFeature({ ...good, store: s.store, barrier: s.barrier })).result.committed, true);
  const out = await publishForms(s.sdk, s.store, s.barrier, [{ family: 'form', key: 'account/main' }]);
  assert.equal(out.withheld, true);
  await publishTablesXml(s.sdk.dataverse, ['account']);
  assert.equal(s.wire.publishes('account').length, 0);
  assert.equal(s.store.readGroup('form', 'account/main').committed.publication.state, 'owed', 'the debt stays for a later run');
});

test('two dashboards, one fails: the other publishes its own scope, the failed one is never published, nor is an app that holds it', async () => {
  const s = await setup();
  const bad = ports(s.wire, s.sdk, { family: 'dashboard', key: 'sales', id: DASH, formxml: '<form d="1"/>', fail: { prove: Object.assign(new Error('tiles differ'), { code: 'create-completion-required' }) } });
  const good = ports(s.wire, s.sdk, { family: 'dashboard', key: 'service', id: DASH2, formxml: '<form d="2"/>' });
  assert.equal(await codeOf(runManagedFeature({ ...bad, store: s.store, barrier: s.barrier })), 'create-completion-required');
  assert.equal((await runManagedFeature({ ...good, store: s.store, barrier: s.barrier })).result.committed, true);
  assert.equal((await publishDashboard(s.sdk, s.store, s.barrier, 'dashboard', 'service', DASH2)).sent, true);
  assert.equal(s.wire.publishes(DASH2).length, 1);
  await s.sdk.fetchArtifact('dashboard', DASH);
  await s.sdk.publishArtifact('dashboard', DASH);
  assert.equal(s.wire.publishes(DASH).length, 0, 'the failed dashboard is cut from every envelope');
  const verdict = s.barrier.checkAppWrite({ held: new Set(), existingApp: true, heldDashboards: [DASH, DASH2] });
  assert.equal(verdict.ok, false);
  assert.deepEqual(verdict.dashboards, [DASH]);
});

test('a dashboard creation record that is not settled quarantines that dashboard id: no dashboard publish and no app publish of it; an unrelated id still publishes', async () => {
  const s = await setup();
  s.wire.putForm({ formid: UNRELATED, name: 'Other', objecttypecode: 'none', type: 0, formxml: '<form o="1"/>' });
  const p = ports(s.wire, s.sdk, { family: 'dashboard', key: 'sales', id: DASH, formxml: '<form d="1"/>' });
  const realApply = p.apply;
  p.apply = async (...a) => { await realApply(...a); throw Object.assign(new Error('the creation record could not be cleared'), { code: CREATION_RECORD_UNSETTLED }); };
  assert.equal(await codeOf(runManagedFeature({ ...p, store: s.store, barrier: s.barrier })), CREATION_RECORD_UNSETTLED);
  await s.sdk.fetchArtifact('dashboard', DASH);
  await s.sdk.publishArtifact('dashboard', DASH);
  assert.equal(s.wire.publishes(DASH).length, 0);
  assert.equal(s.barrier.checkAppWrite({ held: new Set(), existingApp: true, addedDashboards: [DASH] }).ok, false, 'no app write that adds it');
  assert.equal(s.barrier.checkAppWrite({ held: new Set(), existingApp: true, heldDashboards: [] }).ok, true, 'an app that does not hold it may publish');
  await s.sdk.fetchArtifact('dashboard', UNRELATED);
  await s.sdk.publishArtifact('dashboard', UNRELATED);
  assert.equal(s.wire.publishes(UNRELATED).length, 1);
});

test('a run that omits the declaration of a form whose publish answer was lost publishes nothing that overlaps it', async () => {
  const one = await setup();
  await runManagedFeature({ ...ports(one.wire, one.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: one.store, barrier: one.barrier });
  one.wire.script((e) => /PublishXml/.test(e.path), { error: 'socket hang up', code: 'ECONNRESET' });
  assert.equal(await codeOf(publishForms(one.sdk, one.store, one.barrier, [{ family: 'form', key: 'account/main' }])), PUBLICATION_UNCONFIRMED);
  const sent = one.wire.publishes('account').length;

  // Process two: the spec no longer declares the form. Discovery alone withholds what the store says is uncertain.
  const barrier = createPublicationBarrier();
  context(one.dir, barrier);
  const { sdk } = await sdkOver(one.wire, { barrier });
  await publishTablesXml(sdk.dataverse, ['account', 'contact']);
  await sdk.fetchArtifact('form', MAIN);
  await sdk.publishArtifact('form', MAIN);
  assert.equal(one.wire.publishes('account').length, sent, 'zero overlapping sends');
  assert.equal(one.wire.publishes('contact').length, 1, 'the unrelated table still publishes');
  assert.equal(barrier.checkAppWrite({ held: new Set(['account']), existingApp: true }).ok, false);
});

test('no store keeps the build\'s requests exactly; a corrupt store stops before any publish', async () => {
  const run = async (withContext) => {
    const wire = createManagedWire();
    const barrier = createPublicationBarrier();
    const dir = makeTempDir('mp-parity-');
    if (withContext) {
      const c = context(dir, barrier);
      assert.equal(c.absent, true);
      assert.deepEqual(fs.readdirSync(dir), []);
    }
    const { sdk } = await sdkOver(wire, { barrier });
    wire.putForm({ formid: MAIN, name: 'Main', objecttypecode: 'account', type: 2, formxml: '<form/>' });
    await publishTablesXml(sdk.dataverse, ['account']);
    await sdk.fetchArtifact('form', MAIN);
    await sdk.publishArtifact('form', MAIN);
    return wire.log.map((e) => `${e.method} ${e.url} ${JSON.stringify(e.body)}`);
  };
  assert.deepEqual(await run(true), await run(false));

  const dir = makeTempDir('mp-corrupt-');
  const s = openManagedBindings({ workspaceDir: dir, environment: ENV, appUniqueName: APP, solutionUniqueName: SOL });
  const t = s.prepareAttempt({ family: 'form', key: 'account/main', baseGeneration: null, root: { kind: 'form', key: 'account/main', id: MAIN }, knownScopes: [ACCOUNT], declarationSha256: H('e') });
  assert.ok(t);
  fs.writeFileSync(s.file, fs.readFileSync(s.file, 'utf8').slice(0, -3));
  const barrier = createPublicationBarrier();
  let code = null;
  try { context(dir, barrier); } catch (e) { code = e.code; }
  assert.equal(code, CODES.unreadable, 'the build stops: nothing it would publish next is trusted');
});

test('the systemform reader: equal, differing and never-published layers; every other answer is unverified', async () => {
  const wire = createManagedWire();
  const { sdk } = await sdkOver(wire);
  wire.putForm({ formid: MAIN, name: 'Main', objecttypecode: 'account', type: 2, formxml: '<form/>' }, { publishedToo: true });
  assert.equal((await readSystemFormPublication(sdk.dataverse, MAIN.toUpperCase())).state, 'equal');
  wire.saved.get(MAIN).description = 'changed';
  assert.equal((await readSystemFormPublication(sdk.dataverse, MAIN)).state, 'differs');
  wire.putForm({ formid: DASH, name: 'Sales', objecttypecode: 'none', type: 0, formxml: '<form/>' });
  const never = await readSystemFormPublication(sdk.dataverse, DASH);
  assert.deepEqual([never.state, never.published], ['never-published', null]);

  const unverified = async (answer, saved = false) => {
    wire.script((e) => e.method === 'GET' && /systemforms/.test(e.path) && (saved === /RetrieveUnpublished/.test(e.path)), answer);
    return codeOf(readSystemFormPublication(sdk.dataverse, MAIN));
  };
  assert.equal(await unverified({ statusCode: 404, body: { error: { code: '0x80040216', message: 'other' } } }), PUBLICATION_UNVERIFIED, 'a 404 for another reason');
  assert.equal(await unverified({ statusCode: 403, body: { error: { code: '0x80040220' } } }), PUBLICATION_UNVERIFIED);
  assert.equal(await unverified({ statusCode: 200, body: { formid: QUICK, name: 'Main', formxml: '<form/>' } }), PUBLICATION_UNVERIFIED, 'another row');
  assert.equal(await unverified({ statusCode: 200, body: { formid: MAIN, name: 'Main' } }), PUBLICATION_UNVERIFIED, 'no form XML');
  assert.equal(await unverified({ statusCode: 404, body: { error: { code: '0x80040217' } } }, true), PUBLICATION_UNVERIFIED, 'a saved layer that is missing is not "never published"');
  assert.equal(await codeOf(readSystemFormPublication(sdk.dataverse, 'not-a-guid')), PUBLICATION_UNVERIFIED);
  assert.equal(await codeOf(readSystemFormPublication({ get: async () => { throw new Error('reset'); } }, MAIN)), PUBLICATION_UNVERIFIED);
});

test('a form whose row has no description: the hash its feature records from the row is the hash the shared reader answers, so its debt is paid; empty text stays distinct', async () => {
  const owe = (s, desiredSha256) => {
    const t = s.store.prepareAttempt({ family: 'form', key: 'account/main', baseGeneration: null, root: { kind: 'form', key: 'account/main', id: MAIN }, knownScopes: [ACCOUNT], declarationSha256: H('e'), publication: { scope: ACCOUNT, state: 'owed' } });
    s.store.markSending(t, expected(MAIN));
    s.store.noteSaved(t, { proof: null, acknowledgedRoot: true });
    s.store.commitGroup({ token: t, baseGeneration: null, records: [rec('form', 'account/main', MAIN)], proof: PROOF, consumerState: consumer('form'), publication: { scope: ACCOUNT, state: 'owed', desiredSha256, dispatchToken: null } });
  };
  // The row as the feature declares it: no description key at all. The service answers it with description null.
  const declared = { name: 'Main', formxml: '<form v="2"/>' };
  const s = await setup();
  s.wire.putForm({ formid: MAIN, name: 'Main', objecttypecode: 'account', type: 2, formxml: '<form v="1"/>' }, { publishedToo: true });
  s.wire.saved.get(MAIN).formxml = declared.formxml;
  owe(s, systemFormLayerSha256(declared));
  assert.deepEqual(await publishForms(s.sdk, s.store, s.barrier, [{ family: 'form', key: 'account/main' }]), { sent: true, withheld: false, confirmed: [{ family: 'form', key: 'account/main' }] });
  assert.equal(s.wire.publishes('account').length, 1);
  assert.equal(s.store.readGroup('form', 'account/main').committed.publication.state, 'confirmed');
  assert.equal(systemFormLayerSha256(declared), systemFormLayerSha256({ ...declared, description: null }));

  // Control: a declared empty description is not the service's null, so that saved layer is not the owed one.
  const c = await setup();
  c.wire.putForm({ formid: MAIN, name: 'Main', objecttypecode: 'account', type: 2, formxml: '<form v="1"/>' }, { publishedToo: true });
  c.wire.saved.get(MAIN).formxml = declared.formxml;
  owe(c, systemFormLayerSha256({ ...declared, description: '' }));
  assert.equal(await codeOf(publishForms(c.sdk, c.store, c.barrier, [{ family: 'form', key: 'account/main' }])), CODES.completion);
  assert.equal(c.wire.publishes().length, 0);
});

// A managed form CREATED under its own stable id over the wire (POST systemforms {formid}), whose declaration is its
// form XML: the expected proof and the declaration hash both follow it, so a changed declaration is a different plan.
// `resumeCreate` reads the root in both layers by that id. A create whose answer was lost is adopted by the proof.
const isCreate = (e) => e.method === 'POST' && /^systemforms$/i.test(e.path);
function createPorts(wire, sdk, { key, id, formxml }) {
  const p = ports(wire, sdk, { key, id, formxml });
  const exp = { ...expected(id), sentProjectionSha256: sha({ formxml }) };
  p.tokens = [];
  p.resumeAsked = 0;
  p.plan = async () => {
    const current = wire.saved.get(id);
    if (current && current.formxml === formxml) return { noop: true };
    return { root: { kind: 'form', key, id }, expected: exp, declarationSha256: sha({ key, formxml }), publication: { scope: ACCOUNT, state: 'owed' } };
  };
  p.apply = async ({ token }) => {
    p.tokens.push(token);
    const res = await sdk.dataverse.post('/systemforms', { formid: id, name: key, objecttypecode: 'account', type: 2, formxml });
    if (!(res.status >= 200 && res.status < 300)) throw Object.assign(new Error(`the create answered ${res.status}`), { code: 'create-refused' });
    return { sent: true };
  };
  const prove = p.prove;
  p.prove = async (a) => {
    const proved = await prove(a);
    // A recovered create was never acknowledged in this attempt: its root is adopted, not claimed as created.
    return a.recovering ? { ...proved, records: proved.records.map((r) => ({ ...r, origin: 'adopted' })) } : proved;
  };
  p.resumeCreate = async () => { p.resumeAsked += 1; return { root: await readSystemFormRootPresence(sdk.dataverse, id) }; };
  return p;
}
const refuseNextCreate = (wire) => wire.script(isCreate, { statusCode: 400, body: { error: { code: '0x80040203', message: 'refused' } }, unapplied: true });
// A fresh process over the same workspace and wire.
async function nextRun(s) {
  const barrier = createPublicationBarrier();
  const c = context(s.dir, barrier);
  const { sdk } = await sdkOver(s.wire, { barrier });
  return { barrier, store: c.store, debt: c.debt, sdk };
}

test('a create the service refused is resumed in the next run under its own token and id: exactly one more create, then one publish', async () => {
  const s = await setup();
  const first = createPorts(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' });
  refuseNextCreate(s.wire);
  assert.equal(await codeOf(runManagedFeature({ ...first, store: s.store, barrier: s.barrier })), 'create-refused');
  assert.equal(s.wire.log.filter(isCreate).length, 1);
  const stranded = s.store.readGroup('form', 'account/main').pending;
  assert.equal(stranded.phase, 'sending');

  const n = await nextRun(s);
  assert.deepEqual(n.debt.map((d) => d.kind), ['hold']);
  const again = createPorts(s.wire, n.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' });
  const r = await runManagedFeature({ ...again, store: n.store, barrier: n.barrier });
  assert.deepEqual(r.result, { committed: true, recovered: true, resumed: true });
  assert.equal(again.resumeAsked, 1);
  assert.deepEqual(again.tokens, [stranded.token], 'the same create, under the attempt\'s own token');
  assert.equal(s.wire.log.filter(isCreate).length, 2, 'exactly one more create');
  assert.deepEqual([...s.wire.saved.keys()], [MAIN], 'one root, under its stable id');
  assert.equal(n.store.readGroup('form', 'account/main').committed.root.id, MAIN);
  assert.equal(n.barrier.active, false, 'the resumed attempt released its own hold');
  assert.equal((await publishForms(n.sdk, n.store, n.barrier, [{ family: 'form', key: 'account/main' }])).sent, true);
  assert.equal(s.wire.publishes('account').length, 1);

  const third = await nextRun(s);
  assert.deepEqual((await runManagedFeature({ ...createPorts(s.wire, third.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: third.store, barrier: third.barrier })).result, { noop: true });
  assert.equal(s.wire.log.filter(isCreate).length, 2, 'the identical next run creates nothing');
});

test('a create whose root is present is proved and adopted, never resent; a late first create makes the resend fail on the primary key, never a second root', async () => {
  // The service made the row and the answer was lost.
  const s = await setup();
  s.wire.script(isCreate, { statusCode: 400, body: { error: { code: '0x80040203', message: 'lost' } } });
  assert.equal(await codeOf(runManagedFeature({ ...createPorts(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: s.store, barrier: s.barrier })), 'create-refused');
  const n = await nextRun(s);
  const p = createPorts(s.wire, n.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' });
  assert.deepEqual((await runManagedFeature({ ...p, adoptionApproved: true, store: n.store, barrier: n.barrier })).result, { committed: true, recovered: true });
  assert.deepEqual([p.resumeAsked, p.tokens.length, s.wire.log.filter(isCreate).length], [1, 0, 1]);
  assert.equal(n.store.readGroup('form', 'account/main').committed.records[0].origin, 'adopted');

  // The first create is delayed: the read finds no root, and the create lands before the resend reaches the service.
  const d = await setup();
  refuseNextCreate(d.wire);
  await codeOf(runManagedFeature({ ...createPorts(d.wire, d.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: d.store, barrier: d.barrier }));
  const late = await nextRun(d);
  const q = createPorts(d.wire, late.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' });
  const send = q.apply;
  q.apply = async (a) => { d.wire.putForm({ formid: MAIN, name: 'account/main', objecttypecode: 'account', type: 2, formxml: '<form v="1"/>' }); return send(a); };
  assert.equal(await codeOf(runManagedFeature({ ...q, store: late.store, barrier: late.barrier })), 'create-refused');
  assert.equal(d.wire.log.filter(isCreate).length, 2);
  assert.deepEqual([...d.wire.saved.keys()], [MAIN], 'the resend failed on the primary key: one root');
  assert.equal(late.store.readGroup('form', 'account/main').pending.token, q.tokens[0], 'the attempt stays, under its token');
  assert.equal(late.barrier.allowScope(ACCOUNT, 'a sibling'), false, 'and its hold stays');
  const after = await nextRun(d);
  const r = createPorts(d.wire, after.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' });
  assert.deepEqual((await runManagedFeature({ ...r, adoptionApproved: true, store: after.store, barrier: after.barrier })).result, { committed: true, recovered: true });
  assert.equal(d.wire.log.filter(isCreate).length, 2, 'proved, not resent');
});

test('a create is not resumed when its declaration changed, when its root cannot be read, or when it was not a create', async () => {
  const strand = async () => {
    const s = await setup();
    refuseNextCreate(s.wire);
    await codeOf(runManagedFeature({ ...createPorts(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: s.store, barrier: s.barrier }));
    return s;
  };
  // A changed declaration is a new change: refused before anything is sent, and the scope is quarantined.
  const s = await strand();
  const n = await nextRun(s);
  const changed = createPorts(s.wire, n.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' });
  assert.equal(await codeOf(runManagedFeature({ ...changed, store: n.store, barrier: n.barrier })), 'create-completion-required');
  assert.deepEqual([changed.tokens.length, s.wire.log.filter(isCreate).length], [0, 1]);
  assert.equal(n.store.readGroup('form', 'account/main').pending.phase, 'sending', 'the attempt is kept as it was');
  assert.deepEqual(n.barrier.withheld().map((w) => w.blockedBy.length > 0), [true], 'quarantined for the run');

  // A presence read that is not a "does not exist" from both layers sends nothing.
  const u = await strand();
  const m = await nextRun(u);
  u.wire.script((e) => e.method === 'GET' && /systemforms/.test(e.path) && !/RetrieveUnpublished/.test(e.path), { statusCode: 403, body: { error: { code: '0x80040220' } } });
  const blind = createPorts(u.wire, m.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' });
  assert.equal(await codeOf(runManagedFeature({ ...blind, store: m.store, barrier: m.barrier })), PUBLICATION_UNVERIFIED);
  assert.deepEqual([blind.tokens.length, u.wire.log.filter(isCreate).length], [0, 1]);
  assert.equal(m.barrier.allowScope(ACCOUNT, 'a sibling'), false);

  // An edit of a committed form whose send was refused is never resumed: the proof decides, as before.
  const e = await setup();
  await runManagedFeature({ ...ports(e.wire, e.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: e.store, barrier: e.barrier });
  e.wire.script((x) => x.method === 'PATCH', { statusCode: 400, body: { error: { code: '0x80040203' } }, unapplied: true });
  await codeOf(runManagedFeature({ ...ports(e.wire, e.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' }), store: e.store, barrier: e.barrier }));
  const k = await nextRun(e);
  const edit = { ...ports(e.wire, k.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' }), resumeCreate: async () => { throw new Error('never asked'); } };
  assert.equal(await codeOf(runManagedFeature({ ...edit, store: k.store, barrier: k.barrier })), 'create-completion-required');
  assert.equal(e.wire.writes().filter((x) => x.method === 'PATCH').length, 1, 'no second edit');
});

test('the systemform presence read: absent only when both layers say the row does not exist', async () => {
  const wire = createManagedWire();
  const { sdk } = await sdkOver(wire);
  assert.equal(await readSystemFormRootPresence(sdk.dataverse, MAIN), 'absent');
  wire.putForm({ formid: MAIN, name: 'Main', objecttypecode: 'account', type: 2, formxml: '<form/>' });
  assert.equal(await readSystemFormRootPresence(sdk.dataverse, MAIN.toUpperCase()), 'present', 'saved only, never published');
  const unverified = async (answer, saved) => {
    wire.script((e) => e.method === 'GET' && /systemforms/.test(e.path) && saved === /RetrieveUnpublished/.test(e.path), answer);
    return codeOf(readSystemFormRootPresence(sdk.dataverse, DASH));
  };
  assert.equal(await unverified({ statusCode: 404, body: { error: { code: '0x80040216' } } }, true), PUBLICATION_UNVERIFIED, 'a 404 for another reason');
  assert.equal(await unverified({ statusCode: 403, body: { error: { code: '0x80040220' } } }, false), PUBLICATION_UNVERIFIED);
  assert.equal(await unverified({ statusCode: 200, body: { formid: QUICK, name: 'x', formxml: '<form/>' } }, true), PUBLICATION_UNVERIFIED, 'another row');
  assert.equal(await codeOf(readSystemFormRootPresence({ get: async () => { throw new Error('reset'); } }, MAIN)), PUBLICATION_UNVERIFIED);
  assert.equal(await codeOf(readSystemFormRootPresence(sdk.dataverse, 'not-a-guid')), PUBLICATION_UNVERIFIED);
});

test('a prepared attempt that never reached the send is retired by a no-op plan: its hold ends, nothing is written', async () => {
  const s = await setup();
  s.wire.putForm({ formid: MAIN, name: 'Main', objecttypecode: 'account', type: 2, formxml: '<form v="1"/>' }, { publishedToo: true });
  // A run that stopped after prepareAttempt, before markSending: intent only.
  s.store.prepareAttempt({ family: 'form', key: 'account/main', baseGeneration: null, root: { kind: 'form', key: 'account/main', id: MAIN }, knownScopes: [ACCOUNT], declarationSha256: H('e'), publication: { scope: ACCOUNT, state: 'owed' } });
  const n = await nextRun(s);
  assert.deepEqual(n.debt.map((d) => d.kind), ['hold']);
  const r = await runManagedFeature({ ...ports(s.wire, n.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: n.store, barrier: n.barrier });
  assert.deepEqual(r.result, { noop: true });
  assert.equal(n.store.readGroup('form', 'account/main').pending, null);
  assert.equal(n.barrier.active, false, 'its own hold ended');
  assert.deepEqual(s.wire.writes(), []);
  assert.deepEqual((await nextRun(s)).debt, [], 'the next run finds nothing pending');
});

test('a publish that landed and whose answer was lost is confirmed read-only by the next run: no second publish, and the run after finds nothing owed', async () => {
  const s = await setup();
  await runManagedFeature({ ...ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: s.store, barrier: s.barrier });
  s.wire.script((e) => /PublishXml/.test(e.path), { statusCode: 503, body: { error: { code: '0x80040216', message: 'gateway' } } });
  assert.equal(await codeOf(publishForms(s.sdk, s.store, s.barrier, [{ family: 'form', key: 'account/main' }])), PUBLICATION_UNCONFIRMED);
  assert.equal(s.wire.publishes('account').length, 1);
  assert.equal(s.wire.published.get(MAIN).formxml, '<form v="1"/>', 'it landed');

  const n = await nextRun(s);
  assert.deepEqual(n.debt.map((d) => d.kind), ['uncertain']);
  const token = n.store.readGroup('form', 'account/main').committed.publication.dispatchToken;
  assert.deepEqual(await publishForms(n.sdk, n.store, n.barrier, [{ family: 'form', key: 'account/main' }]), { sent: false, withheld: false, confirmed: [{ family: 'form', key: 'account/main' }] });
  const pub = n.store.readGroup('form', 'account/main').committed.publication;
  assert.deepEqual([pub.state, pub.dispatchToken], ['confirmed', token], 'confirmed under its original dispatch');
  assert.equal(s.wire.publishes().length, 1, 'nothing was sent');
  assert.equal(n.barrier.allowScope(ACCOUNT, 'a sibling'), false, 'the quarantine of this run is never cleared');
  assert.deepEqual((await nextRun(s)).debt, [], 'the next run installs no block');
});

test('an uncertain publication that a fresh read does not prove stays blocked: nothing is sent, replayed or deleted; one dispatch is confirmed whole or not at all', async () => {
  const s = await setup();
  await runManagedFeature({ ...ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: s.store, barrier: s.barrier });
  await runManagedFeature({ ...ports(s.wire, s.sdk, { key: 'account/quick', id: QUICK, formxml: '<form q="1"/>' }), store: s.store, barrier: s.barrier });
  const both = [{ family: 'form', key: 'account/main' }, { family: 'form', key: 'account/quick' }];
  s.wire.script((e) => /PublishXml/.test(e.path), { statusCode: 503, body: { error: { code: '0x80040216', message: 'gateway' } } });
  assert.equal(await codeOf(publishForms(s.sdk, s.store, s.barrier, both)), PUBLICATION_UNCONFIRMED);
  // One form of the dispatch is live; the other's published layer is not what was owed.
  const live = s.wire.published.get(QUICK);
  s.wire.published.set(QUICK, { ...live, formxml: '<form q="0"/>' });

  const n = await nextRun(s);
  const states = (st) => both.map(({ family, key }) => st.readGroup(family, key).committed.publication.state);
  const answer = await confirmUncertainPublication({ store: n.store, barrier: n.barrier, scope: ACCOUNT, client: n.sdk.dataverse });
  assert.deepEqual(answer, { confirmed: [], unconfirmed: both.map((g) => ({ ...g, code: PUBLICATION_UNCONFIRMED })) });
  assert.deepEqual(states(n.store), ['unconfirmed', 'unconfirmed'], 'the live one is not confirmed without its sibling');
  assert.equal(await codeOf(publishForms(n.sdk, n.store, n.barrier, both)), PUBLICATION_UNCONFIRMED);
  const failing = { ...require('../lib/managed-layer-readers.js').LAYER_READERS, form: async () => { throw new Error('reset'); } };
  assert.deepEqual((await confirmUncertainPublication({ store: n.store, barrier: n.barrier, scope: ACCOUNT, client: n.sdk.dataverse, readers: failing })).unconfirmed.map((u) => u.code), [PUBLICATION_UNVERIFIED, PUBLICATION_UNVERIFIED]);
  assert.deepEqual((await confirmUncertainPublication({ store: n.store, barrier: n.barrier, scope: ACCOUNT, client: n.sdk.dataverse, readers: {} })).unconfirmed.map((u) => u.code), [LAYER_READER_MISSING, LAYER_READER_MISSING]);
  assert.equal(s.wire.publishes().length, 1, 'nothing was sent again');
  assert.equal(s.wire.writes().filter((w) => !/PublishXml/.test(w.path)).length, 0, 'nothing was written');

  // The whole dispatch is live: one write confirms both.
  s.wire.published.set(QUICK, live);
  const m = await nextRun(s);
  assert.deepEqual(await confirmUncertainPublication({ store: m.store, barrier: m.barrier, scope: ACCOUNT, client: m.sdk.dataverse }), { confirmed: both, unconfirmed: [] });
  assert.deepEqual(states(m.store), ['confirmed', 'confirmed']);
  assert.equal(s.wire.publishes().length, 1);
});

// The same-token continuation of recoverManagedAttempt. A build whose transport carries a send observer
// (createAttemptSendObserver, inside the barrier's gate as build-model-app.js installs it) records on the attempt every
// mutation its apply sends, before it leaves. An attempt that failed with nothing carried out — a local edit that failed
// before any request, or a request the service refused unapplied — is then continued by the next run under its own
// token; anything that may have landed is only proved, as before.
async function observedRun(s) {
  const barrier = createPublicationBarrier();
  const observer = createAttemptSendObserver();
  const { sdk } = await sdkOver(s.wire, { barrier, observer });
  const c = context(s.dir, barrier);
  return { barrier, observer, sdk, store: c.store, debt: c.debt };
}
async function observedSetup() {
  const s = { wire: createManagedWire(), dir: makeTempDir('mp-observed-') };
  return Object.assign(s, await observedRun(s));
}
const isPatch = (e) => e.method === 'PATCH' && /^systemforms\(/i.test(e.path);
// The edit of a managed form, as the forms helper sends it: the service's answer decides, and a refusal is the
// feature's own error. `local` makes the apply fail before it sends anything (a local SDK edit that failed).
function editPorts(wire, sdk, { formxml, local = null }) {
  const p = ports(wire, sdk, { key: 'account/main', id: MAIN, formxml });
  p.sends = [];
  p.apply = async ({ token, continuing }) => {
    p.sends.push([token, continuing === true]);
    if (local) throw local;
    const res = await sdk.dataverse.patch(`/systemforms(${MAIN})`, { formxml });
    if (!(res.status >= 200 && res.status < 300)) throw Object.assign(new Error(`the edit answered ${res.status}`), { code: 'form-layout-rejected' });
    return { sent: true };
  };
  return p;
}
const localFailure = () => Object.assign(new Error('the local copy could not be edited'), { code: 'form-layout-local-edit' });
const observed = (p, n) => ({ ...p, store: n.store, barrier: n.barrier, sendObserver: n.observer });
async function committedEdit(s) {
  await runManagedFeature(observed(ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), s));
  return s.store.readGroup('form', 'account/main').committed;
}

test('an edit that failed locally before any request is continued by the next run under its own token: one edit, then committed', async () => {
  const s = await observedSetup();
  const base = await committedEdit(s);
  const first = editPorts(s.wire, s.sdk, { formxml: '<form v="2"/>', local: localFailure() });
  assert.equal(await codeOf(runManagedFeature(observed(first, s))), 'form-layout-local-edit');
  assert.deepEqual(s.wire.writes(), [], 'nothing reached the service');
  const stranded = s.store.readGroup('form', 'account/main').pending;
  assert.deepEqual([stranded.phase, stranded.sendWindow], ['sending', { possible: 0, notStarted: 0, epoch: 1 }]);

  const n = await observedRun(s);
  assert.deepEqual(n.debt.map((d) => d.kind), ['hold']);
  const again = editPorts(s.wire, n.sdk, { formxml: '<form v="2"/>' });
  assert.deepEqual((await runManagedFeature(observed(again, n))).result, { committed: true, recovered: true, continued: true });
  assert.deepEqual(again.sends, [[stranded.token, true]], 'the same attempt, continued under its own token');
  assert.equal(s.wire.writes().filter(isPatch).length, 1, 'exactly one edit');
  const { committed, pending } = n.store.readGroup('form', 'account/main');
  assert.equal(pending, null);
  assert.notEqual(committed.generation, base.generation);
  assert.equal(s.wire.saved.get(MAIN).formxml, '<form v="2"/>');
  assert.equal(n.barrier.active, false, 'its own hold ended');
  const t = await observedRun(s);
  assert.deepEqual((await runManagedFeature(observed(editPorts(s.wire, t.sdk, { formxml: '<form v="2"/>' }), t))).result, { noop: true });

  // A create that failed locally is continued the same way: one create under its stable id, no presence read needed.
  const c = await observedSetup();
  const create = createPorts(c.wire, c.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' });
  create.apply = async () => { throw localFailure(); };
  assert.equal(await codeOf(runManagedFeature(observed(create, c))), 'form-layout-local-edit');
  const m = await observedRun(c);
  const resent = createPorts(c.wire, m.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' });
  assert.deepEqual((await runManagedFeature(observed(resent, m))).result, { committed: true, recovered: true, continued: true });
  assert.deepEqual([resent.resumeAsked, c.wire.log.filter(isCreate).length], [0, 1]);
  assert.deepEqual([...c.wire.saved.keys()], [MAIN]);
});

test('an edit the service refused unapplied with a Dataverse error is continued by the next run: one more edit, then committed', async () => {
  const s = await observedSetup();
  await committedEdit(s);
  s.wire.script(isPatch, { statusCode: 400, body: { error: { code: '0x80040203', message: 'refused' } }, unapplied: true });
  const first = editPorts(s.wire, s.sdk, { formxml: '<form v="2"/>' });
  assert.equal(await codeOf(runManagedFeature(observed(first, s))), 'form-layout-rejected');
  assert.deepEqual(s.store.readGroup('form', 'account/main').pending.sendWindow, { possible: 0, notStarted: 1, epoch: 1 });

  const n = await observedRun(s);
  const again = editPorts(s.wire, n.sdk, { formxml: '<form v="2"/>' });
  assert.deepEqual((await runManagedFeature(observed(again, n))).result, { committed: true, recovered: true, continued: true });
  assert.deepEqual(again.sends, [[first.sends[0][0], true]]);
  assert.equal(s.wire.writes().filter(isPatch).length, 2, 'the refused edit and its one continuation');
  assert.equal(s.wire.saved.get(MAIN).formxml, '<form v="2"/>');
  assert.equal(n.store.readGroup('form', 'account/main').pending, null);
});

test('an answer that does not prove the edit was not carried out leaves the attempt possibly sent: the next run only proves it', async () => {
  const strand = async (unapplied) => {
    const s = await observedSetup();
    await committedEdit(s);
    // A 400 with no Dataverse error (a proxy's page): nothing says the platform refused the operation.
    s.wire.script(isPatch, { statusCode: 400, body: '<html>bad gateway</html>', unapplied });
    assert.equal(await codeOf(runManagedFeature(observed(editPorts(s.wire, s.sdk, { formxml: '<form v="2"/>' }), s))), 'form-layout-rejected');
    assert.deepEqual(s.store.readGroup('form', 'account/main').pending.sendWindow, { possible: 1, notStarted: 0, epoch: 1 });
    return s;
  };
  // It landed: proved and committed, never sent again.
  const landed = await strand(false);
  const n = await observedRun(landed);
  const p = editPorts(landed.wire, n.sdk, { formxml: '<form v="2"/>' });
  assert.deepEqual((await runManagedFeature(observed(p, n))).result, { committed: true, recovered: true });
  assert.deepEqual([p.sends.length, landed.wire.writes().filter(isPatch).length], [0, 1]);

  // It did not land: the proof fails, nothing is sent, and the attempt stays under its token.
  const lost = await strand(true);
  const token = lost.store.readGroup('form', 'account/main').pending.token;
  const m = await observedRun(lost);
  const q = editPorts(lost.wire, m.sdk, { formxml: '<form v="2"/>' });
  assert.equal(await codeOf(runManagedFeature(observed(q, m))), 'create-completion-required');
  assert.deepEqual([q.sends.length, lost.wire.writes().filter(isPatch).length], [0, 1]);
  assert.equal(m.store.readGroup('form', 'account/main').pending.token, token);
  assert.equal(m.barrier.allowScope(ACCOUNT, 'a sibling'), false);
});

test('a proven-unsent attempt is not continued when its declaration changed, or by a run that does not observe its sends', async () => {
  const strand = async () => {
    const s = await observedSetup();
    const p = createPorts(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' });
    p.apply = async () => { throw localFailure(); };
    await codeOf(runManagedFeature(observed(p, s)));
    return s;
  };
  const s = await strand();
  const n = await observedRun(s);
  const changed = createPorts(s.wire, n.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' });
  assert.equal(await codeOf(runManagedFeature(observed(changed, n))), 'create-completion-required');
  assert.deepEqual([changed.tokens.length, s.wire.writes().length], [0, 0]);
  assert.equal(n.store.readGroup('form', 'account/main').pending.phase, 'sending', 'the attempt is kept as it was');
  assert.deepEqual(n.barrier.withheld().map((w) => w.blockedBy.length > 0), [true], 'quarantined for the run');

  // Without an observer the window is not trusted: only resumeCreate's presence read or the proof decide, as before.
  const u = await strand();
  const m = await nextRun(u);
  const plain = createPorts(u.wire, m.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' });
  assert.deepEqual((await runManagedFeature({ ...plain, store: m.store, barrier: m.barrier })).result, { committed: true, recovered: true, resumed: true });
  assert.equal(plain.resumeAsked, 1);
});

test('the send observer counts a mutation on its attempt before it leaves, only inside a window, and never a publish the barrier withholds', async () => {
  const dir = makeTempDir('mp-observer-');
  const barrier = createPublicationBarrier();
  const { store } = context(dir, barrier);
  const token = store.prepareAttempt({ family: 'form', key: 'account/main', baseGeneration: null, root: { kind: 'form', key: 'account/main', id: MAIN }, knownScopes: [ACCOUNT], declarationSha256: H('e'), publication: { scope: ACCOUNT, state: 'owed' } });
  store.markSending(token, expected(MAIN), { observed: true });
  const windowOf = () => store.readGroup('form', 'account/main').pending.sendWindow;
  const seen = [];
  let answer = { statusCode: 204, headers: {}, body: '' };
  const inner = async (req) => { seen.push([req.method, windowOf().possible]); if (answer instanceof Error) throw answer; return answer; };
  const observer = createAttemptSendObserver();
  assert.equal(observer.installed, false);
  // A wrapper given an observer that is on no transport refuses before it reads or writes anything.
  const before = fs.readFileSync(store.file, 'utf8');
  assert.equal(await codeOf(runManagedFeature({ ...ports(createManagedWire(), null, { key: 'account/other', id: QUICK, formxml: '<form/>' }), store, barrier, sendObserver: observer })), CODES.notSettled);
  assert.equal(fs.readFileSync(store.file, 'utf8'), before);

  const send = barrier.gateRequest(observer.wrap(inner));
  const req = (method, p = `systemforms(${MAIN})`, body = '{}', headers = {}) => send({ url: `${ENV}/api/data/v9.2/${p}`, method, headers, body });
  await req('PATCH');
  assert.deepEqual(windowOf(), { possible: 0, notStarted: 0, epoch: 1 }, 'no window open: not counted');
  const w = observer.open(store, token);
  await req('GET');
  await req('PATCH');
  answer = { statusCode: 400, headers: {}, body: JSON.stringify({ error: { code: '0x80040203', message: 'refused' } }) };
  await req('POST', 'systemforms');
  answer = new Error('socket hang up');
  await assert.rejects(req('DELETE'));
  barrier.hold(token, [ACCOUNT], [MAIN], 'form main');
  answer = { statusCode: 204, headers: {}, body: '' };
  await req('POST', 'PublishXml', JSON.stringify({ ParameterXml: '<importexportxml><entities><entity>account</entity></entities></importexportxml>' }));
  assert.deepEqual(windowOf(), { possible: 2, notStarted: 1, epoch: 1 }, 'a lost answer stays possibly applied');
  // A closed window trails: it still counts every mutation (a re-send, a request left in flight) and records no
  // not-started answer, so it can only grow. Only end() stops it.
  w.close();
  answer = { statusCode: 400, headers: {}, body: JSON.stringify({ error: { code: '0x80040203', message: 'refused' } }) };
  await req('PATCH');
  assert.deepEqual(windowOf(), { possible: 3, notStarted: 1, epoch: 1 }, 'counted after close, and its refusal ends nothing');
  w.end();
  answer = { statusCode: 204, headers: {}, body: '' };
  await req('PATCH');
  assert.deepEqual(seen, [['PATCH', 0], ['GET', 0], ['PATCH', 1], ['POST', 2], ['DELETE', 2], ['PATCH', 3], ['PATCH', 3]], 'counted before it left; the withheld publish never reached the transport');
  assert.deepEqual(windowOf(), { possible: 3, notStarted: 1, epoch: 1 }, 'an ended window counts nothing');

  // A count that cannot be written stops the request before it leaves.
  const broken = { noteAttemptDispatch: () => { throw Object.assign(new Error('disk full'), { code: CODES.writeFailed }); }, noteAttemptNotStarted() {} };
  const w2 = observer.open(broken, token);
  await assert.rejects(req('PATCH'), { code: CODES.writeFailed });
  w2.end();
  assert.equal(seen.length, 7);
});

test('a not-started answer is a Dataverse refusal of one operation or a failed If-Match; nothing else', () => {
  const at = (p, headers = {}) => ({ url: `${ENV}/api/data/v9.2/${p}`, method: 'PATCH', headers });
  const coded = (statusCode, code = '0x80040203') => ({ statusCode, headers: {}, body: JSON.stringify({ error: { code, message: 'x' } }) });
  const row = at(`systemforms(${MAIN})`);
  assert.equal(notStartedAnswer(row, coded(400)), true);
  assert.equal(notStartedAnswer(row, { ...coded(404, '0x80040217'), body: Buffer.from(coded(404, '0x80040217').body) }), true);
  assert.equal(notStartedAnswer(at(`systemforms(${MAIN})`, { 'If-Match': '"7"' }), { statusCode: 412, headers: {}, body: '' }), true);
  for (const [label, req, res] of [
    ['a 412 without If-Match or a code', row, { statusCode: 412, headers: {}, body: '' }],
    ['a 400 without a Dataverse code', row, { statusCode: 400, headers: {}, body: '<html/>' }],
    ['a code that is not one', row, coded(400, 'BadRequest')],
    ['a 409', row, coded(409)],
    ['a 429', row, coded(429)],
    ['a 503', row, coded(503)],
    ['a 401: the client sends it again with a fresh token', row, { statusCode: 401, headers: {}, body: '' }],
    ['a 401 with a code', row, coded(401)],
    ['a 500', row, coded(500)],
    ['a success', row, { statusCode: 204, headers: {}, body: '' }],
    ['a batch', at('$batch'), coded(400)],
    ['a transport error', row, { error: 'socket hang up' }],
    ['a cut-off answer', row, { ...coded(400), incompleteResponse: true }],
    ['no answer', row, null],
  ]) assert.equal(notStartedAnswer(req, res), false, label);
});

// The feature's preflight (runManagedFeature `preflight`): its own safety checks — the clean-continuation check of a
// dirty local copy, a retained creation id, an edit switch — run on EVERY path, recovery included, before anything the
// feature reads into its workspace or sends. A refusal keeps the attempt and its token and writes nothing.
const tracked = (p) => {
  p.calls = [];
  for (const name of ['resolve', 'plan', 'apply', 'prove', 'ensureMembership', 'resumeCreate']) {
    const fn = p[name];
    if (typeof fn === 'function') p[name] = async (...a) => { p.calls.push(name); return fn(...a); };
  }
  return p;
};
const dirtyCopy = () => Object.assign(new Error('the local copy has unsent edits'), { code: 'create-completion-required', category: 'workspace-copy-unsent-edits' });
const fileOf = (store) => (fs.existsSync(store.file) ? fs.readFileSync(store.file, 'utf8') : null);

test('the feature preflight is required: without it nothing is read, held or written', async () => {
  const s = await setup();
  const p = ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' });
  delete p.preflight;
  const before = fileOf(s.store);
  assert.equal(await codeOf(runManagedFeature({ ...p, store: s.store, barrier: s.barrier })), CODES.notSettled);
  assert.deepEqual(s.wire.log, []);
  assert.equal(s.barrier.active, false);
  assert.equal(fileOf(s.store), before);
});

test('the feature preflight runs first on an ordinary run: a refusal plans, prepares and sends nothing', async () => {
  const s = await setup();
  const seen = [];
  const p = tracked(ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }));
  p.preflight = async (a) => { seen.push(a); throw dirtyCopy(); };
  const before = fileOf(s.store);
  assert.equal(await codeOf(runManagedFeature({ ...p, store: s.store, barrier: s.barrier })), 'create-completion-required');
  assert.deepEqual(p.calls, []);
  assert.deepEqual(seen.map((a) => [a.recovering, a.committed, a.pending]), [[false, null, null]]);
  assert.equal(fileOf(s.store), before, 'nothing prepared');
  assert.deepEqual(s.wire.writes(), []);
  assert.equal(s.barrier.allowScope(ACCOUNT, 'a sibling'), false, 'quarantined for the run');
});

test('the feature preflight runs before every recovery route — prove, continue, resume — and a refusal keeps the attempt, its token and every byte, on each identical rerun', async () => {
  // Each case strands an attempt, then answers a fresh run over the same workspace: [run, ports, observed?].
  const proveCase = async () => {
    const s = await setup();
    await runManagedFeature({ ...ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: s.store, barrier: s.barrier });
    const crash = Object.assign(new Error('the process ended'), { code: 'crash' });
    assert.equal(await codeOf(runManagedFeature({ ...ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>', fail: { prove: crash } }), store: s.store, barrier: s.barrier })), 'crash');
    return { s, next: () => nextRun(s), make: (n) => ports(s.wire, n.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' }), want: { committed: true, recovered: true } };
  };
  const continueCase = async () => {
    const s = await observedSetup();
    await committedEdit(s);
    await codeOf(runManagedFeature(observed(editPorts(s.wire, s.sdk, { formxml: '<form v="2"/>', local: localFailure() }), s)));
    return { s, next: () => observedRun(s), make: (n) => editPorts(s.wire, n.sdk, { formxml: '<form v="2"/>' }), want: { committed: true, recovered: true, continued: true } };
  };
  const resumeCase = async () => {
    const s = await setup();
    refuseNextCreate(s.wire);
    await codeOf(runManagedFeature({ ...createPorts(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: s.store, barrier: s.barrier }));
    return { s, next: () => nextRun(s), make: (n) => createPorts(s.wire, n.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), want: { committed: true, recovered: true, resumed: true } };
  };
  for (const [route, strand] of [['prove', proveCase], ['continue', continueCase], ['resume', resumeCase]]) {
    const { s, next, make, want } = await strand();
    const stranded = s.store.readGroup('form', 'account/main').pending;
    assert.equal(stranded.phase, 'sending', route);
    const writes = s.wire.writes().length;
    for (const attempt of [1, 2]) {
      const n = await next();
      const before = fileOf(n.store);
      const seen = [];
      const p = tracked(make(n));
      p.preflight = async (a) => { seen.push(a); throw dirtyCopy(); };
      assert.equal(await codeOf(runManagedFeature({ ...p, store: n.store, barrier: n.barrier, ...(n.observer ? { sendObserver: n.observer } : {}) })), 'create-completion-required', `${route} #${attempt}`);
      assert.deepEqual(p.calls, [], `${route} #${attempt}: nothing read, planned or sent after the refusal`);
      assert.deepEqual(seen.map((a) => [a.recovering, a.pending.token]), [[true, stranded.token]], `${route} #${attempt}`);
      assert.equal(fileOf(n.store), before, `${route} #${attempt}: nothing written`);
      assert.equal(n.store.readGroup('form', 'account/main').pending.token, stranded.token);
      assert.equal(s.wire.writes().length, writes);
      assert.equal(n.barrier.allowScope(ACCOUNT, 'a sibling'), false, `${route} #${attempt}: withheld for the run`);
    }
    const n = await next();
    const p = make(n);
    assert.deepEqual((await runManagedFeature({ ...p, store: n.store, barrier: n.barrier, ...(n.observer ? { sendObserver: n.observer } : {}) })).result, want, `${route}: a passing preflight recovers as before`);
  }
});

// Adoption consent: a root whose create no answer acknowledged is bound only with the feature's typed adoption
// approval (`adoptionApproved: true`, which the feature derives from its own `<family>:<key>` approval). A fresh read
// that proves the content shows what the row is, not that the maker agreed to manage it.
test('an unacknowledged root is committed only with adoption approved: without it the attempt stays, no binding and no membership', async () => {
  const s = await setup();
  s.wire.script(isCreate, { statusCode: 400, body: { error: { code: '0x80040203', message: 'lost' } } });
  assert.equal(await codeOf(runManagedFeature({ ...createPorts(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: s.store, barrier: s.barrier })), 'create-refused');
  const stranded = s.store.readGroup('form', 'account/main').pending;
  for (const attempt of [1, 2]) {
    const n = await nextRun(s);
    const before = fileOf(n.store);
    const p = tracked(createPorts(s.wire, n.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }));
    assert.equal(await codeOf(runManagedFeature({ ...p, store: n.store, barrier: n.barrier })), CODES.adoptionRequired, `#${attempt}`);
    assert.ok(!p.calls.includes('ensureMembership'), 'no membership for a root nobody approved');
    const { committed, pending } = n.store.readGroup('form', 'account/main');
    assert.deepEqual([committed, pending.token], [null, stranded.token], 'no binding; the attempt stays under its token');
    assert.equal(fileOf(n.store), before, 'nothing written');
    assert.equal(n.barrier.allowScope(ACCOUNT, 'a sibling'), false, 'withheld for the run');
  }
  const bad = await nextRun(s);
  assert.equal(await codeOf(runManagedFeature({ ...createPorts(s.wire, bad.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), adoptionApproved: 'yes', store: bad.store, barrier: bad.barrier })), CODES.notSettled, 'only a boolean approval');
  const n = await nextRun(s);
  const p = createPorts(s.wire, n.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' });
  assert.deepEqual((await runManagedFeature({ ...p, adoptionApproved: true, store: n.store, barrier: n.barrier })).result, { committed: true, recovered: true });
  assert.equal(n.store.readGroup('form', 'account/main').committed.records[0].origin, 'adopted');
  assert.equal(s.wire.log.filter(isCreate).length, 1, 'never resent');

  // An acknowledged create needs no approval and commits as created.
  const a = await setup();
  assert.equal((await runManagedFeature({ ...createPorts(a.wire, a.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: a.store, barrier: a.barrier })).result.committed, true);
  assert.equal(a.store.readGroup('form', 'account/main').committed.records[0].origin, 'created');
});

// The send window covers the whole logical operation, the client's own re-sends included; a run's claim on an attempt's
// sends is checked under the store's lease and fences any older claimant at dispatch; a publish that may have been sent
// is settled before a newer generation is committed over it; the not-started rule reads the operation path as the
// service does; and a workflow feature's preflight sees the attempt's effects.
const latch = () => { let resolve; const promise = new Promise((r) => { resolve = r; }); return { promise, resolve }; };
const outcome = (p) => p.then((value) => ({ value }), (error) => ({ error: error.code || error.message }));
const refused = () => JSON.stringify({ error: { code: '0x80040203', message: 'refused' } });

test('send window: a request the client re-sends after the window closed (a 401 refreshed) stays counted, and the next run only proves it', async () => {
  const s = await observedSetup();
  await committedEdit(s);
  const entered = latch(), answer = latch();
  const original = s.wire.request;
  let first = true;
  s.wire.script((e) => e.method === 'PATCH', { statusCode: 401, body: { error: { code: '0x80040220' } }, unapplied: true });
  s.wire.request = async (req) => {
    if (req.method === 'PATCH' && first) { first = false; entered.resolve(); await answer.promise; }
    return original(req);
  };
  const n = await observedRun(s);
  const p = editPorts(s.wire, n.sdk, { formxml: '<form v="2"/>' });
  let write;
  p.apply = async () => {
    write = n.sdk.dataverse.patch(`/systemforms(${MAIN})`, { formxml: '<form v="2"/>' });
    // The apply fails while its own write is still in flight; the client then refreshes the token and sends it again.
    await Promise.all([write, (async () => { await entered.promise; throw localFailure(); })()]);
  };
  assert.equal(await codeOf(runManagedFeature(observed(p, n))), 'form-layout-local-edit');
  answer.resolve();
  assert.equal((await write).status, 204);
  assert.equal(s.wire.writes().filter(isPatch).length, 2, 'the 401 and its re-send');
  const after = n.store.readGroup('form', 'account/main').pending.sendWindow;
  assert.ok(after.possible >= 1, `the re-sent edit stays possibly applied: ${JSON.stringify(after)}`);
  assert.equal(after.notStarted, 0, 'a 401 is answered by sending again, so it ends nothing');
  const again = await observedRun(s);
  const q = editPorts(s.wire, again.sdk, { formxml: '<form v="2"/>' });
  assert.deepEqual((await runManagedFeature(observed(q, again))).result, { committed: true, recovered: true }, 'proved, not continued');
  assert.deepEqual([q.sends.length, s.wire.writes().filter(isPatch).length], [0, 2]);
});

test('send window: a refusal that arrives after the window closed ends nothing; one that arrives while it is open does', async () => {
  const dir = makeTempDir('mp-trailing-');
  const barrier = createPublicationBarrier();
  const { store } = context(dir, barrier);
  const token = store.prepareAttempt({ family: 'form', key: 'account/main', baseGeneration: null, root: { kind: 'form', key: 'account/main', id: MAIN }, knownScopes: [ACCOUNT], declarationSha256: H('e'), publication: { scope: ACCOUNT, state: 'owed' } });
  const marked = store.markSending(token, expected(MAIN), { observed: true, claim: 'first' });
  const epoch = marked ? marked.epoch : undefined;
  const windowOf = () => store.readGroup('form', 'account/main').pending.sendWindow;
  const gate = latch();
  const observer = createAttemptSendObserver();
  const send = observer.wrap(async () => { await gate.promise; return { statusCode: 400, headers: {}, body: refused() }; });
  const req = { url: `${ENV}/api/data/v9.2/systemforms(${MAIN})`, method: 'PATCH', headers: {}, body: '{}' };
  const w = observer.open(store, token, epoch);
  const inFlight = send(req);
  w.close();
  gate.resolve();
  assert.equal((await inFlight).statusCode, 400);
  assert.deepEqual(windowOf(), { possible: 1, notStarted: 0, epoch: 1 }, 'in flight when the window closed: possibly applied');
  w.end();
  const w2 = observer.open(store, token, epoch);
  await send(req);
  w2.end();
  assert.deepEqual(windowOf(), { possible: 1, notStarted: 1, epoch: 1 }, 'answered while open: not started');
});

test('send claim: of two runs that read the same zero, the second is refused under the lease before it sends: one edit', async () => {
  const s = await observedSetup();
  await committedEdit(s);
  await codeOf(runManagedFeature(observed(editPorts(s.wire, s.sdk, { formxml: '<form v="2"/>', local: localFailure() }), s)));
  const token = s.store.readGroup('form', 'account/main').pending.token;
  const a = await observedRun(s);
  const aRead = latch(), releaseA = latch(), bEntered = latch(), releaseB = latch();
  const original = s.wire.request;
  s.wire.request = async (req) => {
    if (req.method === 'PATCH') { bEntered.resolve(); await releaseB.promise; }
    return original(req);
  };
  const b = await observedRun(s);
  s.wire.request = original;
  const pa = editPorts(s.wire, a.sdk, { formxml: '<form v="2"/>' });
  let aSaw;
  pa.preflight = async ({ pending }) => { aSaw = pending.sendWindow; aRead.resolve(); await releaseA.promise; };
  const pb = editPorts(s.wire, b.sdk, { formxml: '<form v="2"/>' });
  const aDone = outcome(runManagedFeature(observed(pa, a)));
  await aRead.promise;
  const bDone = outcome(runManagedFeature(observed(pb, b)));
  assert.equal(await Promise.race([bEntered.promise.then(() => true), bDone.then(() => false)]), true, 'the second run is sending');
  releaseA.resolve();
  const aResult = await aDone;
  releaseB.resolve();
  const bResult = await bDone;
  assert.equal(aSaw.possible, 0, 'the first run read a zero window');
  assert.equal(aResult.error, CODES.pending, 'its stale zero claims nothing');
  assert.deepEqual(pa.sends, [], 'and it sent nothing');
  assert.deepEqual(bResult.value.result, { committed: true, recovered: true, continued: true });
  assert.deepEqual(pb.sends, [[token, true]]);
  assert.equal(s.wire.writes().filter(isPatch).length, 1, 'one edit');
});

test('send claim: a run that claimed the attempt and was overtaken by a newer claim is refused at its dispatch, unsent', async () => {
  const s = await observedSetup();
  await committedEdit(s);
  await codeOf(runManagedFeature(observed(editPorts(s.wire, s.sdk, { formxml: '<form v="2"/>', local: localFailure() }), s)));
  const token = s.store.readGroup('form', 'account/main').pending.token;
  const pause = (p) => {
    const claimed = latch(), release = latch();
    const apply = p.apply;
    p.apply = async (x) => { claimed.resolve(); await release.promise; return apply(x); };
    return { claimed, release };
  };
  const a = await observedRun(s);
  const b = await observedRun(s);
  const pa = editPorts(s.wire, a.sdk, { formxml: '<form v="2"/>' });
  const pb = editPorts(s.wire, b.sdk, { formxml: '<form v="2"/>' });
  const ga = pause(pa), gb = pause(pb);
  const windowNow = () => context(s.dir, createPublicationBarrier()).store.readGroup('form', 'account/main').pending.sendWindow;
  const aDone = outcome(runManagedFeature(observed(pa, a)));
  await ga.claimed.promise;
  assert.equal(windowNow().epoch, 2, 'the first claim');
  const bDone = outcome(runManagedFeature(observed(pb, b)));
  await gb.claimed.promise;
  assert.equal(windowNow().epoch, 3, 'a newer claim over the same zero');
  ga.release.resolve();
  const aResult = await aDone;
  // The store refuses the count under the stale epoch before the request leaves; the client reports that as a failed transport.
  assert.equal(aResult.error, 'CONNECTION_ERROR', 'the overtaken run stops');
  assert.deepEqual([s.wire.writes().filter(isPatch).length, windowNow().possible], [0, 0], 'its edit never left');
  gb.release.resolve();
  assert.deepEqual((await bDone).value.result, { committed: true, recovered: true, continued: true });
  assert.deepEqual(pb.sends, [[token, true]]);
  assert.equal(s.wire.writes().filter(isPatch).length, 1, 'one edit');
  assert.equal(s.wire.saved.get(MAIN).formxml, '<form v="2"/>');
});

test('publication: a change over a publish that may have been sent stops before it prepares anything, unless a fresh read confirms that publish first', async () => {
  const strand = async (unapplied) => {
    const s = await setup();
    await runManagedFeature({ ...ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: s.store, barrier: s.barrier });
    s.wire.script((e) => /PublishXml/.test(e.path), { statusCode: 503, body: { error: { code: '0x80040216' } }, unapplied });
    assert.equal(await codeOf(publishForms(s.sdk, s.store, s.barrier, [{ family: 'form', key: 'account/main' }])), 'managed-publication-unconfirmed');
    return s;
  };
  const refs = [{ family: 'form', key: 'account/main' }];
  // The old publish landed, and no client is given to confirm it: the change is not made over it.
  const s = await strand(false);
  const old = s.store.readGroup('form', 'account/main').committed;
  const n = await nextRun(s);
  const changed = tracked(ports(s.wire, n.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' }));
  const before = fileOf(n.store);
  assert.equal(await codeOf(runManagedFeature({ ...changed, store: n.store, barrier: n.barrier })), PUBLICATION_UNCONFIRMED);
  assert.deepEqual(changed.calls, ['resolve', 'plan'], 'nothing prepared or sent');
  assert.equal(fileOf(n.store), before);
  assert.deepEqual(n.store.readGroup('form', 'account/main'), { committed: old, pending: null, effects: [] });
  assert.equal(s.wire.saved.get(MAIN).formxml, '<form v="1"/>');

  // With a client, the old publish is confirmed read-only first; the new generation then owes its own publish, which a
  // later publish sends.
  const m = await nextRun(s);
  const p = ports(s.wire, m.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' });
  assert.deepEqual((await runManagedFeature({ ...p, client: m.sdk.dataverse, store: m.store, barrier: m.barrier })).result, { committed: true, recovered: false });
  const next = m.store.readGroup('form', 'account/main').committed;
  assert.notEqual(next.generation, old.generation);
  assert.equal(next.publication.state, 'owed', 'the new generation keeps its own debt');
  const publishes = s.wire.publishes().length;
  const t = await nextRun(s);
  assert.equal((await publishForms(t.sdk, t.store, t.barrier, refs)).sent, true);
  assert.equal(s.wire.publishes().length, publishes + 1);
  assert.equal(s.wire.published.get(MAIN).formxml, '<form v="2"/>');

  // The old publish did not land: the fresh read cannot confirm it, so the change stops before it prepares anything.
  const u = await strand(true);
  const k = await nextRun(u);
  const q = tracked(ports(u.wire, k.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' }));
  const prior = fileOf(k.store);
  assert.equal(await codeOf(runManagedFeature({ ...q, client: k.sdk.dataverse, store: k.store, barrier: k.barrier })), PUBLICATION_UNCONFIRMED);
  assert.ok(!q.calls.includes('apply'));
  assert.equal(fileOf(k.store), prior, 'nothing written');
  assert.deepEqual(u.wire.writes().filter(isPatch), []);
});

test('not started: the operation path is read decoded, so an encoded batch is a batch and an ambiguous path ends nothing', async () => {
  const at = (p) => ({ url: `${ENV}/api/data/v9.2/${p}`, method: 'POST', headers: {} });
  const coded = { statusCode: 400, headers: {}, body: refused() };
  for (const [label, p] of [['a batch', '$batch'], ['an encoded batch', '%24batch'], ['an encoded batch in lower case', '%24BATCH'], ['a double-encoded batch', '%2524batch'], ['a malformed escape', `systemforms(${MAIN})%zz`], ['a lone percent', `systemforms(${MAIN})%`], ['a batch segment', '$batch/x']]) {
    assert.equal(notStartedAnswer(at(p), coded), false, label);
  }
  assert.equal(notStartedAnswer(at(`systemforms(${MAIN})`), coded), true, 'one operation');
  assert.equal(notStartedAnswer(at(`systemforms%28${MAIN}%29`), coded), true, 'an encoded single operation is still one');

  // Through the real client: an encoded `$batch` refused with a Dataverse code stays possibly applied.
  const counts = [];
  for (const endpoint of ['$batch', '%24batch']) {
    const s = await observedSetup();
    const token = s.store.prepareAttempt({ family: 'form', key: 'account/main', baseGeneration: null, root: { kind: 'form', key: 'account/main', id: MAIN }, declarationSha256: H('e'), knownScopes: [ACCOUNT] });
    const { epoch } = s.store.markSending(token, expected(MAIN), { observed: true, claim: 'first' });
    const w = s.observer.open(s.store, token, epoch);
    const body = `--batch_1\r\nContent-Type: application/http\r\n\r\nPATCH /api/data/v9.0/systemforms(${MAIN}) HTTP/1.1\r\nContent-Type: application/json\r\n\r\n{"formxml":"<form/>"}\r\n--batch_1--\r\n`;
    s.wire.script((e) => e.path === '$batch', { statusCode: 400, body: { error: { code: '0x80040203' } }, unapplied: true });
    await s.sdk.dataverse.post(`/${endpoint}`, body, { headers: { 'Content-Type': 'multipart/mixed; boundary=batch_1' } });
    w.end();
    counts.push(s.store.readGroup('form', 'account/main').pending.sendWindow.possible);
  }
  assert.deepEqual(counts, [1, 1]);
});

test('workflow preflight: an existing row the attempt never created is listed as an edit, whatever the group\'s commit state says', () => {
  const RULE = '33333333-3333-4333-8333-333333333333';
  const pending = { token: 't1', root: { kind: 'business-rule', key: 'account/hide', id: RULE }, baseGeneration: null, acknowledgedRoot: false, savedObservation: null, expected: { baseObservation: null } };
  const effect = (over) => ({ token: `e-${over.effect}-${over.state || 'u'}`, attemptToken: 't1', rowId: RULE, state: 'definitely-unsent', dispatchToken: null, desiredState: over.effect === 'state' ? 'Active' : null, ...over });
  const state = effect({ effect: 'state' });
  const body = effect({ effect: 'body' });
  assert.deepEqual(existingRowDispatches({ pending, effects: [state, body] }), [state, body], 'no committed group and a null base are not evidence of a create');
  assert.deepEqual(existingRowDispatches({ pending, effects: [effect({ effect: 'create', state: 'confirmed' }), state] }), [], 'its own create, confirmed');
  assert.deepEqual(existingRowDispatches({ pending: { ...pending, acknowledgedRoot: true }, effects: [state] }), [], 'its own create, acknowledged');
  const deactivate = { ...state, desiredState: 'Draft' };
  assert.deepEqual(existingRowDispatches({ pending: { ...pending, acknowledgedRoot: true }, effects: [deactivate] }), [deactivate], 'a deactivation of its own row is an edit');
  assert.deepEqual(existingRowDispatches({ pending: { ...pending, savedObservation: { acknowledgedRoot: true } }, effects: [state] }), []);
  const edited = { ...pending, acknowledgedRoot: true, expected: { baseObservation: { rowVersion: null, savedSha256: H('d') } } };
  assert.deepEqual(existingRowDispatches({ pending: edited, effects: [state] }), [state], 'an acknowledgement on an attempt that edited an existing row is not a create');
  assert.deepEqual(existingRowDispatches({ pending, effects: [effect({ effect: 'create' }), state] }), [state], 'a create that is not confirmed proves nothing');
  assert.deepEqual(existingRowDispatches({ pending, effects: [{ ...state, state: 'dispatching', dispatchToken: 'd' }] }), [], 'a dispatched effect is proved, never sent again');
  assert.deepEqual(existingRowDispatches({ pending, effects: [{ ...state, attemptToken: 'other' }] }), [], 'another attempt\'s effect');
  assert.deepEqual(existingRowDispatches({ pending: null, effects: [state] }), []);
  assert.deepEqual([...rowsCreatedByAttempt({ pending: { ...pending, acknowledgedRoot: true }, effects: [] })], [RULE]);
});

test('workflow preflight: with the edit switch off, a state write to an adopted existing workflow is refused before anything is sent; preflight sees the attempt\'s effects', async () => {
  const s = await setup();
  const key = 'account/hide';
  s.wire.workflows.set(MAIN, { workflowid: MAIN, statecode: 0, statuscode: 1 });
  const token = s.store.prepareAttempt({ family: 'rule', key, baseGeneration: null, root: { kind: 'business-rule', key, id: MAIN }, declarationSha256: H('e'), knownScopes: [] });
  s.store.markSending(token, { ...expected(MAIN), proofSchema: 'rule-v1', baseProofSha256: H('d'), baseObservation: { rowVersion: null, savedSha256: H('d') } });
  const effect = { attemptToken: token, baseGeneration: null, family: 'rule', key, rowId: MAIN, effect: 'state', request: { method: 'PATCH', shape: 'workflow-patch' }, desiredState: 'Active' };
  const recorded = s.store.recordWorkflowEffect(effect);
  const { sdk } = await sdkOver(s.wire, { barrier: s.barrier, workflowEffectGate: createWorkflowEffectGate({ store: s.store }) });
  const switchOn = false;
  const seen = [];
  const result = await codeOf(runManagedFeature({
    family: 'rule', key, phase: 'rules', halt, store: s.store, barrier: s.barrier, adoptionApproved: true,
    preflight: async (a) => {
      seen.push(a.effects.map((e) => e.token));
      if (!switchOn && existingRowDispatches(a).length) throw Object.assign(new Error('edits are switched off'), { code: 'workflow-edit-refused' });
    },
    resolve: async () => {}, plan: async () => {}, apply: async () => {}, ensureMembership: async () => {},
    prove: async () => {
      await withWorkflowEffect({ store: s.store, effect }, () => sdk.dataverse.patch(`/workflows(${MAIN})`, { statecode: 1, statuscode: 2 }));
      return null;
    },
  }));
  assert.equal(result, 'workflow-edit-refused');
  assert.deepEqual(seen, [[recorded.token]]);
  assert.deepEqual(s.wire.writes(), [], 'adoption approval does not switch edits on');
  assert.equal(s.wire.workflows.get(MAIN).statecode, 0);
  assert.equal(s.store.readGroup('rule', key).pending.token, token);
});

test('publication race: a publish dispatched while an edit runs its preflight stops the edit before it prepares or sends; the publish puts only its own version live', { timeout: 20000 }, async () => {
  const s = await setup();
  const refs = [{ family: 'form', key: 'account/main' }];
  await runManagedFeature({ ...ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: s.store, barrier: s.barrier });
  const inPreflight = latch();
  const releaseEdit = latch();
  const entered = latch();
  const releasePublish = latch();
  const p = tracked(ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' }));
  let saw;
  p.preflight = async ({ committed }) => { saw = committed.publication.state; inPreflight.resolve(); await releaseEdit.promise; };
  const editDone = outcome(runManagedFeature({ ...p, client: s.sdk.dataverse, store: s.store, barrier: s.barrier }));
  await inPreflight.promise;
  // Another process publishes version 1 while the edit waits in its preflight: its dispatch is recorded, then held in flight.
  const original = s.wire.request;
  s.wire.request = async (req) => {
    if (req.method === 'POST' && /PublishXml/.test(req.url)) { entered.resolve(); await releasePublish.promise; }
    return original(req);
  };
  const publisher = await nextRun(s);
  s.wire.request = original;
  const publishDone = outcome(publishForms(publisher.sdk, publisher.store, publisher.barrier, refs));
  assert.equal(await Promise.race([entered.promise.then(() => true), publishDone.then(() => false)]), true, 'the publish is in flight');
  assert.equal(publisher.store.readGroup('form', 'account/main').committed.publication.state, 'dispatching');
  releaseEdit.resolve();
  const edited = await editDone;
  releasePublish.resolve();
  const published = await publishDone;
  assert.equal(saw, 'owed', 'the edit read the group before the publish was dispatched');
  assert.equal(edited.error, PUBLICATION_UNCONFIRMED);
  assert.equal(s.barrier.allowScope(ACCOUNT, 'a sibling'), false, 'the edit\'s scope is quarantined for the run');
  assert.ok(!p.calls.includes('apply'), 'nothing sent');
  assert.deepEqual(s.wire.log.filter(isPatch), [], 'the edit never left');
  assert.equal(s.wire.published.get(MAIN).formxml, '<form v="1"/>', 'the earlier publish put only its own version live');
  assert.equal(published.error, undefined, 'the publish settled');
  const reopened = await nextRun(s);
  const after = reopened.store.readGroup('form', 'account/main');
  assert.equal(after.pending, null, 'nothing prepared');
  assert.equal(after.committed.publication.state, 'confirmed');
  // No dead end: the next run makes the edit.
  const again = ports(s.wire, reopened.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' });
  assert.deepEqual((await runManagedFeature({ ...again, client: reopened.sdk.dataverse, store: reopened.store, barrier: reopened.barrier })).result, { committed: true, recovered: false });
  assert.equal(s.wire.saved.get(MAIN).formxml, '<form v="2"/>');
});

test('workflow handoff: a state effect first recorded inside recovery is refused by the operation check before it is sent; only the attempt\'s own Draft completion passes', async () => {
  const key = 'account/hide';
  const refusal = () => Object.assign(new Error('edits are switched off'), { code: 'workflow-edit-refused' });
  // An existing Draft workflow, a pending attempt with a recorded base and no effect recorded yet: the persisted-effect
  // preflight sees nothing, and recovery proposes the state write for the first time.
  const strand = async ({ acknowledged = false } = {}) => {
    const s = await setup();
    s.wire.workflows.set(MAIN, { workflowid: MAIN, statecode: 0, statuscode: 1 });
    const token = s.store.prepareAttempt({ family: 'rule', key, baseGeneration: null, root: { kind: 'business-rule', key, id: MAIN }, declarationSha256: H('e'), knownScopes: [] });
    // The attempt's own create has no base observation; an attempt that read an existing row has one.
    s.store.markSending(token, { ...expected(MAIN), proofSchema: 'rule-v1', ...(acknowledged ? { baseProofSha256: null, baseObservation: null } : { baseProofSha256: H('d'), baseObservation: { rowVersion: null, savedSha256: H('d') } }) });
    if (acknowledged) s.store.noteSaved(token, { proof: null, acknowledgedRoot: true, phase: 'state-pending' });
    const effect = { attemptToken: token, baseGeneration: null, family: 'rule', key, rowId: MAIN, effect: 'state', request: { method: 'PATCH', shape: 'workflow-patch' }, desiredState: 'Active' };
    const { sdk } = await sdkOver(s.wire, { barrier: s.barrier, workflowEffectGate: createWorkflowEffectGate({ store: s.store }) });
    return { s, token, effect, sdk };
  };
  const recover = ({ s, effect, sdk }, proposeWith) => {
    const seen = {};
    const run = codeOf(runManagedFeature({
      family: 'rule', key, phase: 'rules', halt, store: s.store, barrier: s.barrier, adoptionApproved: true,
      preflight: async (a) => {
        seen.preflight = existingRowDispatches(a).length;
        if (existingRowDispatches(a).length) throw refusal();
      },
      resolve: async () => {}, plan: async () => {}, apply: async () => {}, ensureMembership: async () => {},
      prove: async () => {
        await proposeWith(() => sdk.dataverse.patch(`/workflows(${MAIN})`, { statecode: 1, statuscode: 2 }));
        throw Object.assign(new Error('stopped after the write'), { code: 'probe-complete' });
      },
    }));
    return run.then((code) => ({ code, seen }));
  };
  // The documented consumer rule: check the proposed operation, with the switch off, before it is recorded or sent.
  const byRule = (x) => (send) => {
    if (editSwitchRequired(x.s.store.readGroup('rule', key), x.effect)) throw refusal();
    return withWorkflowEffect({ store: x.s.store, effect: x.effect }, send);
  };
  // The same check made by withWorkflowEffect itself when the feature passes its switch, and the row's state from the
  // feature's own fresh read when it has one.
  const bySwitch = (x, read = false) => async (send) => {
    let observedState;
    if (read) {
      const got = await x.sdk.dataverse.get(`/workflows(${MAIN})?$select=statecode`);
      const row = got && got.body !== undefined ? got.body : got && got.data !== undefined ? got.data : got;
      observedState = row.statecode === 0 ? 'Draft' : row.statecode === 1 ? 'Active' : 'Other';
    }
    return withWorkflowEffect({ store: x.s.store, effect: x.effect, workflowConditionalEdits: false, observedState }, send);
  };
  for (const [label, how] of [['the consumer rule', byRule], ['withWorkflowEffect with the switch off', bySwitch]]) {
    const x = await strand();
    const { code, seen } = await recover(x, how(x));
    assert.equal(seen.preflight, 0, `${label}: the persisted-effect preflight sees nothing to refuse`);
    assert.equal(code, 'workflow-edit-refused', label);
    assert.deepEqual(x.s.wire.writes(), [], `${label}: zero writes`);
    assert.equal(x.s.wire.workflows.get(MAIN).statecode, 0, `${label}: Draft kept`);
    const after = x.s.store.readGroup('rule', key);
    assert.deepEqual([after.pending.token, after.effects], [x.token, []], `${label}: the attempt kept, nothing recorded`);
  }
  // The attempt's own Draft, its create acknowledged, read fresh as Draft: activating it is the one write the default
  // path allows.
  const own = await strand({ acknowledged: true });
  assert.equal((await recover(own, bySwitch(own, true))).code, 'probe-complete');
  assert.equal(own.s.wire.writes().length, 1);
  assert.equal(own.s.wire.workflows.get(MAIN).statecode, 1);
  // Any body write, and a state write of another attempt or with no pending attempt, is an edit; a create is not.
  const read = own.s.store.readGroup('rule', key);
  assert.equal(editSwitchRequired(read, own.effect, { observedState: 'Draft' }), false, 'its own activation, read as Draft');
  assert.equal(editSwitchRequired(read, own.effect), true, 'an activation with no fresh read is not shown to complete the attempt');
  assert.equal(editSwitchRequired(read, own.effect, { observedState: 'Active' }), true, 'nor one of a row that is no longer Draft');
  assert.equal(editSwitchRequired(read, { ...own.effect, desiredState: 'Draft' }, { observedState: 'Draft' }), true, 'any other transition');
  assert.equal(editSwitchRequired(read, { ...own.effect, effect: 'body', desiredState: null }, { observedState: 'Draft' }), true, 'a body write of its own Draft is not completion');
  assert.equal(editSwitchRequired(read, { ...own.effect, attemptToken: 'another' }, { observedState: 'Draft' }), true);
  assert.equal(editSwitchRequired({ pending: null, effects: [] }, own.effect, { observedState: 'Draft' }), true);
  assert.equal(editSwitchRequired({ pending: null, effects: [] }, { ...own.effect, effect: 'create' }), false);

  // Its own row, created and already Active: with the switch off it is never deactivated, and an activation without a
  // fresh Draft read is refused as well — zero writes either way, the row Active.
  for (const [label, effect, read] of [['a deactivation', { desiredState: 'Draft' }, true], ['a deactivation, no read', { desiredState: 'Draft' }, false], ['an activation without a fresh read', {}, false], ['an activation of a row read Active', {}, true]]) {
    const active = await strand({ acknowledged: true });
    active.s.wire.workflows.set(MAIN, { workflowid: MAIN, statecode: 1, statuscode: 2 });
    active.effect = { ...active.effect, ...effect };
    const { code } = await recover(active, bySwitch(active, read));
    assert.equal(code, 'workflow-edit-refused', label);
    assert.deepEqual(active.s.wire.writes(), [], `${label}: zero writes`);
    assert.equal(active.s.wire.workflows.get(MAIN).statecode, 1, `${label}: Active kept`);
    assert.deepEqual(active.s.store.readGroup('rule', key).effects, [], `${label}: nothing recorded`);
  }
});

test('workflow handoff: an activation a read found already made is never sent; after a failure before the commit and a maker\'s deactivation, the next run\'s proposal is refused with zero writes', async () => {
  const key = 'account/hide';
  const seen = { observedState: 'Active', observedVersion: 'W/"2"' };
  for (const how of ['fulfil the recorded activation', 'no activation recorded']) {
    const s = await setup();
    // The attempt's own Draft, its create acknowledged; someone else activates it (version 2) before this run sends.
    s.wire.workflows.set(MAIN, { workflowid: MAIN, statecode: 0, statuscode: 1 });
    const token = s.store.prepareAttempt({ family: 'rule', key, baseGeneration: null, root: { kind: 'business-rule', key, id: MAIN }, declarationSha256: H('e'), knownScopes: [] });
    s.store.markSending(token, { ...expected(MAIN), proofSchema: 'rule-v1', baseProofSha256: null, baseObservation: null });
    s.store.noteSaved(token, { proof: null, acknowledgedRoot: true, phase: 'state-pending' });
    const effect = { attemptToken: token, baseGeneration: null, family: 'rule', key, rowId: MAIN, effect: 'state', request: { method: 'PATCH', shape: 'workflow-patch' }, desiredState: 'Active', expectedVersion: 'W/"1"' };
    s.wire.workflows.set(MAIN, { workflowid: MAIN, statecode: 1, statuscode: 2 });
    const fulfilled = how === 'no activation recorded'
      ? s.store.recordFulfilledEffect(effect, seen)
      : s.store.fulfillEffect(s.store.recordWorkflowEffect(effect).token, seen);
    assert.equal(fulfilled.state, 'fulfilled', how);
    // The run fails before its commit; a maker deactivates the row (version 3); the next process proposes the
    // activation again, the row read fresh as Draft, with and without the edit switch.
    s.wire.workflows.set(MAIN, { workflowid: MAIN, statecode: 0, statuscode: 1 });
    const next = await nextRun(s);
    const { sdk } = await sdkOver(s.wire, { barrier: next.barrier, workflowEffectGate: createWorkflowEffectGate({ store: next.store }) });
    for (const switchOn of [false, true]) {
      let ran = false;
      const err = await withWorkflowEffect({ store: next.store, effect: { ...effect, expectedVersion: 'W/"3"' }, workflowConditionalEdits: switchOn, observedState: 'Draft' }, () => {
        ran = true;
        return sdk.dataverse.patch(`/workflows(${MAIN})`, { statecode: 1, statuscode: 2 });
      }).then(() => null, (e) => e);
      assert.equal(err && err.code, WORKFLOW_EFFECT_FULFILLED, `${how}, switch ${switchOn}`);
      assert.equal(err.effect.token, fulfilled.token);
      assert.equal(ran, false, 'the write never runs');
    }
    assert.deepEqual(s.wire.writes(), [], `${how}: zero writes`);
    assert.equal(s.wire.workflows.get(MAIN).statecode, 0, `${how}: the maker's deactivation kept`);
    const after = next.store.readGroup('rule', key);
    assert.deepEqual([after.pending.token, after.effects.map((e) => [e.token, e.state, e.dispatchToken])], [token, [[fulfilled.token, 'fulfilled', null]]], `${how}: the attempt and its fulfilled fact kept`);
    assert.deepEqual(existingRowDispatches(after), [], `${how}: nothing left to send`);
  }
});

// A declaration with authored free text, as a maker writes it: names, a description with markup characters, a URL.
const DECLARED = Object.freeze({
  name: 'Main', description: 'Sales <overview> & pipeline — “quarterly” ünïcode', fieldOptions: { name: { required: false } },
  iframe: { name: 'News', url: 'https://contoso.crm.dynamics.com/WebResources/new_news.htm?id=1&lang=en' },
});
const TODAY = Object.freeze({ ...DECLARED, description: 'Changed since' });
// The ports of a feature that records its declaration with the attempt; its proof answers a consumer state of its own
// (`answered` as its declaration slot — say, what it rebuilt from today's spec), which the store keeps as answered.
function declaring(p, declaration, answered) {
  const plan = p.plan;
  p.plan = async (a) => { const r = await plan(a); return r && r.noop !== true ? { ...r, declaration } : r; };
  const prove = p.prove;
  p.proveSaw = [];
  p.prove = async (a) => { p.proveSaw.push(a.declaration); const r = await prove(a); return answered === undefined ? r : { ...r, consumerState: { ...r.consumerState, declaration: answered } }; };
  return p;
}

test('declaration: an attempt keeps its original declaration from before the send; recovery commits that one, never today\'s, never null', async () => {
  const s = await setup();
  await runManagedFeature({ ...ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: s.store, barrier: s.barrier });
  const first = declaring(ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>', fail: { membership: Object.assign(new Error('membership failed'), { code: 'membership-failed' }) } }), DECLARED);
  const apply = first.apply;
  let onDisk;
  first.apply = async (a) => { onDisk = context(s.dir, createPublicationBarrier()).store.readGroup('form', 'account/main').pending.declaration; return apply(a); };
  assert.equal(await codeOf(runManagedFeature({ ...first, store: s.store, barrier: s.barrier })), 'membership-failed');
  assert.deepEqual(onDisk, DECLARED, 'persisted, losslessly, before the send');
  assert.equal(s.wire.saved.get(MAIN).formxml, '<form v="2"/>');

  for (const answered of [{ rebuilt: 'today' }, null]) {
    const u = await setup();
    await runManagedFeature({ ...ports(u.wire, u.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: u.store, barrier: u.barrier });
    const p = declaring(ports(u.wire, u.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>', fail: { membership: Object.assign(new Error('membership failed'), { code: 'membership-failed' }) } }), DECLARED);
    await codeOf(runManagedFeature({ ...p, store: u.store, barrier: u.barrier }));
    const n = await nextRun(u);
    // Today's spec says something else; the recovery proves the save the attempt made and records what it declared.
    const q = declaring(ports(u.wire, n.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' }), TODAY, answered);
    let preflightSaw;
    q.preflight = async ({ pending }) => { preflightSaw = pending.declaration; };
    assert.deepEqual((await runManagedFeature({ ...q, store: n.store, barrier: n.barrier })).result, { committed: true, recovered: true });
    assert.deepEqual(preflightSaw, DECLARED);
    assert.deepEqual(q.proveSaw, [DECLARED], 'the recovery proof is given the recorded declaration');
    const { committed, pending } = (await nextRun(u)).store.readGroup('form', 'account/main');
    assert.equal(pending, null);
    assert.deepEqual(committed.originalDeclaration, DECLARED, `answered ${answered === null ? 'null' : 'today\'s'}: the original, never today's, never null`);
    assert.deepEqual(committed.consumerState.declaration, answered, 'the feature\'s own state, as it answered it');
  }
});

test('declaration: a changed declaration is never sent under an attempt that recorded another; a prepared one is retired and prepared again', async () => {
  // A continuation whose declaration changed, under the same hash: refused before anything is sent.
  const s = await observedSetup();
  await committedEdit(s);
  const first = declaring(editPorts(s.wire, s.sdk, { formxml: '<form v="2"/>', local: localFailure() }), DECLARED);
  assert.equal(await codeOf(runManagedFeature(observed(first, s))), 'form-layout-local-edit');
  const stranded = s.store.readGroup('form', 'account/main').pending;
  const n = await observedRun(s);
  const changed = declaring(editPorts(s.wire, n.sdk, { formxml: '<form v="2"/>' }), TODAY);
  assert.equal(await codeOf(runManagedFeature(observed(changed, n))), 'create-completion-required');
  assert.deepEqual([changed.sends, s.wire.log.filter(isPatch)], [[], []]);
  assert.deepEqual(n.store.readGroup('form', 'account/main').pending, stranded, 'kept as it was');

  // A prepared attempt (never marked sending) whose plan now declares something else sent nothing: it is retired, and
  // the change is prepared and sent under a new attempt that records today's declaration.
  const u = await setup();
  await runManagedFeature({ ...ports(u.wire, u.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: u.store, barrier: u.barrier });
  const g = u.store.readGroup('form', 'account/main').committed;
  const old = u.store.prepareAttempt({ family: 'form', key: 'account/main', baseGeneration: g.generation, root: { kind: 'form', key: 'account/main', id: MAIN }, knownScopes: [ACCOUNT], declarationSha256: H('e'), declaration: DECLARED, publication: { scope: ACCOUNT, state: 'owed' } });
  const m = await nextRun(u);
  const p = declaring(ports(u.wire, m.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' }), TODAY);
  const tokens = [];
  const apply = p.apply;
  p.apply = async (a) => { tokens.push(a.token); return apply(a); };
  assert.deepEqual((await runManagedFeature({ ...p, store: m.store, barrier: m.barrier })).result, { committed: true, recovered: false });
  assert.equal(tokens.length, 1);
  assert.notEqual(tokens[0], old, 'not sent under the attempt that recorded another declaration');
  assert.deepEqual(m.store.readGroup('form', 'account/main').committed.originalDeclaration, TODAY);
});
// A workflow feature's own derived state, as the rules and process-flow helpers keep it in their declaration slot: a
// flow's applied hash and actual backing identity, a rule's node history. Its plan is a no-op when that state shows
// the authored input already applied; the authored input itself is recorded with the attempt.
function workflowFeature(s, family, id, authored) {
  const key = family === 'bpf' ? 'lead/sale' : 'account/hide';
  const kind = family === 'bpf' ? 'bpf' : 'business-rule';
  const f = { applies: 0 };
  Object.assign(f, {
    phase: 'workflows', family, key, knownScopes: [], knownIds: [id], halt, store: s.store, barrier: s.barrier, adoptionApproved: false,
    preflight: async () => {},
    resolve: async () => ({}),
    plan: async ({ committed }) => {
      const d = committed && committed.consumerState.declaration;
      if (d && d.applied === sha(authored) && s.backing.get(id) === (d.backing || d.rule)) return { noop: true };
      return { root: { kind, key, id }, expected: { ...expected(id), proofSchema: `${family}-v1` }, declarationSha256: sha(authored), declaration: authored };
    },
    apply: async () => { f.applies += 1; s.backing.set(id, `new_${family}_${f.applies}`); return { sent: true }; },
    prove: async () => {
      const backing = s.backing.get(id);
      const derived = family === 'bpf'
        ? { declaration: { flow: { name: authored.name, stages: authored.stages.map((x) => x.name) }, applied: sha(authored), backing }, stages: {} }
        : { declaration: { rule: backing, applied: sha(authored), nodes: [{ key: 'hide-phone', id: UNRELATED }] }, slots: {} };
      return { savedProof: null, acknowledgedRoot: true, records: [rec(kind, key, id)], proof: PROOF, consumerState: derived, publication: null, proofSchema: `${family}-v1` };
    },
    ensureMembership: async () => {},
  });
  return f;
}

test('declaration: the original is kept apart from a workflow feature\'s own state; its backing identity and node history survive, and the identical rerun is a no-op', async () => {
  // Authored input, with free text a feature's derived state could not keep (an environment URL).
  const FLOW = Object.freeze({ name: 'Lead to sale', help: 'See https://contoso.crm.dynamics.com/main.aspx?etn=lead&pagetype=entitylist', stages: [{ name: 'Qualify' }, { name: 'Close' }] });
  for (const family of ['bpf', 'rule']) {
    const s = await setup();
    s.backing = new Map();
    const first = workflowFeature(s, family, MAIN, FLOW);
    assert.deepEqual((await runManagedFeature(first)).result, { committed: true, recovered: false }, family);
    const g = context(s.dir, createPublicationBarrier()).store.readGroup(family, first.key).committed;
    assert.equal(family === 'bpf' ? g.consumerState.declaration.backing : g.consumerState.declaration.rule, s.backing.get(MAIN), `${family}: the actual backing identity is kept`);
    if (family === 'rule') assert.deepEqual(g.consumerState.declaration.nodes, [{ key: 'hide-phone', id: UNRELATED }], 'the node history is kept');
    assert.deepEqual(g.originalDeclaration, FLOW, `${family}: the authored input, losslessly, beside it`);
    const again = workflowFeature(s, family, MAIN, FLOW);
    assert.deepEqual((await runManagedFeature(again)).result, { noop: true }, `${family}: the identical rerun`);
    assert.equal(again.applies, 0, `${family}: nothing sent again`);
  }
});

test('declaration: a change to the authored input alone commits the new original under a new generation with nothing sent and no effect; a no-op plan never does', async () => {
  // A flow whose only change is its security roles: the workflow itself is unchanged (its applied hash covers the flow,
  // not the roles a later phase grants), so nothing is sent; the managed download must still restore today's roles.
  const flowOf = (d) => ({ name: d.name, stages: d.stages });
  const OLD = Object.freeze({ name: 'Lead to sale', stages: [{ name: 'Qualify' }], securityRoles: ['Salesperson'] });
  const NEW = Object.freeze({ ...OLD, securityRoles: ['Salesperson', 'Sales Manager'] });
  const s = await setup();
  s.backing = new Map();
  const feature = (authored, { declarationOnlyIsNoop = false } = {}) => {
    const f = workflowFeature(s, 'bpf', MAIN, authored);
    f.plan = async ({ committed }) => {
      const d = committed && committed.consumerState.declaration;
      const flowApplied = d && d.applied === sha(flowOf(authored)) && s.backing.get(MAIN) === d.backing;
      if (flowApplied && (declarationOnlyIsNoop || JSON.stringify(committed.originalDeclaration) === JSON.stringify(authored))) return { noop: true };
      return { root: { kind: 'bpf', key: f.key, id: MAIN }, expected: { ...expected(MAIN), proofSchema: 'bpf-v1' }, declarationSha256: sha(authored), declaration: authored };
    };
    f.apply = async () => {
      // The flow is created once; after that the plan differs only in authored input the workflow does not carry.
      if (s.backing.has(MAIN)) return { sent: false };
      f.applies += 1; s.backing.set(MAIN, `new_bpf_${f.applies}`); return { sent: true };
    };
    f.prove = async ({ declaration }) => ({ savedProof: null, acknowledgedRoot: f.applies > 0, records: [rec('bpf', f.key, MAIN)], proof: PROOF,
      consumerState: { declaration: { flow: flowOf(declaration), applied: sha(flowOf(declaration)), backing: s.backing.get(MAIN) }, stages: {} }, publication: null, proofSchema: 'bpf-v1' });
    return f;
  };
  assert.deepEqual((await runManagedFeature(feature(OLD))).result, { committed: true, recovered: false });
  const read = () => context(s.dir, createPublicationBarrier()).store;
  const first = read().readGroup('bpf', 'lead/sale').committed;

  // A feature that answers no-op for a roles-only change leaves the stale original: the store never refreshes it alone.
  const stale = feature(NEW, { declarationOnlyIsNoop: true });
  assert.deepEqual((await runManagedFeature(stale)).result, { noop: true });
  assert.deepEqual(read().readGroup('bpf', 'lead/sale').committed.originalDeclaration, OLD);

  const requests = s.wire.log.length;
  const roles = feature(NEW);
  assert.deepEqual((await runManagedFeature(roles)).result, { committed: true, recovered: false });
  const g = read().readGroup('bpf', 'lead/sale');
  assert.deepEqual([roles.applies, s.wire.log.length - requests], [0, 0], 'nothing sent');
  assert.deepEqual(g.committed.originalDeclaration, NEW, 'today\'s authored input, roles included');
  assert.notEqual(g.committed.generation, first.generation);
  assert.deepEqual(g.committed.consumerState, first.consumerState, 'the workflow\'s own state as it was');
  assert.deepEqual([g.pending, g.effects], [null, []], 'no attempt and no effect left');
  const again = feature(NEW);
  assert.deepEqual((await runManagedFeature(again)).result, { noop: true }, 'the identical rerun');
});
test('declaration: a replacement declaration the store refuses keeps the prepared attempt, its bytes, its token and its hold', async () => {
  // The last four put credentials in the URL's userinfo behind whitespace, a no-break space or a custom scheme.
  for (const url of ['https://contoso.com/x?access_token=abc', 'https://contoso.com/x?%61ccess_token=abc',
    'https://fixture [email protected]/', 'https://fixture:synthetic [email protected]/', 'https://fixture\u00a0[email protected]/', 'custom://fixture [email protected]/']) {
    const s = await setup();
    await runManagedFeature({ ...ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: s.store, barrier: s.barrier });
    const g = s.store.readGroup('form', 'account/main').committed;
    const old = s.store.prepareAttempt({ family: 'form', key: 'account/main', baseGeneration: g.generation, root: { kind: 'form', key: 'account/main', id: MAIN }, knownScopes: [ACCOUNT], declarationSha256: H('e'), declaration: { name: 'Original' }, publication: { scope: ACCOUNT, state: 'owed' } });
    const before = fs.readFileSync(s.store.file, 'utf8');
    const m = await nextRun(s);
    assert.equal(m.barrier.allowScope(ACCOUNT, 'a sibling'), false, 'the prepared attempt is held');
    const p = declaring(ports(s.wire, m.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' }), { name: 'Replacement', url });
    const calls = [];
    const apply = p.apply;
    p.apply = async (a) => { calls.push('apply'); return apply(a); };
    assert.equal(await codeOf(runManagedFeature({ ...p, store: m.store, barrier: m.barrier })), CODES.declarationRefused, url);
    assert.equal(fs.readFileSync(s.store.file, 'utf8'), before, `${url}: the bytes kept`);
    assert.equal(m.store.readGroup('form', 'account/main').pending.token, old, `${url}: the token kept`);
    assert.equal(m.barrier.allowScope(ACCOUNT, 'a sibling'), false, `${url}: the hold kept`);
    assert.deepEqual([calls, s.wire.log.filter(isPatch)], [[], []], `${url}: nothing sent`);
  }
});

// A carried publish: the build saved something unmanaged on a table and publishes it through the barrier
// (lib/managed-scope-publisher.js routes it here with `carry: true`). The table's managed groups owe nothing, yet the
// one request ships their saved layers too, so it is journaled on them, with the layers read just before it leaves.
const carryTable = (sdk, store, barrier) => publishManagedScope({
  store, barrier, scope: ACCOUNT, groups: [], client: sdk.dataverse, path: 'table account', carry: true,
  publish: async () => { const r = await publishTablesXml(sdk.dataverse, ['account']); if (!r.ok) throw Object.assign(new Error(r.reason), { code: 'publish-failed' }); },
});

const caught = async (p) => { try { await p; } catch (e) { return e; } return null; };
const pubOf = (store, key = 'account/main') => store.readGroup('form', key).committed.publication;
// Every refusal over an unconfirmed publish names that dispatch as data: its token, the scope's typed approval and the remedy.
const shapeOf = (e) => [e.code, e.dispatchToken, e.approval, e.remedy];
const blockedBy = (token, scope = ACCOUNT) => [PUBLICATION_UNCONFIRMED, token, publicationRiskApproval(scope, token), publicationRemedy(scope, token)];
const editMain = (s, p, formxml) => runManagedFeature({ ...ports(s.wire, p.sdk, { key: 'account/main', id: MAIN, formxml }), client: p.sdk.dataverse, store: p.store, barrier: p.barrier });
// The table publish's answer is lost: the service answers 503 and does not apply it (a delayed completion is driven by
// the test that needs one).
const loseCarry = (s, p) => {
  s.wire.script((e) => /PublishXml/.test(e.path), { statusCode: 503, body: { error: { code: '0x80040216', message: 'gateway' } }, unapplied: true });
  return carryTable(p.sdk, p.store, p.barrier);
};
test('carry: a lost table publish that pays no debt and re-ships only live layers is journaled with its layer evidence and fences the table in every later invocation, a delayed completion included; only the maker\'s typed acceptance releases it', async () => {
  const s = await setup();
  await runManagedFeature({ ...ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: s.store, barrier: s.barrier });
  await publishForms(s.sdk, s.store, s.barrier, [MAIN_G]);
  const settled = pubOf(s.store);
  assert.equal(settled.state, 'confirmed');

  // An ordinary build of the next run saves something unmanaged on account and publishes the table; the answer is lost.
  const a = await nextRun(s);
  assert.deepEqual(a.debt, []);
  const lostErr = await caught(loseCarry(s, a));
  assert.equal(lostErr.code, PUBLICATION_UNCONFIRMED, 'the carried publish is sent and its outcome is not proved');
  assert.equal(s.wire.publishes('account').length, 2, 'the ordinary publish is sent once');
  const pub = pubOf(a.store);
  assert.notEqual(pub.dispatchToken, settled.dispatchToken);
  const live = settled.desiredSha256;
  assert.deepEqual(pub, { ...settled, state: 'unconfirmed', dispatchToken: pub.dispatchToken, carriedFrom: { state: 'confirmed', dispatchToken: settled.dispatchToken, publishedSha256: live, savedSha256: live } }, 'journaled with the layers read before the send; the desired hash is as committed');
  assert.deepEqual(shapeOf(lostErr), blockedBy(pub.dispatchToken), 'the lost send names its own dispatch');

  // Invocation 2: the published layer already showed the carried content before the send, so reading it again is no
  // evidence that the lost request ended. Nothing is edited or published, and the error names the way out.
  const b = await nextRun(s);
  assert.deepEqual(b.debt.map((d) => d.kind), ['uncertain']);
  const writesBefore = s.wire.writes().length;
  const refused = await caught(editMain(s, b, '<form v="2"/>'));
  assert.equal(refused.code, PUBLICATION_UNCONFIRMED);
  assert.deepEqual(shapeOf(refused.cause), blockedBy(pub.dispatchToken), 'the settlement refusal (the halt\'s cause) names the way out');
  assert.ok(refused.cause.message.endsWith(publicationRemedy(ACCOUNT, pub.dispatchToken)), 'its message keeps the remedy');
  assert.deepEqual(pubOf(b.store), pub, 'never confirmed from an observation that was already true before the send');
  assert.deepEqual(await confirmUncertainPublication({ store: b.store, barrier: b.barrier, scope: ACCOUNT, client: b.sdk.dataverse }), { confirmed: [], unconfirmed: [{ ...MAIN_G, code: PUBLICATION_UNCONFIRMED }] });
  // The publication adapter refuses the same way: a group passed in `groups` whose publish is uncertain, and a carry
  // over a scope one covers.
  assert.deepEqual(shapeOf(await caught(publishForms(b.sdk, b.store, b.barrier, [MAIN_G]))), blockedBy(pub.dispatchToken), 'a group passed whose publish is uncertain');
  assert.deepEqual(shapeOf(await caught(carryTable(b.sdk, b.store, b.barrier))), blockedBy(pub.dispatchToken), 'a covered group of the uncertain dispatch');

  // Invocation 3, while the old request may still run: no PATCH, not even one whose proof would fail.
  const c = await nextRun(s);
  assert.equal(await codeOf(editMain(s, c, '<form v="unproved"/>')), PUBLICATION_UNCONFIRMED);
  assert.equal(s.wire.writes().length, writesBefore, 'no PATCH and no publish in any later invocation');
  // The service completes the old request now, with no client request: it publishes what is saved, still the carried content.
  for (const [id, row] of s.wire.saved) if (row.objecttypecode === 'account' && row.type !== 0) s.wire.published.set(id, { ...row });
  assert.equal(s.wire.published.get(MAIN).formxml, '<form v="1"/>', 'no unproved edit was exposed');
  const d = await nextRun(s);
  assert.deepEqual(d.debt.map((x) => x.kind), ['uncertain'], 'a run boundary is not evidence either');

  // The way out: the maker's typed acceptance for this scope and this dispatch, recorded in the store.
  const bytes = fs.readFileSync(d.store.file, 'utf8');
  const accept = (args) => codeOf(Promise.resolve().then(() => d.store.acceptUncertainPublication({ scope: ACCOUNT, dispatchToken: pub.dispatchToken, approval: publicationRiskApproval(ACCOUNT, pub.dispatchToken), ...args })));
  assert.equal(await accept({ approval: `publication-risk:table:contact/${pub.dispatchToken}` }), CODES.notSettled);
  // The approval names the dispatch it was printed for: the scope alone, or this scope with another dispatch, accepts nothing.
  assert.equal(await accept({ approval: 'publication-risk:table:account' }), CODES.notSettled);
  assert.equal(await accept({ approval: publicationRiskApproval(ACCOUNT, 'another-dispatch') }), CODES.notSettled);
  assert.equal(await accept({ approval: undefined }), CODES.notSettled);
  assert.equal(await accept({ dispatchToken: 'another-dispatch' }), CODES.notSettled);
  assert.equal(fs.readFileSync(d.store.file, 'utf8'), bytes, 'a refused acceptance writes nothing');
  // Each refusal says it came before the write, so a caller may say nothing was recorded.
  assert.throws(() => d.store.acceptUncertainPublication({ scope: ACCOUNT, dispatchToken: 'another-dispatch', approval: publicationRiskApproval(ACCOUNT, 'another-dispatch') }), (e) => e.code === CODES.notSettled && e.refusedBeforeWrite === true);
  assert.deepEqual(d.store.acceptUncertainPublication({ scope: ACCOUNT, dispatchToken: pub.dispatchToken, approval: publicationRiskApproval(ACCOUNT, pub.dispatchToken) }), { released: [MAIN_G] });
  assert.deepEqual(pubOf(d.store), settled, 'the publication it had before the send is back, and the desired hash never changed');
  assert.deepEqual(JSON.parse(fs.readFileSync(d.store.file, 'utf8')).publicationRiskAcceptances.map((x) => [x.approval, x.dispatchToken]), [[publicationRiskApproval(ACCOUNT, pub.dispatchToken), pub.dispatchToken]]);

  // The run after: the edit is made once.
  const e = await nextRun(s);
  assert.deepEqual(e.debt, []);
  assert.equal((await editMain(s, e, '<form v="2"/>')).result.committed, true);
  assert.deepEqual(s.wire.writes().slice(writesBefore).map((w) => w.method), ['PATCH']);
});

// An older store can hold an attempt beside a publish no read can settle. Retiring a sending or saved attempt is
// refused, and recovering it is refused while the publish is uncertain, so the typed acceptance must not need either
// first: it releases only the publication, and normal recovery then settles the attempt it left in place.
test('acceptance: a pending attempt (prepared, sending or saved) beside an unprovable publish does not block the typed acceptance; it is kept whole and recovered afterwards', async () => {
  const outcomes = [];
  for (const phase of ['prepared', 'sending', 'saved']) {
    const s = await setup();
    await editMain(s, s, '<form v="1"/>');
    await publishForms(s.sdk, s.store, s.barrier, [MAIN_G]);
    const committed = s.store.readGroup('form', 'account/main').committed;
    const token = s.store.prepareAttempt({ family: 'form', key: 'account/main', root: committed.root, baseGeneration: committed.generation, declarationSha256: H('a'), knownScopes: [ACCOUNT] });
    if (phase !== 'prepared') {
      const { epoch } = s.store.markSending(token, { ...expected(MAIN), baseObservation: { rowVersion: null, savedSha256: committed.publication.desiredSha256 } }, { observed: true, claim: 'first' });
      if (phase === 'saved') {
        s.store.noteAttemptDispatch(token, epoch);
        s.store.noteSaved(token, { proof: { savedSha256: committed.publication.desiredSha256 }, acknowledgedRoot: false });
      }
    }
    // What an older store could hold: the group's publish lost while it carried only layers already live.
    const env = JSON.parse(fs.readFileSync(s.store.file, 'utf8'));
    const p = env.groups.find((g) => g.family === 'form' && g.key === 'account/main').publication;
    p.carriedFrom = { state: p.state, dispatchToken: p.dispatchToken, publishedSha256: p.desiredSha256, savedSha256: p.desiredSha256 };
    p.state = 'unconfirmed';
    p.dispatchToken = 'older-lost-carry';
    fs.writeFileSync(s.store.file, `${JSON.stringify(env, null, 2)}\n`);
    const n = await nextRun(s);
    const pending = n.store.readGroup('form', 'account/main').pending;
    const writes = s.wire.writes().length;
    // Before: recovery is refused while the publish is uncertain, and a sending or saved attempt is never retired. (A
    // prepared one is retired by the run itself, as before: it was never sent.)
    if (phase !== 'prepared') assert.equal(await codeOf(editMain(s, n, '<form v="1"/>')), PUBLICATION_UNCONFIRMED, phase);
    if (phase !== 'prepared') assert.equal(await codeOf(Promise.resolve().then(() => n.store.retireUnsentAttempt({ token, baseGeneration: committed.generation }))), CODES.pending, phase);
    // The approval, dispatch token and scope checks are unchanged, and a refusal writes nothing.
    const bytes = fs.readFileSync(n.store.file, 'utf8');
    const accept = (args) => n.store.acceptUncertainPublication({ scope: ACCOUNT, dispatchToken: 'older-lost-carry', approval: publicationRiskApproval(ACCOUNT, 'older-lost-carry'), ...args });
    for (const args of [{ approval: 'publication-risk:table:contact/older-lost-carry' }, { approval: 'publication-risk:table:account' }, { dispatchToken: 'another-dispatch' }, { scope: { type: 'table', table: 'contact' } }]) {
      assert.equal(await codeOf(Promise.resolve().then(() => accept(args))), CODES.notSettled, `${phase}: ${JSON.stringify(args)}`);
      assert.equal(fs.readFileSync(n.store.file, 'utf8'), bytes);
    }
    assert.deepEqual(accept({}), { released: [MAIN_G] }, phase);
    const after = n.store.readGroup('form', 'account/main');
    assert.deepEqual(after.pending, pending, `${phase}: the attempt, its expected proof and its saved observation are kept whole`);
    assert.equal(after.committed.publication.state, committed.publication.state, `${phase}: the publication it had before is back`);
    assert.deepEqual(JSON.parse(fs.readFileSync(n.store.file, 'utf8')).publicationRiskAcceptances.map((a) => a.dispatchToken), ['older-lost-carry']);
    // The next invocation settles the attempt by the usual recovery.
    const m = await nextRun(s);
    const result = (await editMain(s, m, '<form v="1"/>')).result;
    outcomes.push([phase, result.committed === true, s.wire.writes().length - writes]);
    assert.equal(m.store.readGroup('form', 'account/main').pending, null, phase);
  }
  // A sending or saved attempt whose change is already what the service holds commits read-only: no write at all.
  // The prepared one was never sent: the run retires it and finds nothing to change.
  assert.deepEqual(outcomes, [['prepared', false, 0], ['sending', true, 0], ['saved', true, 0]]);
});

test('carry: a carried group is journaled with the layers read before the send; a definite no-start restores it; a send answered and read back settles under its own token; a lost one settles read-only only once a layer it changed shows', async () => {
  const s = await setup();
  await runManagedFeature({ ...ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: s.store, barrier: s.barrier });
  const generation = s.store.readGroup('form', 'account/main').committed.generation;
  // The earlier shape without layer evidence is kept only for a settled group with a desired hash: an owed group, whose
  // debt this send does not pay, is never carried without the layers read before the send.
  assert.equal(pubOf(s.store).state, 'owed');
  const owedBefore = fs.readFileSync(s.store.file, 'utf8');
  assert.equal(await codeOf(Promise.resolve().then(() => s.store.markPublishDispatch({ scope: ACCOUNT, token: 'carry-0', carried: [{ ...MAIN_G, generation }] }))), CODES.notSettled);
  assert.equal(fs.readFileSync(s.store.file, 'utf8'), owedBefore);
  await publishForms(s.sdk, s.store, s.barrier, [MAIN_G]);
  const settled = pubOf(s.store);
  const h = settled.desiredSha256;

  // The store: a group committed again since it was read, or carried without both layers, refuses the mark; nothing is written.
  const before = fs.readFileSync(s.store.file, 'utf8');
  const mark = (carried) => codeOf(Promise.resolve().then(() => s.store.markPublishDispatch({ scope: ACCOUNT, token: 'carry-1', carried })));
  assert.equal(await mark([{ ...MAIN_G, generation: generation + 1, publishedSha256: h, savedSha256: h }]), CODES.conflict);
  assert.equal(await mark([{ ...MAIN_G, generation, publishedSha256: h }]), CODES.notSettled);
  assert.equal(fs.readFileSync(s.store.file, 'utf8'), before);
  s.store.markPublishDispatch({ scope: ACCOUNT, token: 'carry-1', carried: [{ ...MAIN_G, generation, publishedSha256: h, savedSha256: h }] });
  assert.deepEqual(pubOf(s.store), { ...settled, state: 'dispatching', dispatchToken: 'carry-1', carriedFrom: { state: 'confirmed', dispatchToken: settled.dispatchToken, publishedSha256: h, savedSha256: h } });
  s.store.notePublishOutcome({ token: 'carry-1', outcome: 'definite-no-start' });
  assert.deepEqual(pubOf(s.store), settled, 'the settled publication is back, token and all');

  // A carried publish that answers success and is read back settles under its own token in the same invocation.
  assert.deepEqual(await carryTable(s.sdk, s.store, s.barrier), { sent: true, withheld: false, confirmed: [] });
  const after = pubOf(s.store);
  assert.deepEqual([after.state, after.dispatchToken === settled.dispatchToken, 'carriedFrom' in after], ['confirmed', false, false]);

  // A second form owes a publish this carry does not pay: its published layer differs from its saved one, so the send
  // changes it, and that change is the evidence a later read can show.
  committedForm(s, { id: QUICK, key: 'account/quick', publishedXml: '<form q="1"/>', savedXml: '<form q="2"/>' });
  assert.equal(await codeOf(loseCarry(s, s)), PUBLICATION_UNCONFIRMED);
  const lost = pubOf(s.store, 'account/quick');
  assert.deepEqual([lost.state, lost.carriedFrom.state, lost.carriedFrom.savedSha256 === lost.desiredSha256, lost.carriedFrom.publishedSha256 === lost.carriedFrom.savedSha256], ['unconfirmed', 'owed', true, false]);
  const sends = s.wire.publishes('account').length;
  // Before the service completes it, every layer reads as it did before the send: nothing is settled.
  const n = await nextRun(s);
  assert.equal((await confirmUncertainPublication({ store: n.store, barrier: n.barrier, scope: ACCOUNT, client: n.sdk.dataverse })).confirmed.length, 0);
  assert.equal(pubOf(n.store, 'account/quick').state, 'unconfirmed');
  // The service completes it: the changed layer shows, and the next run settles the whole dispatch read-only.
  s.wire.published.set(QUICK, { ...s.wire.saved.get(QUICK) });
  const m = await nextRun(s);
  const done = await confirmUncertainPublication({ store: m.store, barrier: m.barrier, scope: ACCOUNT, client: m.sdk.dataverse });
  assert.deepEqual([done.confirmed.length, done.unconfirmed.length], [2, 0]);
  const quick = pubOf(m.store, 'account/quick');
  assert.deepEqual([quick.state, quick.dispatchToken, quick.desiredSha256, 'carriedFrom' in quick], ['confirmed', lost.dispatchToken, lost.desiredSha256, false], 'the debt the carry paid is confirmed');
  assert.deepEqual([pubOf(m.store).state, 'carriedFrom' in pubOf(m.store)], ['confirmed', false]);
  assert.equal(s.wire.publishes('account').length, sends, 'nothing was sent to confirm it');
  assert.deepEqual((await nextRun(s)).debt, [], 'the run after installs no block');
});

test('carry: every covered shape is journaled before the send — a maker\'s published change (saved = published, not desired), a not-needed form and a not-needed dashboard with no desired hash — and a lost send fences the scope in the next invocation without inventing debt', async () => {
  const fencedNextRun = async (s, scope, sendAgain) => {
    const n = await nextRun(s);
    assert.deepEqual(n.debt.map((d) => d.kind), ['uncertain']);
    assert.equal(n.barrier.allowScope(scope, 'a restart'), false);
    const writes = s.wire.writes().length;
    assert.equal(await codeOf(sendAgain(n)), PUBLICATION_UNCONFIRMED);
    assert.equal(s.wire.writes().length, writes, 'a restart does not forget the lost dispatch');
  };

  // A maker published a change of the managed form after it was confirmed: saved = published, and neither is desired.
  const a = await setup();
  await runManagedFeature({ ...ports(a.wire, a.sdk, { key: 'account/main', id: MAIN, formxml: '<form v="1"/>' }), store: a.store, barrier: a.barrier });
  await publishForms(a.sdk, a.store, a.barrier, [MAIN_G]);
  const desired = pubOf(a.store).desiredSha256;
  a.wire.putForm({ ...a.wire.saved.get(MAIN), formxml: '<form maker="published"/>' }, { publishedToo: true });
  assert.equal(await codeOf(loseCarry(a, a)), PUBLICATION_UNCONFIRMED);
  const pa = pubOf(a.store);
  assert.deepEqual([pa.state, pa.desiredSha256, pa.carriedFrom.state, pa.carriedFrom.publishedSha256 === pa.carriedFrom.savedSha256, pa.carriedFrom.savedSha256 === desired], ['unconfirmed', desired, 'confirmed', true, false]);
  await fencedNextRun(a, ACCOUNT, (n) => carryTable(n.sdk, n.store, n.barrier));

  // A form whose saved layer equalled its published one at the commit: not-needed, no desired hash.
  const b = await setup();
  committedForm(b, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="1"/>', state: 'not-needed' });
  assert.equal(await codeOf(loseCarry(b, b)), PUBLICATION_UNCONFIRMED);
  const pb = pubOf(b.store);
  assert.deepEqual([pb.state, pb.desiredSha256, pb.carriedFrom.state, pb.carriedFrom.dispatchToken, pb.carriedFrom.publishedSha256 === pb.carriedFrom.savedSha256], ['unconfirmed', null, 'not-needed', null, true]);
  await fencedNextRun(b, ACCOUNT, (n) => carryTable(n.sdk, n.store, n.barrier));

  // A no-write adoption of an already-published dashboard: not-needed, no desired hash, no token. Its carry goes
  // through the SDK's publishArtifact, which RETURNS a failed publish ({ shipped: false }) instead of throwing.
  const c = await setup();
  const dash = ports(c.wire, c.sdk, { family: 'dashboard', key: 'ops', id: DASH, formxml: '<dash v="1"/>' });
  const apply = dash.apply;
  dash.apply = async (args) => { const answer = await apply(args); c.wire.published.set(DASH, { ...c.wire.saved.get(DASH) }); return answer; };
  await runManagedFeature({ ...dash, store: c.store, barrier: c.barrier });
  assert.deepEqual(c.store.readGroup('dashboard', 'ops').committed.publication, { scope: dashScope(DASH), state: 'not-needed', desiredSha256: null, dispatchToken: null });
  let answer;
  const carryDash = (n) => publishManagedScope({
    store: n.store, barrier: n.barrier, scope: dashScope(DASH), groups: [], client: n.sdk.dataverse, path: 'dashboard ops', carry: true,
    publish: async () => { await n.sdk.fetchArtifact('dashboard', DASH); answer = await n.sdk.publishArtifact('dashboard', DASH); return answer; },
  });
  c.wire.script((e) => /PublishXml/.test(e.path), { statusCode: 503, body: { error: { code: '0x80040216', message: 'gateway' } }, unapplied: true });
  assert.equal(await codeOf(carryDash(c)), PUBLICATION_UNCONFIRMED);
  assert.equal(answer && answer.shipped, false, 'the SDK answered the 503 without throwing');
  const pc = c.store.readGroup('dashboard', 'ops').committed.publication;
  assert.deepEqual([pc.state, pc.desiredSha256, pc.carriedFrom.state, pc.carriedFrom.dispatchToken], ['unconfirmed', null, 'not-needed', null]);
  await fencedNextRun(c, dashScope(DASH), carryDash);
});

test('carry: a publish() that returns a failed answer instead of throwing is never read back as a success; its debt settles read-only once it shows', async () => {
  const s = await setup();
  committedForm(s, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
  // The request reached the service and applied, but the callback reports it as not shipped: the outcome is unknown.
  const out = await caught(publishManagedScope({
    store: s.store, barrier: s.barrier, scope: ACCOUNT, groups: [MAIN_G], client: s.sdk.dataverse, path: 'managed forms of account',
    publish: async () => { await publishTablesXml(s.sdk.dataverse, ['account']); return { shipped: false, publish: { kind: 'failed', error: { statusCode: 503 } } }; },
  }));
  assert.equal(out.code, PUBLICATION_UNCONFIRMED);
  assert.deepEqual(shapeOf(out), blockedBy(pubOf(s.store).dispatchToken));
  assert.equal(pubOf(s.store).state, 'unconfirmed', 'not confirmed by the read-back of an answer that said it failed');
  // The debt is a layer the send changed: the next run sees it live and settles it without sending.
  const sends = s.wire.publishes('account').length;
  const n = await nextRun(s);
  assert.deepEqual(await confirmUncertainPublication({ store: n.store, barrier: n.barrier, scope: ACCOUNT, client: n.sdk.dataverse }), { confirmed: [MAIN_G], unconfirmed: [] });
  assert.equal(s.wire.publishes('account').length, sends);
});

test('carry: a publish() answer is judged by its publish kind, never by `shipped` — submitted, verified and unverifiable are read back; failed, an unknown kind, a no-request kind beside a sent request and `shipped: false` with no kind are unknown', async () => {
  // The SDK's own successful publish answers `shipped: false, kind: 'submitted'` (shipped is kind === 'verified').
  const d = await setup();
  const dash = ports(d.wire, d.sdk, { family: 'dashboard', key: 'ops', id: DASH, formxml: '<dash v="1"/>' });
  const apply = dash.apply;
  dash.apply = async (args) => { const r = await apply(args); d.wire.published.set(DASH, { ...d.wire.saved.get(DASH) }); return r; };
  await runManagedFeature({ ...dash, store: d.store, barrier: d.barrier });
  let answer;
  const sent = await publishManagedScope({
    store: d.store, barrier: d.barrier, scope: dashScope(DASH), groups: [], client: d.sdk.dataverse, path: 'dashboard ops', carry: true,
    publish: async () => { await d.sdk.fetchArtifact('dashboard', DASH); answer = await d.sdk.publishArtifact('dashboard', DASH); return answer; },
  });
  assert.deepEqual([answer.shipped, answer.publish.kind], [false, 'submitted'], 'the SDK\'s ordinary success answer');
  assert.deepEqual(sent, { sent: true, withheld: false, confirmed: [] });
  assert.equal(d.store.readGroup('dashboard', 'ops').committed.publication.state, 'not-needed', 'read back and settled under its own token');

  // A form that owes a publish, sent through a callback that returns each kind after a request that applied.
  const owe = async (returned, { send = true } = {}) => {
    const s = await setup();
    committedForm(s, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
    const out = await caught(publishManagedScope({
      store: s.store, barrier: s.barrier, scope: ACCOUNT, groups: [MAIN_G], client: s.sdk.dataverse, path: 'managed forms of account',
      publish: async () => { if (send) await publishTablesXml(s.sdk.dataverse, ['account']); return returned; },
    }));
    return { code: out ? out.code : null, state: pubOf(s.store).state, message: out ? out.message : '' };
  };
  for (const kind of ['submitted', 'verified', 'unverifiable']) {
    assert.deepEqual(await owe({ shipped: kind === 'verified', publish: { kind } }), { code: null, state: 'confirmed', message: '' }, kind);
  }
  for (const [label, returned] of [
    ['failed', { shipped: false, publish: { kind: 'failed', error: { statusCode: 503 } } }],
    ['an unknown kind', { shipped: false, publish: { kind: 'queued' } }],
    ['a no-request kind beside a sent request', { shipped: false, publish: { kind: 'notApplicable' } }],
    ['shipped false with no kind', { shipped: false }],
  ]) {
    const r = await owe(returned);
    assert.deepEqual([r.code, r.state], [PUBLICATION_UNCONFIRMED, 'unconfirmed'], label);
  }
  // No request at all, and the answer says so: the barrier saw nothing pass its permit and fails closed, as before.
  const none = await owe({ shipped: false, publish: { kind: 'none' } }, { send: false });
  assert.deepEqual([none.code, none.state], [PUBLICATION_UNCONFIRMED, 'unconfirmed']);
  assert.match(none.message, /did not pass the publication barrier/);
});

test('publication refusals: a send answered but not read back names its own dispatch as data; a send with no managed group on the scope journals nothing and names none', async () => {
  const waits = [];
  const send = (s, readers) => caught(publishManagedScope({
    store: s.store, barrier: s.barrier, scope: ACCOUNT, groups: [MAIN_G], client: s.sdk.dataverse, path: 'managed forms of account', ...(readers ? { readers } : {}),
    publish: () => publishTablesXml(s.sdk.dataverse, ['account']), settle: { sleep: async (ms) => { waits.push(ms); } },
  }));
  // The publish answers success but the service did not apply it: the read-back does not show the debt, nor does any
  // read after each of the bounded settle delays.
  const a = await setup();
  committedForm(a, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
  a.wire.script((e) => /PublishXml/.test(e.path), { statusCode: 204, unapplied: true });
  const unshown = await send(a);
  assert.match(unshown.message, /does not show what it shipped/);
  assert.deepEqual(waits, [...PUBLICATION_SETTLE_DELAYS_MS], 'the read-back is made again after each settle delay, and no more');
  assert.equal(a.wire.publishes('account').length, 1, 'a read-back that never shows the send is never answered with a second publish');
  assert.deepEqual(shapeOf(unshown), blockedBy(pubOf(a.store).dispatchToken));
  // The saved layer is still the one the publish shipped, which is also what a platform that reads the two layers apart
  // shows: the stop names that case and what the maker checks, and the next run's fresh read names it again.
  assert.match(unshown.message, /does not show what it shipped: managed form "account\/main" its saved layer is still the one the publish shipped, yet the published layer reads differently: either the publish did not put it live, or the platform reads this artifact's saved and published layers apart/);
  assert.match(unshown.message, /In the maker, compare what is published with the spec: if it matches, accept the risk with the publication-risk approval this build prints/);
  const labelsOf = async (s) => {
    const n = await nextRun(s);
    const labels = [];
    const r = await confirmUncertainPublication({ store: n.store, barrier: { blockScope: (scope, label) => labels.push(label) }, scope: ACCOUNT, client: n.sdk.dataverse });
    assert.deepEqual(r.confirmed, []);
    return labels.join('\n');
  };
  assert.match(await labelsOf(a), /a fresh read did not prove it ended: its saved layer is still the one the publish shipped, yet the published layer reads differently.*; .*publication-risk:table:account\//);
  // Control: something saved over the form after the publish, so its saved layer is not what was shipped any more. It
  // stays unconfirmed as before, and neither stop says the layers read apart.
  const m = await setup();
  committedForm(m, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
  m.wire.script((e) => /PublishXml/.test(e.path), { statusCode: 204, unapplied: true });
  const moved = await caught(publishManagedScope({
    store: m.store, barrier: m.barrier, scope: ACCOUNT, groups: [MAIN_G], client: m.sdk.dataverse, path: 'managed forms of account', settle: { sleep: async () => {} },
    publish: async () => { const r = await publishTablesXml(m.sdk.dataverse, ['account']); m.wire.saved.get(MAIN).formxml = '<form v="3"/>'; return r; },
  }));
  assert.equal(moved && moved.code, PUBLICATION_UNCONFIRMED);
  assert.equal(moved.message, 'the publish was sent and the published layer does not show what it shipped');
  assert.doesNotMatch(await labelsOf(m), /still the one the publish shipped|read apart/);  // The read-back itself fails.
  const b = await setup();
  committedForm(b, { id: MAIN, key: 'account/main', publishedXml: '<form v="1"/>', savedXml: '<form v="2"/>' });
  let reads = 0;
  const { LAYER_READERS } = require('../lib/managed-layer-readers.js');
  const unread = await send(b, { ...LAYER_READERS, form: async (...args) => { reads += 1; if (reads > 1) throw new Error('reset'); return LAYER_READERS.form(...args); } });
  assert.match(unread.message, /could not be read back/);
  assert.deepEqual(shapeOf(unread), blockedBy(pubOf(b.store).dispatchToken));
  // A carry over a table with no managed group: nothing is journaled, so there is no dispatch to accept.
  const c = await setup();
  c.wire.script((e) => /PublishXml/.test(e.path), { statusCode: 503, body: { error: { code: '0x80040216', message: 'gateway' } }, unapplied: true });
  const bare = await caught(carryTable(c.sdk, c.store, c.barrier));
  assert.deepEqual(shapeOf(bare), [PUBLICATION_UNCONFIRMED, undefined, undefined, undefined]);
});

// --- Caption diagnostics of an adopted form (lib/form-caption-diagnostics.js) --------------------------------------
// A form the build adopted can read one way saved and another way published in one cell's base-language caption, with
// the publish's saved layer unchanged. No read tells a platform read projection from a maker's unpublished edit, so the
// stop stays exactly as strict as before; it only names the cell and the language. Every helper failure must leave the
// generic stop, its data, its requests and the store exactly as a run with no diagnostic leaves them.
const CAP_TAB = '0a0a0a0a-0000-4000-8000-0000000000a1';
const CAP_SECTION = '0b0b0b0b-0000-4000-8000-0000000000b1';
const CAP_CELL = '0c0c0c0c-0000-4000-8000-0000000000c1';
const CAP_CELL2 = '0d0d0d0d-0000-4000-8000-0000000000d1';
const cellXml = (id, caption, { control = 'subgrid_issues', lcid = '1033', more = '' } = {}) => `<cell id="{${id.toUpperCase()}}"><labels><label description="${caption}" languagecode="${lcid}" />${more}</labels><control id="${control}" classid="{E7A81278-8635-4D9E-8D4D-59480B391C5B}" /></cell>`;
const captionForm = (cells, { section = CAP_SECTION } = {}) => `<form><tabs><tab id="{${CAP_TAB}}" name="general"><labels><label description="General" languagecode="1033" /></labels><columns><column width="100%"><sections><section id="{${section}}" name="main"><labels><label description="Main" languagecode="1033" /></labels><rows><row>${cells}</row></rows></section></sections></column></columns></tab></tabs></form>`;
const SAVED_SPLIT = captionForm(cellXml(CAP_CELL, 'Inspections'));
const PUBLISHED_SPLIT = captionForm(cellXml(CAP_CELL, 'Issues'));
const CAPTION_HELPER = require('node:path').join(__dirname, '..', 'lib', 'form-caption-diagnostics.js');

// Run `fn` with the caption helper module replaced, in the module cache, by `impl` over the real one (a loader stub for
// this test only: production code has no switch for it), and put the cache back after.
async function withCaptionHelper(impl, fn) {
  const Module = require('node:module');
  const before = require.cache[CAPTION_HELPER];
  const real = fs.existsSync(CAPTION_HELPER) ? require(CAPTION_HELPER) : {};
  const stub = new Module(CAPTION_HELPER);
  stub.filename = CAPTION_HELPER;
  stub.loaded = true;
  stub.exports = { ...real, ...impl };
  require.cache[CAPTION_HELPER] = stub;
  try { return await fn(); } finally { if (before) require.cache[CAPTION_HELPER] = before; else delete require.cache[CAPTION_HELPER]; }
}
// The store bytes with the tokens a run mints at random named by their order, so two runs compare by what they wrote.
const tokenless = (text) => {
  const seen = new Map();
  return String(text).replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, (t) => { if (!seen.has(t)) seen.set(t, `token-${seen.size}`); return seen.get(t); });
};
// An adopted form whose publish answers success and is not applied: the published read keeps the old caption, the saved
// read the caption the publish shipped.
// `before(s)` arranges the org further before the publish; `wire` is the wire's options.
async function splitPublish({ origin = 'adopted', savedXml = SAVED_SPLIT, publishedXml = PUBLISHED_SPLIT, before, wire } = {}) {
  const s = await setup(wire);
  committedForm(s, { id: MAIN, key: 'account/main', publishedXml, savedXml, origin });
  if (before) before(s);
  s.wire.script((e) => /PublishXml/.test(e.path), { statusCode: 204, unapplied: true });
  const at = s.wire.log.length;
  const e = await caught(publishManagedScope({
    store: s.store, barrier: s.barrier, scope: ACCOUNT, groups: [MAIN_G], client: s.sdk.dataverse, path: 'managed forms of account',
    publish: () => publishTablesXml(s.sdk.dataverse, ['account']), settle: { sleep: async () => {} },
  }));
  const token = pubOf(s.store).dispatchToken;
  return {
    s, e, token,
    requests: s.wire.log.slice(at).map((x) => `${x.method} ${x.path}`),
    store: tokenless(fs.readFileSync(s.store.file, 'utf8')),
    shape: [e.code, e.dispatchToken === token, e.approval === publicationRiskApproval(ACCOUNT, token), e.remedy === publicationRemedy(ACCOUNT, token)],
  };
}
// The next run's read-only confirmation of that dispatch: the scope's block labels, its answer, and whether it wrote.
async function splitConfirm(s) {
  const n = await nextRun(s);
  const labels = [];
  const before = fs.readFileSync(n.store.file, 'utf8');
  const at = s.wire.log.length;
  const r = await confirmUncertainPublication({ store: n.store, barrier: { blockScope: (scope, label) => labels.push(label) }, scope: ACCOUNT, client: n.sdk.dataverse });
  return { r, labels, unchanged: fs.readFileSync(n.store.file, 'utf8') === before, requests: s.wire.log.slice(at).map((x) => `${x.method} ${x.path}`) };
}

test('caption diagnostics: an adopted form whose saved and published captions differ in one cell stays unconfirmed, and its stop names that cell and language — never its text, never in the store', async () => {
  const run = await splitPublish();
  assert.equal(run.e.code, PUBLICATION_UNCONFIRMED);
  assert.deepEqual(run.shape, [PUBLICATION_UNCONFIRMED, true, true, true], 'the dispatch, approval and remedy are the ones it always named');
  assert.equal(pubOf(run.s.store).state, 'unconfirmed', 'a diagnostic confirms nothing');
  assert.match(run.e.message, /does not show what it shipped: managed form "account\/main" its saved layer is still the one the publish shipped/);
  assert.ok(run.e.message.endsWith(`. managed form "account/main": Caption difference at cell ${CAP_CELL} (language 1033). This observation does not show whether the difference is an unpublished edit or a platform read projection.`), run.e.message);
  assert.doesNotMatch(run.e.message, /Inspections|Issues/, 'no caption text is repeated');
  assert.doesNotMatch(fs.readFileSync(run.s.store.file, 'utf8'), /captionDifferences|languageCode|0c0c0c0c/i, 'the diagnostic is never written to the store');
  // The reader answers it beside the two hashes, which are what they would be without it.
  const group = run.s.store.readGroup('form', 'account/main').committed;
  const read = await readSystemFormLayers(run.s.sdk.dataverse, group);
  assert.deepEqual(read.captionDifferences, { entries: [{ cellId: CAP_CELL, languageCode: 1033 }], omittedCount: 0 });
  const created = await readSystemFormLayers(run.s.sdk.dataverse, { ...group, records: group.records.map((r) => ({ ...r, origin: 'created' })) });
  assert.deepEqual(created, { savedSha256: read.savedSha256, publishedSha256: read.publishedSha256 }, 'a created form gets no diagnostic, and the same two hashes');
  // The next run's read-only confirmation names it too, writes nothing, and leaves the dispatch unconfirmed.
  const next = await splitConfirm(run.s);
  assert.deepEqual(next.r.confirmed, []);
  assert.equal(next.unchanged, true);
  assert.match(next.labels.join('\n'), new RegExp(`a fresh read did not prove it ended: its saved layer is still the one the publish shipped.*; .*publication-risk:table:account/.*\\. managed form "account/main": Caption difference at cell ${CAP_CELL} \\(language 1033\\)`));
});

test('caption diagnostics are fail-safe: a helper that throws, answers anything unusable, or a formatter that throws leaves the generic stop, its data, its requests and the store exactly as a run with no diagnostic', async () => {
  let calls = 0;
  const control = await withCaptionHelper({ cellCaptionDifferences: () => { calls += 1; return null; } }, () => splitPublish());
  assert.ok(calls > 0, 'the adopted form\'s layers are offered to the diagnostic helper');
  const controlNext = await withCaptionHelper({ cellCaptionDifferences: () => null }, () => splitConfirm(control.s));
  assert.equal(control.e.message.includes('Caption difference'), false);
  const cases = [
    ['a helper that throws', { cellCaptionDifferences: () => { calls += 1; throw new Error('diagnostic exploded'); } }],
    ['a malformed answer', { cellCaptionDifferences: () => { calls += 1; return { entries: [{ cellId: 'not-a-guid', languageCode: 1033 }], omittedCount: 0 }; } }],
    ['an empty answer', { cellCaptionDifferences: () => { calls += 1; return { entries: [], omittedCount: 0 }; } }],
    ['too many entries', { cellCaptionDifferences: () => { calls += 1; return { entries: Array.from({ length: 9 }, (_, i) => ({ cellId: `0c0c0c0c-0000-4000-8000-00000000000${i}`, languageCode: 1033 })), omittedCount: 0 }; } }],
    ['a getter that throws', { cellCaptionDifferences: () => { calls += 1; return { get entries() { throw new Error('getter'); }, omittedCount: 0 }; } }],
    ['a formatter that throws', { formatCaptionDifferences: () => { calls += 1; throw new Error('formatter exploded'); } }],
    ['a formatter that answers no text', { formatCaptionDifferences: () => { calls += 1; return { text: 'x' }; } }],
  ];
  for (const [label, impl] of cases) {
    calls = 0;
    const run = await withCaptionHelper(impl, () => splitPublish());
    assert.ok(calls > 0, `${label}: the stub was reached`);
    assert.equal(run.e.code, control.e.code, label);
    assert.equal(run.e.message, control.e.message, `${label}: the generic message`);
    assert.deepEqual(run.shape, control.shape, `${label}: the dispatch, approval and remedy`);
    assert.deepEqual(run.requests, control.requests, `${label}: the requests`);
    assert.equal(run.store, control.store, `${label}: the store bytes`);
    assert.equal(pubOf(run.s.store).state, 'unconfirmed', label);
    const next = await withCaptionHelper(impl, () => splitConfirm(run.s));
    assert.deepEqual(next.r, controlNext.r, `${label}: the recovered confirmation`);
    assert.equal(next.unchanged, true, `${label}: the read-only confirmation writes nothing`);
    assert.deepEqual(next.requests, controlNext.requests, `${label}: the confirmation's requests`);
    assert.deepEqual(next.labels.map((l) => l.split(run.token).join('<token>')), controlNext.labels.map((l) => l.split(control.token).join('<token>')), `${label}: the confirmation's block`);
  }
});

test('caption diagnostics compare one cell by its id, its tab, section and control, one language at a time — anything ambiguous or unread names nothing', () => {
  const { cellCaptionDifferences, formatCaptionDifferences } = require('../lib/form-caption-diagnostics.js');
  const pair = (s, p) => cellCaptionDifferences(captionForm(s), captionForm(p));
  assert.deepEqual(pair(cellXml(CAP_CELL, 'A'), cellXml(CAP_CELL, 'B')), { entries: [{ cellId: CAP_CELL, languageCode: 1033 }], omittedCount: 0 });
  assert.equal(pair(cellXml(CAP_CELL, 'A'), cellXml(CAP_CELL, 'A')), null, 'the same caption');
  // A second language on both sides is compared on its own; one on a single side is not reported (no base language is inferred).
  assert.deepEqual(pair(cellXml(CAP_CELL, 'A', { more: '<label description="X" languagecode="3082" />' }), cellXml(CAP_CELL, 'A', { more: '<label description="Y" languagecode="3082" />' })),
    { entries: [{ cellId: CAP_CELL, languageCode: 3082 }], omittedCount: 0 });
  assert.equal(pair(cellXml(CAP_CELL, 'A', { more: '<label description="X" languagecode="3082" />' }), cellXml(CAP_CELL, 'A')), null);
  // An extra cell, a cell that moved section, or holds another control is not a caption difference.
  assert.equal(pair(cellXml(CAP_CELL, 'A') + cellXml(CAP_CELL2, 'Z'), cellXml(CAP_CELL, 'A')), null);
  assert.equal(cellCaptionDifferences(captionForm(cellXml(CAP_CELL, 'A')), captionForm(cellXml(CAP_CELL, 'B'), { section: CAP_CELL2 })), null);
  assert.equal(pair(cellXml(CAP_CELL, 'A'), cellXml(CAP_CELL, 'B', { control: 'subgrid_other' })), null);
  // Ambiguity names nothing: a cell id twice, a language twice in a cell, a language that is not a whole number, unread XML.
  assert.equal(pair(cellXml(CAP_CELL, 'A') + cellXml(CAP_CELL, 'A'), cellXml(CAP_CELL, 'B')), null);
  assert.equal(pair(cellXml(CAP_CELL, 'A', { more: '<label description="C" languagecode="1033" />' }), cellXml(CAP_CELL, 'B')), null);
  assert.equal(pair(cellXml(CAP_CELL, 'A', { lcid: 'en' }), cellXml(CAP_CELL, 'B', { lcid: 'en' })), null);
  assert.equal(cellCaptionDifferences('<form><tabs>', captionForm(cellXml(CAP_CELL, 'B'))), null);
  assert.equal(cellCaptionDifferences(captionForm(cellXml(CAP_CELL, 'A')), null), null);
  // Bounded: eight named, sorted by cell then language, the rest counted.
  const ids = Array.from({ length: 10 }, (_, i) => `0e0e0e0e-0000-4000-8000-0000000000${String(10 + (9 - i))}`);
  const many = cellCaptionDifferences(captionForm(ids.map((id) => cellXml(id, 'A', { control: id })).join('')), captionForm(ids.map((id) => cellXml(id, 'B', { control: id })).join('')));
  assert.equal(many.entries.length, 8);
  assert.equal(many.omittedCount, 2);
  assert.deepEqual(many.entries.map((e) => e.cellId), [...ids].sort().slice(0, 8));
  assert.match(formatCaptionDifferences(many), /^Caption differences at cell 0e0e0e0e-0000-4000-8000-000000000010 \(language 1033\), .*, and 2 more\. This observation does not show/);
  assert.equal(formatCaptionDifferences({ entries: [{ cellId: 'x', languageCode: 1033 }], omittedCount: 0 }), null);
});

test('caption diagnostics never reach a dashboard or a created form, and never change a layer hash', async () => {
  const run = await splitPublish({ origin: 'created' });
  assert.equal(run.e.code, PUBLICATION_UNCONFIRMED);
  assert.doesNotMatch(run.e.message, /Caption difference/, 'a form the build created is not diagnosed');
  const adopted = await splitPublish();
  assert.equal(adopted.e.message.split('. managed form "account/main": Caption difference')[0], run.e.message, 'the same generic stop before the diagnostic');
  assert.deepEqual(adopted.requests, run.requests, 'the same requests');
  // The dashboard reader is not the form reader: an adopted dashboard root gets no diagnostic.
  const { readSystemFormRootLayers } = require('../lib/systemform-published.js');
  const d = await setup();
  d.wire.putForm({ formid: DASH, name: 'Ops', objecttypecode: 'none', type: 0, formxml: PUBLISHED_SPLIT }, { publishedToo: true });
  d.wire.saved.get(DASH).formxml = SAVED_SPLIT;
  const dash = await readSystemFormRootLayers(d.sdk.dataverse, { root: { kind: 'dashboard', key: 'ops', id: DASH }, records: [{ ...rec('dashboard', 'ops', DASH), origin: 'adopted' }] });
  assert.deepEqual(Object.keys(dash).sort(), ['publishedSha256', 'savedSha256']);
});

// Shared form cells (lib/form-caption-sharing.js): once a caption-related publication stop is decided and its table blocked, the
// other forms of that table that hold the stopped form's cell id are read with GETs and shown on a display-only note beside the
// stop, with a second barrier label. The stop itself — its code, message, data, the store and the approval it names — is exactly
// the one a run whose table has no such sharer gives.
const SHARE_PEER = '33333333-3333-4333-8333-333333333301';
const SHARE_FRESH = '33333333-3333-4333-8333-333333333302';
const SHARE_CONTACT = '33333333-3333-4333-8333-333333333303';
const SHARE_OWN_CELL = '0f0f0f0f-0000-4000-8000-0000000000f1';
const PLANNED_SPLIT = captionForm(cellXml(CAP_CELL, 'Planned'));
// Other forms of the org: with `shared`, "Account copy" holds MAIN's cell id behind another control in another section and
// reads the same pair of captions; without it, it holds a cell of its own. A form with a cell of its own and MAIN's captions,
// and a contact form holding MAIN's cell id, are never sharers.
function putNeighbours(s, { shared = true } = {}) {
  const copy = (caption) => captionForm(cellXml(shared ? CAP_CELL : CAP_CELL2, caption, { control: 'subgrid_copy' }), { section: '0e0e0e0e-0000-4000-8000-0000000000e1' });
  const put = (id, name, table, savedXml, publishedXml) => {
    s.wire.putForm({ formid: id, name, objecttypecode: table, type: 2, formxml: publishedXml }, { publishedToo: true });
    s.wire.saved.get(id).formxml = savedXml;
  };
  put(SHARE_PEER, 'Account copy', 'account', copy('Inspections'), copy('Issues'));
  put(SHARE_FRESH, 'Account fresh', 'account', captionForm(cellXml(SHARE_OWN_CELL, 'Inspections')), captionForm(cellXml(SHARE_OWN_CELL, 'Issues')));
  put(SHARE_CONTACT, 'Contact main', 'contact', SAVED_SPLIT, PUBLISHED_SPLIT);
}
const SHARING_LABEL = /^shared form cells observed on table account: 1 cell entry reused by other forms of the table \(read-only observation; see the stop for recovery guidance\)$/;
const isTableListing = (x) => /^systemforms(\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublishedMultiple\(\))?$/i.test(x.path);

// An owed form whose saved layer a maker changed after the commit, in a caption: the drift stop, as a run sees it.
async function sharedDrift({ shared, wire } = {}) {
  const s = await setup(wire);
  committedForm(s, { id: MAIN, key: 'account/main', publishedXml: PUBLISHED_SPLIT, savedXml: PLANNED_SPLIT });
  s.wire.saved.get(MAIN).formxml = SAVED_SPLIT;
  if (shared !== undefined) putNeighbours(s, { shared });
  const at = s.wire.log.length;
  const e = await caught(publishForms(s.sdk, s.store, s.barrier, [MAIN_G]));
  return {
    s, e,
    requests: s.wire.log.slice(at).map((x) => `${x.method} ${x.path}`),
    store: tokenless(fs.readFileSync(s.store.file, 'utf8')),
    withheld: s.barrier.withheld(),
  };
}

test('shared form cells, drift stop: the note names every form holding the cell and its captions, qualifies the publish-or-undo advice, and leaves the stop and the store exactly as without a sharer', async () => {
  const run = await sharedDrift({ shared: true });
  const control = await sharedDrift({ shared: false });
  assert.equal(run.e.code, 'create-completion-required');
  assert.equal(run.e.message, control.e.message, 'the same message');
  assert.deepEqual(Object.keys(run.e), Object.keys(control.e), 'the same data');
  assert.equal(JSON.stringify(run.e), JSON.stringify(control.e));
  assert.equal(run.store, control.store, 'the same store bytes');
  assert.deepEqual(run.requests, control.requests, 'the same requests');
  assert.ok(run.requests.every((r) => r.startsWith('GET ')), run.requests.join('\n'));
  assert.equal(run.s.wire.publishes().length, 0);
  assert.equal(pubOf(run.s.store).state, 'owed');
  assert.equal(Object.prototype.propertyIsEnumerable.call(run.e, 'formCaptionSharingNote'), false);
  const note = run.e.formCaptionSharingNote;
  assert.ok(note.includes(`Cell ${CAP_CELL}, language 1033, of stopped form ${MAIN}: 2 forms of the table hold this cell id.`), note);
  assert.ok(note.includes(`  form ${MAIN} (name "Main"): saved "Inspections"; published "Issues"; the cell is in the saved and the published read.`), note);
  assert.ok(note.includes(`  form ${SHARE_PEER} (name "Account copy"): saved "Inspections"; published "Issues"; the cell is in the saved and the published read.`), note);
  assert.match(note, /Scan complete: every form of table account returned by the saved and the published read was examined/);
  assert.match(note, /The publish-or-undo advice above is not sufficient for this pattern/);
  for (const absent of [SHARE_FRESH, SHARE_CONTACT, 'Planned']) assert.ok(!note.includes(absent), absent);
  assert.equal(control.e.formCaptionSharingNote, undefined, 'no sharer, no note');
  // The table stays blocked by the stop's own label; the observation adds one display-only label beside it.
  const [w] = run.withheld;
  const [cw] = control.withheld;
  assert.equal(w.table, 'account');
  assert.deepEqual(w.blockedBy.slice(0, -1), cw.blockedBy);
  assert.match(w.blockedBy[w.blockedBy.length - 1], SHARING_LABEL);
  assert.equal(cw.blockedBy.some((l) => /shared form cells/.test(l)), false);
});

test('shared form cells, unconfirmed stop: the note rides on the stop without the drift sentence, and the next run shows it again — read-only, the dispatch still unconfirmed', async () => {
  const control = await splitPublish({ before: (s) => putNeighbours(s, { shared: false }) });
  const run = await splitPublish({ before: (s) => putNeighbours(s) });
  assert.equal(run.e.code, PUBLICATION_UNCONFIRMED);
  assert.equal(run.e.message.split(run.token).join('<token>'), control.e.message.split(control.token).join('<token>'));
  assert.deepEqual(run.shape, control.shape);
  assert.equal(run.store, control.store);
  assert.deepEqual(run.requests, control.requests);
  assert.equal(run.s.wire.publishes('account').length, 1, 'the one publish it always sent');
  const note = run.e.formCaptionSharingNote;
  assert.ok(note.includes(`  form ${SHARE_PEER} (name "Account copy"): saved "Inspections"; published "Issues";`), note);
  assert.doesNotMatch(note, /publish-or-undo/, 'this stop printed no such advice');
  assert.match(note, /an adopt approval or a publication-risk approval does not grant it/);
  assert.equal(control.e.formCaptionSharingNote, undefined);
  assert.ok(run.s.barrier.withheld()[0].blockedBy.some((l) => SHARING_LABEL.test(l)));

  // The next run's read-only confirmation: the same answer, nothing written, the label beside its block.
  const next = await splitConfirm(run.s);
  const controlNext = await splitConfirm(control.s);
  assert.deepEqual(next.r.confirmed, []);
  assert.equal(next.unchanged, true);
  assert.deepEqual(next.requests, controlNext.requests);
  assert.ok(next.requests.every((r) => r.startsWith('GET ')));
  assert.deepEqual(next.labels.slice(0, -1).map((l) => l.split(run.token).join('<token>')), controlNext.labels.map((l) => l.split(control.token).join('<token>')));
  assert.match(next.labels[next.labels.length - 1], SHARING_LABEL);

  // A later publish of the scope, and a later change of the form, each stop on the dispatch with the note.
  const n = await nextRun(run.s);
  const owed = await caught(publishForms(n.sdk, n.store, n.barrier, [MAIN_G]));
  assert.equal(owed.code, PUBLICATION_UNCONFIRMED);
  assert.match(owed.formCaptionSharingNote, new RegExp(`form ${SHARE_PEER} \\(name "Account copy"\\)`));
  const m = await nextRun(run.s);
  const settle = await caught(runManagedFeature({ ...ports(run.s.wire, m.sdk, { key: 'account/main', id: MAIN, formxml: PLANNED_SPLIT }), store: m.store, barrier: m.barrier, client: m.sdk.dataverse }));
  assert.equal(settle.code, PUBLICATION_UNCONFIRMED);
  // The feature's halt wraps the stop as its cause; the note stays on the stop (the build reads it down the cause chain).
  assert.match(settle.cause.message, /has a publish that may have been sent and is not proved ended/);
  assert.match(settle.cause.formCaptionSharingNote, new RegExp(`form ${SHARE_PEER} \\(name "Account copy"\\)`));
  assert.equal(run.s.wire.publishes('account').length, 1, 'nothing more was published');
  assert.equal(pubOf(m.store).state, 'unconfirmed');
});

test('shared form cells in an organization with a second language: the stop decided on the saved layer as compared, and that is what is explained', async () => {
  const wire = { platform: { secondLanguage: 1036 } };
  const run = await splitPublish({ wire, before: (s) => putNeighbours(s) });
  assert.equal(run.e.code, PUBLICATION_UNCONFIRMED);
  assert.ok(run.e.formCaptionSharingNote.includes(`  form ${SHARE_PEER} (name "Account copy"): saved "Inspections"; published "Issues";`), run.e.formCaptionSharingNote);
  assert.match(run.e.formCaptionSharingNote, /Scan complete/);
  const drift = await sharedDrift({ shared: true, wire });
  assert.equal(drift.e.code, 'create-completion-required');
  assert.match(drift.e.formCaptionSharingNote, /The publish-or-undo advice above is not sufficient/);
});

test('shared form cells are never read for a publish that goes through: a healthy owed publish lists no table', async () => {
  const s = await setup();
  putNeighbours(s);
  await runManagedFeature({ ...ports(s.wire, s.sdk, { key: 'account/main', id: MAIN, formxml: SAVED_SPLIT }), store: s.store, barrier: s.barrier });
  const at = s.wire.log.length;
  assert.equal((await publishForms(s.sdk, s.store, s.barrier, [MAIN_G])).sent, true);
  assert.equal(pubOf(s.store).state, 'confirmed');
  assert.equal(s.wire.log.slice(at).filter(isTableListing).length, 0);
});

// Straight after a publish the platform may answer a cell caption still being rewritten (the wire's `rewritingReads`), while a
// read some seconds later is the saved layer exactly: the read-back is made again on the bounded settle schedule, and only a
// read that shows the send confirms it.
const cellForm = (caption) => `<form><tabs><tab id="{t}"><labels><label description="General" languagecode="1033" /></labels><columns><column><sections><section id="{s}">`
  + `<labels><label description="Main" languagecode="1033" /></labels><rows><row><cell id="{c}"><labels><label description="${caption}" languagecode="1033" /></labels>`
  + '<control id="name" datafieldname="name" /></cell></row></rows></section></sections></column></columns></tab></tabs></form>';
test('publication read-back: a published read that lags behind a publish is read again after each settle delay and confirms once it shows the send; without the re-read, or when a re-read fails, it stays unconfirmed', async () => {
  const run = async (rewritingReads, settle, readers) => {
    const s = await setup({ platform: { rewritingReads } });
    committedForm(s, { id: MAIN, key: 'account/main', publishedXml: cellForm('Account name'), savedXml: cellForm('Customer name') });
    const out = await caught(publishManagedScope({
      store: s.store, barrier: s.barrier, scope: ACCOUNT, groups: [MAIN_G], client: s.sdk.dataverse, path: 'managed forms of account', settle, ...(readers ? { readers } : {}),
      publish: () => publishTablesXml(s.sdk.dataverse, ['account']),
    }));
    return { s, out };
  };
  const waits = [];
  const sleep = async (ms) => { waits.push(ms); };
  const lagging = await run(2, { sleep });
  assert.equal(lagging.out, null);
  assert.equal(pubOf(lagging.s.store).state, 'confirmed');
  assert.deepEqual(waits, PUBLICATION_SETTLE_DELAYS_MS.slice(0, 2), 'two reads lagged, so two waits, then the read that shows the send');
  assert.equal(lagging.s.wire.publishes('account').length, 1, 'one publish: the lag is read through, never published over');
  // The same lag with no re-read (an empty schedule) is not confirmed: what confirms is a read that shows the send.
  const once = await run(2, { delaysMs: [], sleep });
  assert.equal(once.out && once.out.code, PUBLICATION_UNCONFIRMED);
  assert.match(once.out.message, /does not show what it shipped/);
  assert.equal(pubOf(once.s.store).state, 'unconfirmed');
  // A re-read that fails is not waited out: the scope is unconfirmed at once and blocked for the run.
  const { LAYER_READERS } = require('../lib/managed-layer-readers.js');
  let reads = 0;
  waits.length = 0;
  const failing = await run(5, { sleep }, { ...LAYER_READERS, form: async (...args) => { reads += 1; if (reads > 2) throw new Error('reset'); return LAYER_READERS.form(...args); } });
  assert.equal(failing.out && failing.out.code, PUBLICATION_UNCONFIRMED);
  assert.match(failing.out.message, /could not be read back/);
  assert.deepEqual(waits, PUBLICATION_SETTLE_DELAYS_MS.slice(0, 1));
  assert.equal(failing.s.barrier.allowScope(ACCOUNT, 'a sibling view'), false);
  // A schedule that is not whole milliseconds is the caller's mistake, refused before anything is sent.
  for (const delaysMs of [[1.5], [-1], 'soon', [Number.NaN]]) {
    const bad = await run(0, { delaysMs, sleep });
    assert.ok(bad.out instanceof TypeError, JSON.stringify(delaysMs));
    assert.equal(bad.s.wire.publishes('account').length, 0);
  }
});

test('carry: a table with no managed group is published as before — no store write and no extra request', async () => {
  const s = await setup();
  const before = fs.existsSync(s.store.file) ? fs.readFileSync(s.store.file, 'utf8') : null;
  const requests = s.wire.log.length;
  assert.deepEqual(await carryTable(s.sdk, s.store, s.barrier), { sent: true, withheld: false, confirmed: [] });
  assert.equal(fs.existsSync(s.store.file) ? fs.readFileSync(s.store.file, 'utf8') : null, before);
  assert.deepEqual(s.wire.log.slice(requests).map((e) => `${e.method} ${e.path}`), ['POST PublishXml']);
});
// An approved, adopted existing form the build edits, adding one cell: the edit's answer acknowledges the write, never a
// create of the form, and the receipt names the new cell. `answer` overrides what prove answers.
const CELL = '13131313-1313-4131-8131-131313131313';
const CELL_KEY = 'account/main/cell-1';
const cellChild = { kind: 'form-cell', key: CELL_KEY, namespaceParentId: MAIN, id: CELL, associationSha256: H('f') };
const cellReceipt = { kind: 'form-cell', key: CELL_KEY, id: CELL };
function adoptedEditWithCell(s, sdk, answer = {}) {
  const p = ports(s.wire, sdk, { key: 'account/main', id: MAIN, formxml: '<form v="2"/>' });
  p.plan = async () => ({
    root: { kind: 'form', key: 'account/main', id: MAIN }, declarationSha256: H('e'), publication: { scope: ACCOUNT, state: 'owed' },
    expected: { ...expected(MAIN), baseObservation: { rowVersion: null, savedSha256: H('d') }, children: [cellChild] },
  });
  const prove = p.prove;
  p.prove = async (a) => {
    const got = await prove(a);
    return {
      ...got, acknowledgedRoot: false, acknowledgedChildCreates: [cellReceipt],
      records: [{ ...rec('form', 'account/main', MAIN), origin: 'adopted' }, rec('form-cell', CELL_KEY, CELL)], ...answer,
    };
  };
  return p;
}
async function adoptedFormSetup() {
  const s = await setup();
  s.wire.putForm(formRow(MAIN, '<form v="1"/>'));
  return s;
}
const bound = (store) => { const g = store.readGroup('form', 'account/main'); return g.committed ? Object.fromEntries(g.committed.records.map((r) => [r.kind, r.origin])) : null; };

test('child receipt: a cell an approved edit adds to an adopted existing form is bound as created; the root stays adopted', async () => {
  const s = await adoptedFormSetup();
  const p = adoptedEditWithCell(s, s.sdk);
  assert.deepEqual((await runManagedFeature({ ...p, store: s.store, barrier: s.barrier, adoptionApproved: true })).result, { committed: true, recovered: false });
  assert.deepEqual(bound(s.store), { form: 'adopted', 'form-cell': 'created' });
});

test('child receipt: an edit never acknowledges its root, a receipt names only expected children and never the root, and never stands in for the adoption approval', async () => {
  const attempt = async (answer, { approved = true } = {}) => {
    const s = await adoptedFormSetup();
    const code = await codeOf(runManagedFeature({ ...adoptedEditWithCell(s, s.sdk, answer), store: s.store, barrier: s.barrier, adoptionApproved: approved }));
    const g = s.store.readGroup('form', 'account/main');
    return { code, committed: g.committed, pending: g.pending };
  };
  const ack = await attempt({ acknowledgedRoot: true });
  assert.equal(ack.code, 'managed-not-settled', 'an answer to an edit is not a create');
  assert.equal(ack.committed, null);
  assert.equal(ack.pending.acknowledgedRoot, false);
  assert.equal(ack.pending.savedObservation, null, 'nothing written');
  const root = await attempt({ acknowledgedChildCreates: [cellReceipt, { kind: 'form', key: 'account/main', id: MAIN }] });
  assert.equal(root.code, 'create-completion-required', 'a receipt never names the root');
  assert.equal(root.pending.acknowledgedChildCreates, undefined, 'nothing written');
  // Not even when the expected proof lists the root's row as a child under another kind, in any spelling of its GUID.
  for (const aliasId of [MAIN, `{${MAIN}}`, `{${MAIN.toUpperCase()}}`, MAIN.toUpperCase()]) {
    const alias = { kind: 'form-cell', key: 'account/main/alias', namespaceParentId: MAIN, id: aliasId, associationSha256: H('f') };
    const s = await adoptedFormSetup();
    const p = adoptedEditWithCell(s, s.sdk, { acknowledgedChildCreates: [cellReceipt, { kind: 'form-cell', key: 'account/main/alias', id: aliasId }] });
    const plan = p.plan;
    p.plan = async (a) => { const got = await plan(a); return { ...got, expected: { ...got.expected, children: [cellChild, alias] } }; };
    const code = await codeOf(runManagedFeature({ ...p, store: s.store, barrier: s.barrier, adoptionApproved: true }));
    const g = s.store.readGroup('form', 'account/main');
    assert.equal(code, 'create-completion-required', aliasId);
    assert.equal(g.pending.acknowledgedChildCreates, undefined, `${aliasId}: the root's row is never receipted`);
    assert.equal(g.committed, null, `${aliasId}: nothing bound`);
  }
  const stranger = await attempt({ acknowledgedChildCreates: [cellReceipt, { kind: 'form-cell', key: 'account/main/cell-9', id: QUICK }] });
  assert.equal(stranger.code, 'create-completion-required', 'a child the expected proof does not name');
  assert.equal(stranger.pending.acknowledgedChildCreates, undefined, 'nothing written');
  assert.equal(stranger.committed, null);
  const otherId = await attempt({ acknowledgedChildCreates: [{ ...cellReceipt, id: QUICK }] });
  assert.equal(otherId.code, 'create-completion-required', 'the expected child under another id');
  const rootCreated = await attempt({ records: [rec('form', 'account/main', MAIN), rec('form-cell', CELL_KEY, CELL)] });
  assert.equal(rootCreated.code, 'create-completion-required', 'a receipt does not let the root say created');
  assert.equal(rootCreated.committed, null);
  const unapproved = await attempt({}, { approved: false });
  assert.equal(unapproved.code, 'managed-adoption-required', 'a receipt is not the adoption approval');
  assert.equal(unapproved.committed, null);
  assert.deepEqual(unapproved.pending.acknowledgedChildCreates, [cellReceipt], 'the receipt is kept with the attempt');
});

test('child receipt: kept under the attempt token across runs; a recovery binds the cell from the original receipt, never from today\'s answer, and only with a current approval', async () => {
  const s = await adoptedFormSetup();
  assert.equal(await codeOf(runManagedFeature({ ...adoptedEditWithCell(s, s.sdk), store: s.store, barrier: s.barrier })), 'managed-adoption-required');
  const token = s.store.readGroup('form', 'account/main').pending.token;
  const later = await nextRun(s);
  // Today's prove answers no receipt at all: the recovery reads the original attempt's.
  const today = { acknowledgedChildCreates: [] };
  assert.equal(await codeOf(runManagedFeature({ ...adoptedEditWithCell(s, later.sdk, today), store: later.store, barrier: later.barrier })), 'managed-adoption-required', 'no grant today, nothing bound');
  assert.equal(later.store.readGroup('form', 'account/main').pending.token, token);
  const done = await runManagedFeature({ ...adoptedEditWithCell(s, later.sdk, today), store: later.store, barrier: later.barrier, adoptionApproved: true });
  assert.deepEqual(done.result, { committed: true, recovered: true });
  assert.deepEqual(bound(later.store), { form: 'adopted', 'form-cell': 'created' });
  assert.equal(s.wire.log.filter(isPatch).length, 1, 'one edit, never sent again');
});

// Retiring a workflow group whose root a fresh read proved gone, through the real client and the effect gate. The order
// is the contract's: observe the group, then read the root, then retire against that observation.
const FLOW_ROW = '44444444-4444-4444-8444-444444444444';
const FLOW_KEY = 'retirement-flow';
const flowArgs = (token, observation, family = 'bpf') => ({ family, key: FLOW_KEY, generation: null, rootId: FLOW_ROW, evidence: { kind: 'root-absent', rootId: FLOW_ROW, row: 'not-found' }, attemptToken: token, observation });
const flowCreate = (token, body, family = 'bpf') => ({ attemptToken: token, family, key: FLOW_KEY, baseGeneration: null, rowId: FLOW_ROW, effect: 'create', request: { method: 'POST', shape: family === 'rule' ? 'rule-create' : 'bpf-create' }, desiredSha256: requestBodySha256(body) });
const answerBody = (answer) => { const b = answer.body ?? answer.data ?? answer; return typeof b === 'string' ? JSON.parse(b) : b; };
async function prepareFlow(store, { family = 'bpf', observed = true } = {}) {
  const token = store.prepareAttempt({ family, key: FLOW_KEY, baseGeneration: null, root: { kind: family === 'rule' ? 'business-rule' : family, key: FLOW_KEY, id: FLOW_ROW }, knownScopes: [], declarationSha256: H('e') });
  const { epoch } = store.markSending(token, { ...expected(FLOW_ROW), proofSchema: `${family}-v1` }, { observed, claim: 'first' });
  return { token, epoch };
}
async function rowMissing(sdk) {
  const answer = await sdk.dataverse.get(`/workflows(${FLOW_ROW})`);
  assert.deepEqual([answer.statusCode ?? answer.status, answerBody(answer).error.code], [404, '0x80040217']);
}
// A wire that loses the answer to a workflow create and keeps the request, to deliver it later: a create that landed
// after the run gave up on it.
const losingCreates = (s, queued) => ({ request: async (r) => {
  if (r.method === 'POST' && /\/workflows$/.test(r.url)) { queued.push(() => s.wire.request(r)); return { error: new Error('the answer was lost'), code: 'ECONNRESET' }; }
  return s.wire.request(r);
} });

test('absent root: a 404 read before another run sent, confirmed and acknowledged the create proves nothing; retirement refuses with nothing written', async () => {
  const s = await setup();
  const { token } = await prepareFlow(s.store);
  const body = { workflowid: FLOW_ROW, name: 'Racing create' };
  const effect = flowCreate(token, body);
  s.store.recordWorkflowEffect(effect);
  const retiree = openManagedBindings({ workspaceDir: s.dir, environment: ENV, appUniqueName: APP, solutionUniqueName: SOL });
  const { observation } = retiree.observeRetirement({ family: 'bpf', key: FLOW_KEY });
  await rowMissing(s.sdk);
  const { sdk } = await sdkOver(s.wire, { barrier: s.barrier, workflowEffectGate: createWorkflowEffectGate({ store: s.store }) });
  await withWorkflowEffect({ store: s.store, effect }, () => sdk.dataverse.post('/workflows', body));
  s.store.confirmEffect(s.store.readGroup('bpf', FLOW_KEY).effects[0].token, { observedSha256: requestBodySha256(body) });
  s.store.noteSaved(token, { proof: null, acknowledgedRoot: true });
  const before = fs.readFileSync(s.store.file, 'utf8');
  const writes = s.wire.log.filter((r) => r.method !== 'GET').length;
  let refusal = null;
  try { retiree.retireAbsentGroup(flowArgs(token, observation)); } catch (e) { refusal = e; }
  assert.deepEqual([refusal && refusal.code, s.wire.workflows.has(FLOW_ROW)], [CODES.conflict, true], 'the row now exists; the old 404 is not about it');
  assert.equal(fs.readFileSync(s.store.file, 'utf8'), before, 'nothing written');
  assert.equal(s.wire.log.filter((r) => r.method !== 'GET').length, writes);
  assert.equal(retiree.readGroup('bpf', FLOW_KEY).pending.token, token, 'the attempt stays for its commit');
});

for (const observed of [false, true]) {
  test(`absent root: a workflow attempt that may have sent a create it never journaled is not retired on a 404 (send window ${observed ? 'counted a send' : 'absent'})`, async () => {
    const s = await setup();
    const { token, epoch } = await prepareFlow(s.store, { observed });
    const observer = observed ? createAttemptSendObserver() : null;
    const queued = [];
    const { sdk } = await sdkOver(losingCreates(s, queued), { barrier: s.barrier, observer, workflowEffectGate: createWorkflowEffectGate({ store: s.store }) });
    const window = observer && observer.open(s.store, token, epoch);
    try { await assert.rejects(sdk.dataverse.post('/workflows', { workflowid: FLOW_ROW, name: 'Unjournaled create' })); } finally { if (window) window.end(); }
    assert.ok(queued.length > 0, 'the create reached the service (the client may resend it)');
    const { observation } = s.store.observeRetirement({ family: 'bpf', key: FLOW_KEY });
    await rowMissing(sdk);
    const before = fs.readFileSync(s.store.file, 'utf8');
    let refusal = null;
    try { s.store.retireAbsentGroup(flowArgs(token, observation)); } catch (e) { refusal = e; }
    assert.deepEqual([refusal && refusal.code, /does not account for/.test(refusal && refusal.message)], [CODES.pending, true]);
    assert.equal(fs.readFileSync(s.store.file, 'utf8'), before, 'nothing written');
    await queued[0]();
    assert.equal(answerBody(await sdk.dataverse.get(`/workflows(${FLOW_ROW})`)).workflowid, FLOW_ROW, 'the create that was on its way lands');
    assert.equal(s.store.readGroup('bpf', FLOW_KEY).pending.token, token, 'and the attempt that may own it is still there to recover it');
  });
}

test('absent root: a workflow create whose answer was lost stays unconfirmed, and a 404 never retires it, before or after the late delivery', async () => {
  const s = await setup();
  const { token } = await prepareFlow(s.store);
  const body = { workflowid: FLOW_ROW, name: 'Delayed' };
  const queued = [];
  const { sdk } = await sdkOver(losingCreates(s, queued), { barrier: s.barrier, workflowEffectGate: createWorkflowEffectGate({ store: s.store }) });
  await assert.rejects(withWorkflowEffect({ store: s.store, effect: flowCreate(token, body) }, () => sdk.dataverse.post('/workflows', body)));
  assert.equal(s.store.readGroup('bpf', FLOW_KEY).effects[0].state, 'unconfirmed');
  const { observation } = s.store.observeRetirement({ family: 'bpf', key: FLOW_KEY });
  await rowMissing(sdk);
  const before = fs.readFileSync(s.store.file, 'utf8');
  assert.equal(await codeOf((async () => s.store.retireAbsentGroup(flowArgs(token, observation)))()), CODES.pending);
  await queued[0]();
  assert.equal(await codeOf((async () => s.store.retireAbsentGroup(flowArgs(token, observation)))()), CODES.pending);
  assert.equal(fs.readFileSync(s.store.file, 'utf8'), before);
});

test('absent root: a dashboard both layers read fresh prove gone retires alone, owing its publish, a sibling\'s carried journal and the quarantine untouched', async () => {
  const s = await setup();
  committedForm(s, { id: MAIN, key: 'account/main', publishedXml: '<form/>', savedXml: '<form/>', state: 'not-needed' });
  const form = s.store.readGroup('form', 'account/main').committed;
  s.store.markPublishDispatch({ groups: [], scope: ACCOUNT, token: 'sibling-carry',
    carried: [{ family: 'form', key: 'account/main', generation: form.generation, savedSha256: H('5'), publishedSha256: H('5') }] });
  s.store.notePublishOutcome({ token: 'sibling-carry', outcome: 'unconfirmed' });
  const t = s.store.prepareAttempt({ family: 'dashboard', key: 'sales', baseGeneration: null, root: { kind: 'dashboard', key: 'sales', id: DASH }, knownScopes: [dashScope(DASH)], declarationSha256: H('e'), publication: { scope: dashScope(DASH), state: 'owed' } });
  s.store.markSending(t, { ...expected(DASH), proofSchema: 'dashboard-v1' });
  s.store.noteSaved(t, { proof: null, acknowledgedRoot: true });
  const dash = s.store.commitGroup({ token: t, baseGeneration: null, records: [rec('dashboard', 'sales', DASH)], proof: PROOF, consumerState: consumer('dashboard'), publication: { scope: dashScope(DASH), state: 'owed', desiredSha256: H('6'), dispatchToken: null } });
  const args = (observation, evidence = { kind: 'root-absent', rootId: DASH, saved: 'not-found', published: 'not-found' }) => ({ family: 'dashboard', key: 'sales', generation: dash.generation, rootId: DASH, evidence, observation });
  // Saved but never published: a missing published layer alone is no absence, and cannot even be put as evidence.
  s.wire.putForm({ formid: DASH, name: 'Sales', objecttypecode: 'none', type: 0, formxml: '<form/>' });
  const early = s.store.observeRetirement({ family: 'dashboard', key: 'sales' }).observation;
  assert.equal(await readSystemFormRootPresence(s.sdk.dataverse, DASH), 'present');
  const unchanged = fs.readFileSync(s.store.file, 'utf8');
  assert.equal(await codeOf((async () => s.store.retireAbsentGroup(args(early, { kind: 'root-absent', rootId: DASH, published: 'not-found' })))()), CODES.notSettled);
  assert.equal(fs.readFileSync(s.store.file, 'utf8'), unchanged);
  // Deleted: observe, then read both layers by the id, then retire.
  s.wire.saved.delete(DASH);
  s.barrier.quarantine([dashScope(DASH)], [DASH], 'dashboard sales (already stopped)');
  const before = s.store.snapshot().envelope;
  const { observation } = s.store.observeRetirement({ family: 'dashboard', key: 'sales' });
  const reads = s.wire.log.length;
  assert.equal(await readSystemFormRootPresence(s.sdk.dataverse, DASH), 'absent');
  assert.equal(s.wire.log.length - reads, 2, 'one read per layer');
  const writes = s.wire.log.filter((r) => r.method !== 'GET').length;
  assert.deepEqual(s.store.retireAbsentGroup(args(observation)), { retired: { family: 'dashboard', key: 'sales', generation: dash.generation, attempt: null } });
  const after = s.store.snapshot().envelope;
  assert.deepEqual([after.groups, after.attempts, after.workflowEffects, after.publicationRiskAcceptances],
    [before.groups.filter((g) => g.family !== 'dashboard'), before.attempts, before.workflowEffects, before.publicationRiskAcceptances]);
  assert.deepEqual([after.retiredGroups[0].publication, after.retiredGroups[0].attempt], ['owed', null], 'the debt is recorded owed, never paid');
  assert.equal(s.wire.log.filter((r) => r.method !== 'GET').length, writes, 'retiring sends nothing');
  assert.equal(s.barrier.allowScope(dashScope(DASH), 'still stopped'), false, 'the quarantine stays');
  const next = openManagedBindings({ workspaceDir: s.dir, environment: ENV, appUniqueName: APP, solutionUniqueName: SOL });
  assert.equal(next.readGroup('dashboard', 'sales').committed, null);
  assert.equal(next.readGroup('form', 'account/main').committed.publication.state, 'unconfirmed', 'the sibling\'s carried journal stays');
});

for (const family of ['rule', 'bpf']) {
  test(`absent root: a ${family} create confirmed by a read, its activation answered unapplied, then the row deleted, retires on a fresh 404 with no write`, async () => {
    const s = await setup();
    const { token } = await prepareFlow(s.store, { family, observed: false });
    const { sdk } = await sdkOver(s.wire, { barrier: s.barrier, workflowEffectGate: createWorkflowEffectGate({ store: s.store }) });
    const row = { workflowid: FLOW_ROW, name: 'Own created workflow' };
    const body = family === 'rule' ? { Entity: row } : row;
    const address = family === 'rule' ? '/workflows(00000000-0000-0000-0000-000000000000)/Microsoft.Dynamics.CRM.CreateProcessWithWfomJson' : '/workflows';
    await withWorkflowEffect({ store: s.store, effect: flowCreate(token, body, family) }, () => sdk.dataverse.post(address, body));
    assert.equal(answerBody(await sdk.dataverse.get(`/workflows(${FLOW_ROW})`)).name, row.name);
    s.store.confirmEffect(s.store.readGroup(family, FLOW_KEY).effects[0].token, { observedSha256: requestBodySha256(body) });
    s.store.noteSaved(token, { proof: null, acknowledgedRoot: true });
    const activation = { attemptToken: token, family, key: FLOW_KEY, baseGeneration: null, rowId: FLOW_ROW, effect: 'state', desiredState: 'Active', expectedVersion: 'W/"1"', request: { method: 'PATCH', shape: 'workflow-patch' } };
    s.wire.script((e) => e.method === 'PATCH', { statusCode: 412, body: { error: { code: '0x80060882', message: 'Version mismatch' } }, unapplied: true });
    const answered = await withWorkflowEffect({ store: s.store, effect: activation, workflowConditionalEdits: false, observedState: 'Draft' },
      () => sdk.dataverse.patch(`/workflows(${FLOW_ROW})`, { statecode: 1, statuscode: 2 }, { headers: { 'If-Match': 'W/"1"' } })).catch((e) => e);
    assert.equal(answered.statusCode ?? answered.status, 412);
    assert.deepEqual(s.store.readGroup(family, FLOW_KEY).effects.map((e) => e.state), ['confirmed', 'definitely-unsent']);
    s.wire.workflows.delete(FLOW_ROW);
    const { observation } = s.store.observeRetirement({ family, key: FLOW_KEY });
    await rowMissing(sdk);
    const writes = s.wire.log.filter((r) => r.method !== 'GET').length;
    assert.deepEqual(s.store.retireAbsentGroup(flowArgs(token, observation, family)), { retired: { family, key: FLOW_KEY, generation: null, attempt: token } });
    assert.equal(s.wire.log.filter((r) => r.method !== 'GET').length, writes, 'retiring sends nothing');
    const audit = s.store.snapshot().envelope.retiredGroups[0];
    assert.deepEqual([audit.generation, audit.publication, audit.attempt.effects], [null, null, [{ effect: 'create', state: 'confirmed' }, { effect: 'state', state: 'definitely-unsent' }]], 'created, never activated');
  });
}