Files
stack/packages/bus/tests/request-bootstrap.test.mjs
T

476 lines
31 KiB
JavaScript

// Lifecycle Task 2 (#797 / Gitea #1839): a confirmed new-project selection becomes a usable project.
// Real startBroker over a real organization file, a real git factory repo and a fixture data root.
// The test barrier stands in for a kill: it throws after a step's effect and before its receipt.
import test from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { startBroker } from '../src/runtime.mjs';
import { prepareBootstrap } from '../src/request-bootstrap.mjs';
import { hostPreparation, staffFor } from '../src/request-host.mjs';
import { bootConfig, loadSystem } from '../../cli/src/config.mjs';
import { fixture, tmp } from '../../cli/tests/helpers.mjs';
import { organizationWriter } from '../../business/src/organization.mjs';
import { loadBusiness } from '../../business/src/business.mjs';
import { managedState } from '../../business/src/project-bootstrap.mjs';
import { workingRepo } from '../../seat/src/working.mjs';
const INTENT = 'Build a single-file timer.\nKeep these exact bytes.\n';
const GIT_ENV = { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null', GIT_AUTHOR_NAME: 'Factory', GIT_AUTHOR_EMAIL: '[email protected]',
GIT_COMMITTER_NAME: 'Factory', GIT_COMMITTER_EMAIL: '[email protected]' };
const git = (cwd, ...args) => execFileSync('git', args, { cwd, env: GIT_ENV, encoding: 'utf8' }).trim();
const PROJECT_FILE = { projectVersion: 1, id: 'stack', vars: { 'tracker.project': 1, 'git.workingBranch': 'main' } };
// The factory: the declared `stack` project is a git repository with a project file.
function factory(root) {
const dir = join(root, 'project');
mkdirSync(join(dir, '.mosaic'), { recursive: true });
writeFileSync(join(dir, '.mosaic/project.json'), JSON.stringify(PROJECT_FILE, null, 2) + '\n');
writeFileSync(join(dir, 'README.md'), 'factory\n');
git(dir, 'init', '-q', '-b', 'main'); git(dir, 'add', '-A'); git(dir, 'commit', '-q', '-m', 'factory');
return dir;
}
// `defaultServices` boots with nothing injected, so the host builds its own preparation and admission; `withTrackers` forwards the
// boot config's tracker settings as process.mjs does (the adapter itself is not built).
async function setup(t, { barrier, configureFactory = () => {}, beforePropose = () => {}, defaultServices = false, withTrackers = defaultServices } = {}) {
const root = tmp(t, 'bootstrap-'), f = fixture(root, 'demo'), source = factory(root);
configureFactory({ root, f, source });
const hooks = { barrier };
const system = loadSystem({ env: f.env });
const writer = organizationWriter({ dir: join(root, 'config'), rolesDir: f.roles });
const plans = (dataRoot, ready = () => true) => ({
preparePlans: (state, args, from) => Promise.all(['autonomous', 'guided'].map(mode => prepareBootstrap({
business: writer.read('demo').document, request: state.request, sourceProject: args.source_project, project: args.project, name: args.name,
mode, dataRoot, organizationRevision: writer.read('demo').revision, tracker: { root: 1, project: args.tracker_project },
staff: { pm: state.pm, technical_reviewer: 'cto', coder: 'coder', reviewer: 'reviewer', chief: 'chief' },
intent: { text: from.text, source_message: from.source_message } }))),
admitPlan: plan => plan.organization_revision === writer.read('demo').revision && ready() ? { ready: true } : { ready: false, code: 'organization-stale' },
barrier: step => hooks.barrier?.(step),
});
const boot = async () => {
const warnings = [];
const { trackers, ...config } = JSON.parse(JSON.stringify(bootConfig({ system, businessId: 'demo', env: f.env, warn: w => warnings.push(w) })));
const bus = await startBroker({ ...config, ...(withTrackers ? { trackers } : {}), requestServices: defaultServices ? {} : plans(f.dataRoot) });
t.after(() => bus.close().catch(() => {}));
return { bus, config, trackers, warnings };
};
const first = await boot();
const caps = { human: first.bus.broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true }) };
for (const role of ['pm', 'cto', 'coder']) {
caps[role] = first.bus.broker.bindLaunch({ business: 'demo', role, run: role + '-run', harness: 'pi' });
first.bus.broker.request(caps[role], { verb: 'role.claim' });
}
const call = (who, verb, args = {}) => first.bus.broker.request(caps[who], { verb, args });
const sent = call('human', 'message.send', { to: 'pm', body: INTENT });
const opened = await call('pm', 'request.open', { request: sent.request });
// A source the preparation refuses never reaches a decision; the refusal is the outcome, so setup hands it back.
let proposed = null, proposeError = null;
beforePropose({ root, f, source });
try {
proposed = await call('pm', 'request.propose', { request: sent.request, revision: opened.revision, op: 'plan-1', source_project: 'stack',
project: 'timer', name: 'Timer', tracker_project: 2 });
} catch (e) { proposeError = e; }
const choose = async (choice = 'guided') => {
call('human', 'decision.resolve', { id: proposed.selection.decision, choice });
return first.bus.requestLifecycle.resume('demo', sent.request);
};
const paths = { code: join(f.dataRoot, 'products/demo/timer/code'), records: join(f.dataRoot, 'projects/demo/timer'), product: join(f.dataRoot, 'products/demo/timer') };
const changes = () => { try { return readFileSync(writer.logFile('demo'), 'utf8').trim().split('\n').map(l => JSON.parse(l)); } catch { return []; } };
const additions = () => changes().filter(c => c.state === 'committed' && c.detail?.verb === 'project.add');
return { root, f, system, source, writer, hooks, boot, bus: first.bus, first, call, caps, request: sent.request, proposed, proposeError, choose, paths, changes, additions,
rows: () => first.bus.broker.request(caps.human, { verb: 'project.list', args: {} }) };
}
test('bootstrap_connects_all_resources', async t => {
const f = await setup(t), factoryHead = git(f.source, 'rev-parse', 'HEAD'), orgBefore = f.writer.read('demo');
const done = await f.choose('guided');
assert.equal(done.phase, 'discovery'); assert.equal(done.project, 'timer'); assert.equal(done.mode, 'guided');
assert.equal(done.wait.code, 'request-discovery-unavailable');
// The organization file: exactly one added mapping, everything else byte-for-byte the same document.
const org = f.writer.read('demo');
assert.deepEqual(org.document.projects.timer, { root: f.paths.code, repo: f.paths.records });
assert.deepEqual(org.document.projects.stack, orgBefore.document.projects.stack);
const { projects: a, ...restNow } = org.document, { projects: b, ...restBefore } = orgBefore.document;
assert.deepEqual(restNow, restBefore);
assert.equal(f.additions().length, 1);
assert.equal(f.additions()[0].detail.plan_digest, done.plan_digest);
assert.equal(f.additions()[0].after, org.revision);
// The code checkout: the factory commit plus one seed commit that writes only the project file.
assert.equal(git(f.paths.code, 'rev-parse', 'HEAD~1'), factoryHead);
assert.equal(git(f.paths.code, 'diff', '--name-status', 'HEAD~1', 'HEAD'), 'M\t.mosaic/project.json');
assert.deepEqual(JSON.parse(readFileSync(join(f.paths.code, '.mosaic/project.json'), 'utf8')), { projectVersion: 1, id: 'timer', vars: { 'git.workingBranch': 'main' } });
assert.equal(git(f.paths.code, 'remote'), '');
assert.equal(git(f.paths.code, 'status', '--porcelain'), '');
// The records repository: layout commit, then the original intent as the owner's edit.
assert.equal(git(f.paths.records, 'rev-list', '--count', 'HEAD'), '2');
assert.equal(git(f.paths.records, 'log', '-1', '--format=%an|%s'), 'jason|Edit spec/north-star.md');
assert.equal(git(f.paths.records, 'rev-parse', 'HEAD'), done.spec_commit);
assert.equal(readFileSync(join(f.paths.records, 'spec/north-star.md'), 'utf8'), INTENT);
// The chat association and the working repository.
const chat = f.rows().find(p => p.name === 'Timer');
assert.equal(chat.repo, 'timer'); assert.equal(chat.id, done.chat_project);
assert.equal(f.rows().filter(p => p.name === 'Timer').length, 1);
assert.equal(git(workingRepo(f.f.dataRoot, 'demo', 'timer'), 'rev-parse', 'refs/heads/main'), git(f.paths.code, 'rev-parse', 'HEAD'));
// The single tracker root stays; the selected board lives in the immutable plan and the admission projection.
const plan = done.selection.bindings.find(x => x.digest === done.plan_digest).plan;
assert.deepEqual(plan.tracker, { root: 1, project: 2 });
assert.deepEqual(await f.first.bus.admission({ business: 'demo', project: 'timer' }), { ready: true, revision: org.revision, code: null });
// The factory is untouched and the broker serves the new project without a restart.
assert.equal(git(f.source, 'rev-parse', 'HEAD'), factoryHead); assert.equal(git(f.source, 'status', '--porcelain'), '');
assert.ok(f.call('human', 'project.create', { name: 'Side', repo: 'timer' }).id);
// The next launch: a fresh boot lists the project, verifies it and still names the one tracker project.
await f.first.bus.close();
const next = await f.boot();
assert.deepEqual(next.config.businesses.demo.projects.timer, { root: f.paths.code, repo: f.paths.records });
assert.equal(next.trackers.demo.project, 1);
assert.deepEqual(next.warnings, []);
assert.equal(loadBusiness('demo', { dir: join(f.root, 'config'), rolesDir: f.f.roles }).projects.timer.root, f.paths.code);
});
test('a_product_is_not_admitted_until_every_step_passes', async t => {
let seen;
const f = await setup(t, { barrier: async step => { if (step === 'intent') seen = { admission: await f.first.bus.admission({ business: 'demo', project: 'timer' }) }; } });
await f.choose();
assert.equal(seen.admission.ready, false); assert.equal(typeof seen.admission.code, 'string');
assert.equal((await f.first.bus.admission({ business: 'demo', project: 'timer' })).ready, true);
assert.deepEqual(await f.first.bus.admission({ business: 'demo', project: 'stack' }), { ready: true, revision: f.writer.read('demo').revision, code: null });
assert.deepEqual(await f.first.bus.admission({ business: 'demo', project: 'absent' }), { ready: false, revision: null, code: 'project-unknown' });
assert.deepEqual(await f.first.bus.admission({ business: 'other', project: 'timer' }), { ready: false, revision: null, code: 'project-unknown' });
});
// Lifecycle #800: an association or organization change can land after the last awaited read.
function staleCase(name, change, { keep } = {}) {
test(name, async t => {
let armed = true;
const f = await setup(t, { barrier: step => { if (armed && step === 'begin') { armed = false; change(f); } } });
const orgBefore = readFileSync(join(f.root, 'config/businesses/demo.json'));
const out = await f.choose();
assert.equal(out.wait.code, 'request-plan-stale'); assert.equal(out.phase, 'selection'); assert.equal(out.project, null);
assert.equal(out.plan_digest, null); assert.equal(out.selection, null);
assert.equal(f.additions().length, 0);
assert.equal(existsSync(f.paths.records), false);
assert.equal(existsSync(join(f.paths.code, '.mosaic')), false);
keep?.(f, orgBefore);
// Nothing is retained that a fresh preview could trip over, and a re-run does not resume the old plan.
assert.equal((await f.first.bus.requestLifecycle.resume('demo', f.request)).wait.code, 'request-plan-stale');
});
}
staleCase('an_organization_change_after_confirmation_waits_without_effect', f => {
const now = f.writer.read('demo'), next = structuredClone(now.document); next.vars['tracker.pollSeconds'] = 61;
f.writer.write('demo', next, { revision: now.revision, actor: 'jason' });
}, { keep: f => assert.equal(existsSync(f.paths.product), false) });
staleCase('a_changed_source_commit_waits_without_effect', f => {
writeFileSync(join(f.source, 'README.md'), 'changed\n'); git(f.source, 'commit', '-qam', 'moved');
}, { keep: f => assert.equal(existsSync(f.paths.product), false) });
staleCase('preexisting_unrelated_data_is_left_alone_and_the_plan_waits', f => {
mkdirSync(f.paths.code, { recursive: true }); writeFileSync(join(f.paths.code, 'keep.txt'), 'mine\n');
}, { keep: f => assert.equal(readFileSync(join(f.paths.code, 'keep.txt'), 'utf8'), 'mine\n') });
staleCase('a_symlink_ancestor_is_refused_and_its_target_is_untouched', f => {
const outside = join(f.root, 'outside'); mkdirSync(outside); symlinkSync(outside, join(f.f.dataRoot, 'products'));
}, { keep: f => { assert.deepEqual(readdirSync(join(f.root, 'outside')), []); assert.ok(lstatSync(join(f.f.dataRoot, 'products')).isSymbolicLink()); } });
staleCase('a_path_overlap_with_a_declared_project_waits_without_effect', f => {
const now = f.writer.read('demo'), next = structuredClone(now.document);
next.projects.stack = { ...next.projects.stack, repo: join(f.paths.code, 'inner') };
writeFileSync(join(f.root, 'config/businesses/demo.json'), JSON.stringify(next, null, 2) + '\n');
}, { keep: f => assert.equal(existsSync(f.paths.product), false) });
// Kill (the barrier throws after the effect and before its receipt), reopen, recover exactly once.
for (const step of ['mapping', 'intent']) {
test(`kill_after_${step}_then_reopen_recovers_the_same_project_exactly_once`, async t => {
let armed = true;
const f = await setup(t, { barrier: s => { if (armed && s === step) { armed = false; throw new Error('killed'); } } });
const factoryHead = git(f.source, 'rev-parse', 'HEAD');
const stopped = await f.choose();
assert.equal(stopped.phase, 'bootstrap'); assert.equal(stopped.wait.code, 'bootstrap-uncertain');
assert.equal(f.writer.read('demo').document.projects.timer !== undefined, true);
assert.equal((await f.first.bus.admission({ business: 'demo', project: 'timer' })).ready, false);
const mapped = f.writer.read('demo').revision;
await f.first.bus.close();
const next = await f.boot();
const human = next.bus.broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
const done = await next.bus.broker.request(human, { verb: 'request.get', args: { request: f.request } });
assert.equal(done.phase, 'discovery');
if (step === 'mapping') assert.equal(f.writer.read('demo').revision, mapped, 'recovery adds no second mapping');
assert.equal(f.additions().length, 1);
assert.equal(git(f.paths.records, 'rev-list', '--count', 'HEAD'), '2');
assert.equal(git(f.paths.records, 'rev-parse', 'HEAD'), done.spec_commit);
assert.equal(git(f.paths.code, 'rev-list', '--count', 'HEAD'), '2');
assert.equal(git(f.paths.code, 'rev-parse', 'HEAD~1'), factoryHead);
assert.equal(git(f.source, 'rev-parse', 'HEAD'), factoryHead); assert.equal(git(f.source, 'status', '--porcelain'), '');
assert.equal(next.bus.broker.request(human, { verb: 'project.list', args: {} }).filter(p => p.name === 'Timer').length, 1);
assert.equal((await next.bus.admission({ business: 'demo', project: 'timer' })).ready, true);
assert.equal(next.warnings.length, 0);
});
}
test('ordinary_organization_writers_still_refuse_every_project_change', async t => {
const f = await setup(t), now = f.writer.read('demo'), next = structuredClone(now.document);
next.projects.timer = { root: f.paths.code, repo: f.paths.records };
assert.throws(() => f.writer.write('demo', next, { revision: now.revision, actor: 'jason' }), { code: 'organization-projects-protected' });
assert.equal(f.writer.read('demo').revision, now.revision);
});
// ---- Fix round for review r1 (#797 Task 2): C1, C2, I1 ---------------------------------------------------------
const external = (root, name = 'external') => { const dir = join(root, name); mkdirSync(dir); return dir; };
const stateOf = async (f, bus = f.first.bus) => bus.broker.request(bus.broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true }), { verb: 'request.get', args: { request: f.request } });
// C1. A committed `.mosaic` link is refused where the plan is prepared, so the owner never sees a plan that would write through it.
test('c1_a_committed_mosaic_directory_link_is_refused_and_the_external_file_keeps_its_bytes', async t => {
let victim, before;
const f = await setup(t, { configureFactory: ({ root, source }) => {
const outside = external(root);
victim = join(outside, 'project.json'); before = JSON.stringify(PROJECT_FILE, null, 2) + '\n';
writeFileSync(victim, before);
rmSync(join(source, '.mosaic'), { recursive: true });
symlinkSync(outside, join(source, '.mosaic'));
git(source, 'add', '-A'); git(source, 'commit', '-qm', 'linked project metadata');
} });
assert.equal(f.proposeError?.code, 'request-project-refused'); assert.equal(f.proposed, null);
assert.equal(readFileSync(victim, 'utf8'), before);
assert.equal(existsSync(f.paths.product), false); assert.equal(f.additions().length, 0);
});
// The config loader refuses a linked project file at boot, so this link is committed after boot: preparation is the guard.
test('c1_a_committed_project_file_link_is_refused_at_preparation', async t => {
let victim, before;
const f = await setup(t, { beforePropose: ({ root, source }) => {
const outside = external(root);
victim = join(outside, 'project.json'); before = JSON.stringify(PROJECT_FILE, null, 2) + '\n';
writeFileSync(victim, before);
rmSync(join(source, '.mosaic/project.json'));
symlinkSync(victim, join(source, '.mosaic/project.json'));
git(source, 'add', '-A'); git(source, 'commit', '-qm', 'linked project file');
} });
assert.equal(f.proposeError?.code, 'request-project-refused'); assert.equal(f.proposed, null);
assert.equal(readFileSync(victim, 'utf8'), before);
assert.equal(existsSync(f.paths.product), false);
});
// The executor does not trust the plan: a link that appears in the checkout is refused before anything is written through it.
for (const [what, link] of [
['mosaic_directory', (code, outside) => { rmSync(join(code, '.mosaic'), { recursive: true }); symlinkSync(outside, join(code, '.mosaic')); }],
['project_file', (code, outside) => { rmSync(join(code, '.mosaic/project.json')); symlinkSync(join(outside, 'project.json'), join(code, '.mosaic/project.json')); }],
]) {
test(`c1_a_${what}_link_in_the_checkout_is_refused_and_the_external_file_keeps_its_bytes`, async t => {
let victim, before, f;
f = await setup(t, { barrier: step => {
if (step !== 'cloned') return;
const outside = external(f.root);
victim = join(outside, 'project.json'); before = JSON.stringify(PROJECT_FILE, null, 2) + '\n';
writeFileSync(victim, before);
link(f.paths.code, outside);
} });
const out = await f.choose();
assert.equal(out.phase, 'bootstrap'); assert.equal(out.wait.code, 'bootstrap-uncertain');
assert.equal(readFileSync(victim, 'utf8'), before);
assert.equal(git(f.paths.code, 'rev-list', '--count', 'HEAD'), '1', 'no seed commit was made through the link');
assert.equal(f.additions().length, 0);
assert.equal((await f.first.bus.admission({ business: 'demo', project: 'timer' })).ready, false);
});
}
test('c1_a_marker_temp_link_is_never_followed_and_the_product_is_not_admitted', async t => {
let victim, f;
f = await setup(t, { barrier: step => {
if (step !== 'activate') return;
victim = join(external(f.root), 'victim.txt'); writeFileSync(victim, 'mine\n');
symlinkSync(victim, join(f.paths.product, 'bootstrap.json.tmp'));
} });
const out = await f.choose();
assert.equal(out.phase, 'bootstrap'); assert.equal(out.wait.code, 'bootstrap-uncertain');
assert.equal(readFileSync(victim, 'utf8'), 'mine\n');
assert.equal(JSON.parse(readFileSync(join(f.paths.product, 'bootstrap.json'), 'utf8')).state, 'reserved');
assert.equal((await f.first.bus.admission({ business: 'demo', project: 'timer' })).ready, false);
});
test('c1_a_seed_temp_link_is_never_followed_and_the_seed_is_not_published', async t => {
let victim, f;
f = await setup(t, { barrier: step => {
if (step !== 'reserve') return;
victim = join(external(f.root), 'victim.txt'); writeFileSync(victim, 'mine\n');
symlinkSync(victim, join(f.paths.product, 'project.json.seed'));
} });
const out = await f.choose();
assert.equal(out.wait.code, 'bootstrap-uncertain');
assert.equal(readFileSync(victim, 'utf8'), 'mine\n');
assert.equal(git(f.paths.code, 'rev-list', '--count', 'HEAD'), '1'); assert.equal(f.additions().length, 0);
});
// C2. A path nobody claimed is never removed.
test('c2_unrelated_code_tmp_contents_survive_and_the_step_is_uncertain', async t => {
let f;
f = await setup(t, { barrier: step => {
if (step !== 'reserve') return;
mkdirSync(join(f.paths.product, 'code.tmp'));
writeFileSync(join(f.paths.product, 'code.tmp', 'keep.txt'), 'unrelated\n');
} });
const out = await f.choose();
assert.equal(readFileSync(join(f.paths.product, 'code.tmp', 'keep.txt'), 'utf8'), 'unrelated\n');
assert.deepEqual(readdirSync(join(f.paths.product, 'code.tmp')), ['keep.txt']);
assert.equal(out.phase, 'bootstrap'); assert.equal(out.wait.code, 'bootstrap-uncertain');
assert.equal(existsSync(f.paths.code), false); assert.equal(f.additions().length, 0);
const op = `bootstrap:${out.plan_digest}:seed`;
assert.equal(f.first.bus.requestJournal?.effects?.('demo', f.request).filter(r => r.op === op).at(-1)?.stage ?? 'uncertain', 'uncertain');
});
// Ownership comes from the claim this plan wrote, never from how a directory looks.
test('c2_an_unclaimed_empty_code_tmp_is_kept_and_not_adopted', async t => {
let f;
f = await setup(t, { barrier: step => { if (step === 'reserve') mkdirSync(join(f.paths.product, 'code.tmp')); } });
const out = await f.choose();
assert.equal(out.wait.code, 'bootstrap-uncertain');
assert.deepEqual(readdirSync(join(f.paths.product, 'code.tmp')), []); assert.equal(existsSync(f.paths.code), false);
assert.equal(existsSync(join(f.paths.product, 'code.tmp.claim')), false); assert.equal(f.additions().length, 0);
});
test('c2_an_unclaimed_clone_of_the_same_commit_is_kept_and_not_adopted', async t => {
let f;
f = await setup(t, { barrier: step => { if (step === 'reserve') git(f.root, 'clone', '-q', f.source, join(f.paths.product, 'code.tmp')); } });
const out = await f.choose();
assert.equal(out.wait.code, 'bootstrap-uncertain');
assert.equal(existsSync(join(f.paths.product, 'code.tmp/.git')), true); assert.equal(existsSync(f.paths.code), false);
assert.equal(f.additions().length, 0);
});
test('c2_a_claimed_clone_left_by_a_kill_is_adopted_exactly_once_on_retry', async t => {
let armed = true;
const f = await setup(t, { barrier: step => { if (armed && step === 'clone') { armed = false; throw new Error('killed'); } } });
const stopped = await f.choose();
assert.equal(stopped.wait.code, 'bootstrap-uncertain');
assert.equal(existsSync(join(f.paths.product, 'code.tmp/.git')), true); assert.equal(existsSync(f.paths.code), false);
assert.equal(existsSync(join(f.paths.product, 'code.tmp.claim')), true);
await f.first.bus.close();
const next = await f.boot();
const done = await stateOf(f, next.bus);
assert.equal(done.phase, 'discovery');
assert.equal(existsSync(join(f.paths.product, 'code.tmp')), false); assert.equal(existsSync(join(f.paths.product, 'code.tmp.claim')), false);
assert.equal(git(f.paths.code, 'rev-list', '--count', 'HEAD'), '2'); assert.equal(f.additions().length, 1);
});
test('c2_a_claimed_clone_with_foreign_content_is_kept_and_reported_uncertain', async t => {
let armed = true;
const f = await setup(t, { barrier: step => { if (armed && step === 'clone') { armed = false; throw new Error('killed'); } } });
await f.choose(); await f.first.bus.close();
writeFileSync(join(f.paths.product, 'code.tmp/extra.txt'), 'foreign\n');
const next = await f.boot();
const out = await stateOf(f, next.bus);
assert.equal(out.phase, 'bootstrap'); assert.equal(out.wait.code, 'bootstrap-uncertain');
assert.equal(readFileSync(join(f.paths.product, 'code.tmp/extra.txt'), 'utf8'), 'foreign\n');
assert.equal(existsSync(f.paths.code), false); assert.equal(f.additions().length, 0);
});
// I1. The freshness check holds before every effect, not only the first one.
test('i1_an_organization_change_after_reservation_waits_and_keeps_the_reserved_paths', async t => {
let armed = true, f;
f = await setup(t, { barrier: step => {
if (armed && step === 'reserve') {
armed = false;
const now = f.writer.read('demo'), next = structuredClone(now.document); next.vars['tracker.pollSeconds'] = 61;
f.writer.write('demo', next, { revision: now.revision, actor: 'jason' });
}
} });
const out = await f.choose();
assert.equal(out.phase, 'bootstrap'); assert.equal(out.wait.code, 'request-plan-stale'); assert.equal(out.project, 'timer');
assert.equal(existsSync(join(f.paths.product, 'bootstrap.json')), true, 'completed evidence is kept');
assert.equal(existsSync(f.paths.code), false); assert.equal(existsSync(join(f.paths.product, 'code.tmp')), false);
assert.equal(f.additions().length, 0); assert.deepEqual(readdirSync(f.paths.records), []);
assert.equal((await f.first.bus.admission({ business: 'demo', project: 'timer' })).ready, false);
assert.equal((await f.first.bus.requestLifecycle.resume('demo', f.request)).wait.code, 'request-plan-stale', 'a re-run performs no effect either');
assert.equal(existsSync(f.paths.code), false);
});
test('i1_an_organization_change_after_the_mapping_stops_the_remaining_effects_across_a_restart', async t => {
let armed = true, f;
f = await setup(t, { barrier: step => {
if (armed && step === 'mapping') {
armed = false;
const now = f.writer.read('demo'), next = structuredClone(now.document); next.vars['tracker.pollSeconds'] = 61;
f.writer.write('demo', next, { revision: now.revision, actor: 'jason' });
}
} });
const out = await f.choose();
assert.equal(out.phase, 'bootstrap'); assert.equal(out.wait.code, 'request-plan-stale');
assert.equal(f.additions().length, 1);
assert.deepEqual(readdirSync(f.paths.records), [], 'no records were written on the moved organization');
await f.first.bus.close();
const next = await f.boot();
const again = await stateOf(f, next.bus);
assert.equal(again.phase, 'bootstrap'); assert.equal(again.wait.code, 'request-plan-stale');
assert.deepEqual(readdirSync(f.paths.records), []); assert.equal(f.additions().length, 1);
assert.equal(f.writer.read('demo').document.projects.timer !== undefined, true);
assert.equal((await next.bus.admission({ business: 'demo', project: 'timer' })).ready, false);
});
// I2. A product is classified by its layout, so deleting the marker cannot turn an unfinished one into an ordinary project.
test('i2_a_missing_marker_does_not_admit_an_unfinished_product_after_reopen', async t => {
let armed = true;
const f = await setup(t, { barrier: step => { if (armed && step === 'mapping') { armed = false; throw new Error('killed'); } } });
const stopped = await f.choose();
assert.equal(stopped.wait.code, 'bootstrap-uncertain'); assert.equal(f.additions().length, 1);
await f.first.bus.close();
rmSync(join(f.paths.product, 'bootstrap.json'));
const entry = f.writer.read('demo').document.projects.timer;
assert.equal(managedState({ dataRoot: f.f.dataRoot, business: 'demo', project: 'timer', entry }), 'reserved');
const next = await f.boot();
const admitted = await next.bus.admission({ business: 'demo', project: 'timer' });
assert.equal(admitted.ready, false); assert.equal(admitted.code, 'project-pending');
assert.equal(existsSync(join(f.paths.product, 'bootstrap.json')), false, 'recovery never rewrites a marker it did not write');
assert.equal((await stateOf(f, next.bus)).phase, 'bootstrap');
assert.equal(next.warnings.length, 0);
});
// I3. Nothing is injected: the host builds its own preparation and admission from the organization, the source
// checkout, the tracker settings it booted with and the staff the organization names.
test('i3_a_normal_boot_reaches_a_bootstrap_selection_and_bootstraps_the_project', async t => {
const f = await setup(t, { defaultServices: true });
assert.equal(f.proposeError, null);
assert.equal(f.proposed.phase, 'selection'); assert.equal(f.proposed.wait.kind, 'decision');
const [auto, guided] = f.proposed.selection.bindings.map(b => b.plan);
assert.deepEqual([auto.mode, guided.mode], ['autonomous', 'guided']);
assert.equal(auto.source.commit, git(f.source, 'rev-parse', 'HEAD'), 'the displayed commit is the source checkout\'s');
assert.equal(auto.organization_revision, f.writer.read('demo').revision);
assert.deepEqual(auto.tracker, { root: 1, project: 2 });
assert.deepEqual(auto.staff, { pm: 'pm', technical_reviewer: 'cto', coder: 'coder', reviewer: 'reviewer', chief: 'chief' });
assert.deepEqual([auto.code_root, auto.records_root], [f.paths.code, f.paths.records]);
assert.equal(auto.intent.text, INTENT);
const out = await f.choose();
assert.equal(out.phase, 'discovery'); assert.equal(f.additions().length, 1);
assert.equal((await f.first.bus.admission({ business: 'demo', project: 'timer' })).ready, true);
});
test('i3_a_missing_tracker_root_is_a_named_setup_wait_and_creates_nothing', async t => {
const f = await setup(t, { defaultServices: true, withTrackers: false });
assert.equal(f.proposeError, null);
assert.equal(f.proposed.phase, 'selection'); assert.equal(f.proposed.wait.code, 'request-tracker-unavailable');
assert.equal(f.proposed.selection ?? null, null, 'no plan and no decision were made up');
assert.equal(existsSync(f.paths.product), false); assert.equal(f.additions().length, 0);
});
test('i3_a_staff_the_organization_does_not_name_is_a_named_setup_wait', async t => {
const f = await setup(t, { defaultServices: true, configureFactory: ({ root }) => {
const file = join(root, 'config/businesses/demo.json'), doc = JSON.parse(readFileSync(file, 'utf8'));
doc.launch.instances = ['coder']; writeFileSync(file, JSON.stringify(doc, null, 2) + '\n');
} });
assert.equal(f.proposeError, null);
assert.equal(f.proposed.wait.code, 'request-staff-unavailable'); assert.equal(f.proposed.selection ?? null, null);
assert.equal(existsSync(f.paths.product), false);
});
test('i3_host_admission_refuses_a_plan_whose_world_has_moved_with_a_named_code', async t => {
const f = await setup(t, { defaultServices: true }), plan = f.proposed.selection.bindings[0].plan;
const host = (over = {}) => hostPreparation({ dataRoot: f.f.dataRoot, organization: f.writer, trackers: { demo: { project: 1 } }, ...over });
assert.deepEqual(host().admitPlan(plan), { ready: true });
assert.deepEqual(host({ trackers: null }).admitPlan(plan), { ready: false, code: 'request-tracker-unavailable' });
assert.deepEqual(host({ trackers: { demo: { project: 7 } } }).admitPlan(plan), { ready: false, code: 'request-tracker-unavailable' });
assert.deepEqual(host({ organization: { read: () => { throw new Error('gone'); } } }).admitPlan(plan), { ready: false, code: 'request-organization-unavailable' });
assert.deepEqual(host().admitPlan({ ...plan, staff: { ...plan.staff, coder: 'reviewer' } }), { ready: false, code: 'request-staff-unavailable' });
const now = f.writer.read('demo'), next = structuredClone(now.document); next.vars['tracker.pollSeconds'] = 61;
f.writer.write('demo', next, { revision: now.revision, actor: 'jason' });
assert.deepEqual(host().admitPlan(plan), { ready: false, code: 'request-organization-changed' });
assert.equal(staffFor(now.document, 'cto'), null, 'the PM cannot also be the technical reviewer');
assert.equal(staffFor({ ...now.document, launch: { ...now.document.launch, instances: ['coder', 'reviewer', 'reviewer'] } }, 'pm'), null);
});