450 lines
29 KiB
JavaScript
450 lines
29 KiB
JavaScript
import { requestArchived } from './broker.mjs';
|
|
// Lifecycle Task 2 (#797 / Gitea #1839): the host executor behind a confirmed new-project selection.
|
|
//
|
|
// prepareBootstrap builds the immutable resource plan the owner sees. executeBootstrap consumes exactly that
|
|
// plan's binding and walks the steps below, each under its own journal receipt (`bootstrap:<digest>:<step>`),
|
|
// so a restart re-drives it from the receipts and the on-disk evidence without doing any step twice:
|
|
//
|
|
// reserve re-verify the plan against the world (#800), then reserve the product paths and a marker
|
|
// seed clone the source commit into a claimed temporary checkout, drop its remote, commit the one project-file change
|
|
// working confine the working path, then seed the working repository from that commit
|
|
// mapping publish the one organization mapping through the private exact-add writer
|
|
// records initialize the records repository under that mapping
|
|
// intent save the original displayed intent as the owner's edit of spec/north-star.md
|
|
// chat associate the chat project
|
|
// activate mark the product complete, then admit the project to the running broker
|
|
//
|
|
// Every inspection compares deterministic paths, the stored commits and exact bytes. What it cannot prove
|
|
// is kept as it is and reported as `bootstrap-uncertain`; nothing unrelated is removed and no commit is rewound.
|
|
// Nothing is ever deleted recursively, and every write goes through an exclusively created file and a rename,
|
|
// inside directories that are verified not to be links, so a link in a source checkout cannot redirect a write.
|
|
// Before every effect the organization revision and the chat association are checked again (#800), and the check
|
|
// and the whole effect, including asynchronous git children, run under the organization lock (`guarded`). A project is ready
|
|
// only with both a complete marker and a committed activate receipt, so the marker goes first and nothing is
|
|
// admitted until it is published.
|
|
import { createHash } from 'node:crypto';
|
|
import { execFileSync } from 'node:child_process';
|
|
import { closeSync, constants, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync, writeSync } from 'node:fs';
|
|
import { dirname, join, relative, sep } from 'node:path';
|
|
import { digest, refuse, validatePlan } from './request-store.mjs';
|
|
import { gitEnv, runGit } from '../../seat/src/checkout.mjs';
|
|
import { initializeWorking, inspectWorkingRepository, workingRepo } from '../../seat/src/working.mjs';
|
|
import { initProject, writeHumanFile } from '../../project/src/index.mjs';
|
|
import { SAFE, identity } from '../../project/src/git.mjs';
|
|
import { loadProject } from '../../business/src/project.mjs';
|
|
import { canonicalJson } from '../../business/src/util.mjs';
|
|
import { managedPaths, markerBytes, markerFile, readMarker } from '../../business/src/project-bootstrap.mjs';
|
|
|
|
const INTENT_PATH = 'spec/north-star.md';
|
|
const LAYOUT_SUBJECT = 'Initialize project layout v1';
|
|
const exists = path => { try { return lstatSync(path); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } };
|
|
const within = (parent, path) => path === parent || path.startsWith(parent + sep);
|
|
const overlaps = (a, b) => within(a, b) || within(b, a);
|
|
const plain = x => x !== null && typeof x === 'object' && !Array.isArray(x);
|
|
|
|
// One synchronous git read, so the stale check has no await in it. null when git refuses.
|
|
function gitSync(root, args) {
|
|
try {
|
|
return execFileSync('git', [...SAFE, '-C', root, ...args],
|
|
{ env: { ...gitEnv(), GIT_CEILING_DIRECTORIES: dirname(root) }, encoding: 'utf8', timeout: 10000, stdio: ['ignore', 'pipe', 'pipe'] }).trim();
|
|
} catch { return null; }
|
|
}
|
|
// The checked-out commit of a repository root.
|
|
const headOf = root => gitSync(root, ['rev-parse', '--verify', 'HEAD^{commit}']);
|
|
|
|
// The one metadata file the seed rewrites. `.mosaic` must be a real directory and `project.json` a regular file in it,
|
|
// never a link, so neither a read nor a write can leave the checkout (C1).
|
|
const PROJECT_FILE = '.mosaic/project.json';
|
|
function metadataProblem(root) {
|
|
const dir = exists(join(root, '.mosaic'));
|
|
if (!dir || dir.isSymbolicLink() || !dir.isDirectory()) return '.mosaic is not a directory';
|
|
const file = exists(join(root, PROJECT_FILE));
|
|
if (!file || file.isSymbolicLink() || !file.isFile()) return `${PROJECT_FILE} is not a regular file`;
|
|
return null;
|
|
}
|
|
// The same rule on the committed tree: a tree for `.mosaic` and a regular blob for the project file.
|
|
function committedMetadataProblem(root, commit) {
|
|
const dir = gitSync(root, ['ls-tree', commit, '--', '.mosaic']), file = gitSync(root, ['ls-tree', commit, '--', PROJECT_FILE]);
|
|
if (!dir?.startsWith('040000 tree ')) return '.mosaic is not a committed directory';
|
|
if (!/^100(644|755) blob /.test(file ?? '')) return `${PROJECT_FILE} is not a committed regular file`;
|
|
return null;
|
|
}
|
|
|
|
// The chat project id is a function of the plan, so a retry computes the same one.
|
|
export function chatProjectId(request, planDigest) {
|
|
const h = createHash('sha256').update(`chat-project:${request}:${planDigest}`).digest('hex');
|
|
return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-8${h.slice(17, 20)}-${h.slice(20, 32)}`;
|
|
}
|
|
|
|
// prepareBootstrap({ business, request, sourceProject, project, name, mode, dataRoot, organizationRevision, tracker, staff, intent })
|
|
// Resolves the validated, immutable plan for one mode. `business` is the organization document; the plan names
|
|
// the source commit, the two managed roots and the original intent exactly as the owner will confirm them.
|
|
export async function prepareBootstrap({ business, request, sourceProject, project, name, mode, dataRoot, organizationRevision, tracker, staff, intent }) {
|
|
const source = business?.projects?.[sourceProject];
|
|
if (!plain(source) || source.kind === 'library' || typeof source.root !== 'string') refuse('request-project-refused');
|
|
const commit = headOf(source.root);
|
|
if (!commit || metadataProblem(source.root) || committedMetadataProblem(source.root, commit)) refuse('request-project-refused');
|
|
const factory = loadProject(source.root);
|
|
// The plan carries variables only, so a project file with role overrides cannot be reproduced from it.
|
|
if (Object.keys(factory.roles).length) refuse('request-project-refused');
|
|
const vars = { ...factory.vars };
|
|
delete vars['tracker.project'];
|
|
const { root, repo } = managedPaths({ dataRoot, business: business.id, project });
|
|
return validatePlan({ version: 1, business: business.id, request, project, name, chat_project: null, mode, organization_revision: organizationRevision,
|
|
source: { project: sourceProject, commit, remote: source.remote ?? null, forks: [] }, code_root: root, records_root: repo,
|
|
tracker: { root: tracker.root, project: tracker.project }, staff: { ...staff },
|
|
intent: { text: intent.text, sha256: digest(intent.text), source_message: intent.source_message, generated: false },
|
|
project_vars: JSON.parse(JSON.stringify(vars)), existing: false });
|
|
}
|
|
|
|
// Read an existing declared project. No managed-path allocation, clone or writer runs here.
|
|
export function prepareExistingPlan({ business, request, project, name, mode, dataRoot, organizationRevision, tracker, staff, intent, chat_project = null }) {
|
|
const source = business.projects?.[project];
|
|
if (!plain(source) || source.kind === 'library') refuse('request-project-refused');
|
|
const commit = headOf(source.root);
|
|
if (!commit || metadataProblem(source.root) || committedMetadataProblem(source.root, commit)) refuse('request-project-refused');
|
|
const config = loadProject(source.root), vars = { ...config.vars };
|
|
if (config.id !== project) refuse('request-project-refused');
|
|
delete vars['tracker.project'];
|
|
return validatePlan({ version: 1, business: business.id, request, project, name, chat_project, mode,
|
|
organization_revision: organizationRevision, source: { project, commit, remote: source.remote ?? null, forks: [] },
|
|
code_root: source.root, records_root: source.repo ?? join(dataRoot, 'projects', business.id, project),
|
|
tracker, staff, intent: { text: intent.text, sha256: digest(intent.text), source_message: intent.source_message, generated: false },
|
|
project_vars: vars, existing: true });
|
|
}
|
|
|
|
class Uncertain extends Error {}
|
|
class ForeignWorking extends Uncertain {}
|
|
|
|
// executeBootstrap({ binding, owner, journal, services }) -> { project, chat_project, spec_commit, organization_revision }
|
|
// services: dataRoot, organization (the writer), chat { state, associate }, activate (synchronous), barrier (tests).
|
|
// Throws RequestError('request-plan-stale') before any effect when the world no longer matches the plan; any other
|
|
// failure leaves the receipts as they are for the next run.
|
|
export async function executeBootstrap({ binding, owner, journal, services }) {
|
|
const plan = validatePlan(structuredClone(binding?.plan));
|
|
if (plan.existing || binding.digest !== digest(plan)) refuse('invalid-request-plan');
|
|
const { organization: writer, dataRoot } = services;
|
|
const { business, project, request } = plan;
|
|
const planDigest = binding.digest, base = name => `bootstrap:${planDigest}:${name}`;
|
|
const here = managedPaths({ dataRoot, business, project });
|
|
const workingPath = workingRepo(dataRoot, business, project);
|
|
const product = dirname(here.root), marker = markerFile({ dataRoot, business, project });
|
|
const chatId = chatProjectId(request, planDigest), human = () => writer.read(business).document.human;
|
|
const active = () => {
|
|
if (requestArchived(journal.readRequest(business, request), services, [project, plan.source.project, plan.chat_project, chatId])) refuse('project-archived');
|
|
};
|
|
const uncertain = () => { throw new Uncertain('bootstrap-uncertain'); };
|
|
const markerOwns = () => {
|
|
const m = readMarker(marker);
|
|
return m !== null && m.version === 1 && m.project === project && m.request === request && m.plan_digest === planDigest;
|
|
};
|
|
const entry = { root: here.root, repo: here.repo };
|
|
const receipt = { request, plan_digest: planDigest, project, data_root: dataRoot };
|
|
|
|
// A path is confined when it and every ancestor up to the data root are real directories, never links (C1).
|
|
const confined = path => {
|
|
for (let p = path; p !== dataRoot; p = dirname(p)) {
|
|
if (!within(dataRoot, p)) return false;
|
|
const st = exists(p);
|
|
if (!st || st.isSymbolicLink() || !st.isDirectory()) return false;
|
|
}
|
|
return true;
|
|
};
|
|
// Writes through an exclusively created sibling and a rename, so a link sitting at `file` is replaced and never
|
|
// followed. `stage` creates the sibling and returns the rename; a `temp` left by an earlier attempt is this plan's
|
|
// own only if it is a regular file with exactly these bytes, otherwise nothing is touched and the step is uncertain.
|
|
const stage = (file, temp, bytes) => {
|
|
if (!confined(dirname(file)) || !confined(dirname(temp))) uncertain();
|
|
const old = exists(temp);
|
|
if (old) { if (!old.isFile() || readFileSync(temp, 'utf8') !== bytes) uncertain(); unlinkSync(temp); }
|
|
const fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
try { writeSync(fd, bytes); } finally { closeSync(fd); }
|
|
return () => renameSync(temp, file);
|
|
};
|
|
const publish = (file, temp, bytes) => stage(file, temp, bytes)();
|
|
// #800 before every effect, not only the first: the organization is still at the revision this plan expects (the
|
|
// confirmed one before the mapping, this plan's own post-add one after it), the mapping is the plan's, and the chat
|
|
// association is not another's. `fresh` runs under the organization lock, so a bare `fresh()` proves the world
|
|
// matched at that instant and nothing more: the lock is released when it returns. What keeps a write from landing
|
|
// under a stale plan is `guarded(effect)`: the caller has finished every asynchronous read the effect depends on,
|
|
// and the check and the entire effect run with the lock held, through every awaited child. A mismatch keeps
|
|
// what is done and performs nothing further. The effect must not take the organization lock itself; mapping
|
|
// uses the writer's own exact-add transaction separately.
|
|
const checkFresh = ({ revision, document }) => {
|
|
active();
|
|
const stale = () => refuse('request-plan-stale');
|
|
if (document.id !== business || document.human !== owner) stale();
|
|
const added = writer.findAddition(business, { request, plan_digest: planDigest, project });
|
|
if (added) { if (revision !== added.after || canonicalJson(document.projects?.[project]) !== canonicalJson(entry)) stale(); }
|
|
else if (revision !== plan.organization_revision || Object.hasOwn(document.projects ?? {}, project)) stale();
|
|
if (services.chat.state({ business, project, name: plan.name, id: chatId }) === 'conflict') stale();
|
|
};
|
|
const fresh = () => writer.hold(business, checkFresh);
|
|
const guarded = effect => writer.holdAsync(business, now => { checkFresh(now); return effect(); });
|
|
|
|
const git = (cwd, args, extra = {}, file = false) => {
|
|
if (args.includes(`--git-dir=${workingPath}`)) {
|
|
if (!confined(workingPath)) uncertain();
|
|
inspectWorkingRepository(workingPath);
|
|
}
|
|
return runGit([...SAFE, ...(file ? ['-c', 'protocol.file.allow=always'] : []), ...(cwd ? ['-C', cwd] : []), ...args],
|
|
{ ...gitEnv(), ...(cwd ? { GIT_CEILING_DIRECTORIES: dirname(cwd) } : {}), ...extra });
|
|
};
|
|
const out = async (cwd, args, extra, file) => { const r = await git(cwd, args, extra, file); if (!r.ok) refuse('bootstrap-git-failed'); return r.out.trim(); };
|
|
const tryOut = async (cwd, args) => { const r = await git(cwd, args); return r.ok ? r.out.trim() : null; };
|
|
|
|
// One receipt per step. A committed receipt replays its result; anything else re-inspects the evidence.
|
|
async function step(name, run, { after = true } = {}) {
|
|
active();
|
|
const op = base(name), last = journal.effects(business, request).filter(r => r.op === op).at(-1);
|
|
if (last?.stage === 'committed') return last.result;
|
|
if (last?.stage === 'refused') refuse(last.code ?? 'bootstrap-refused');
|
|
// An early refusal, before anything is recorded. The effects below each check again through `guarded`.
|
|
if (name !== 'reserve') fresh();
|
|
const header = { version: 1, business, request, op, kind: 'bootstrap', digest: planDigest };
|
|
journal.prepareEffect({ ...header, stage: 'prepared', result: null, code: null });
|
|
let result;
|
|
try {
|
|
// Every effect after the reservation builds inside a product directory the marker proves is this plan's. A marker that
|
|
// is gone, unreadable or another plan's means ownership can no longer be shown, so nothing further is done and nothing
|
|
// is rewritten: the step is uncertain and the product stays unadmitted.
|
|
if (name !== 'reserve' && !markerOwns()) uncertain();
|
|
result = await run({ recovering: last !== undefined });
|
|
} catch (e) {
|
|
if (!(e instanceof Uncertain)) throw e;
|
|
journal.finishEffect({ ...header, stage: e instanceof ForeignWorking ? 'refused' : 'uncertain', result: null, code: 'bootstrap-uncertain' });
|
|
refuse('bootstrap-uncertain');
|
|
}
|
|
if (after) await services.barrier?.(name);
|
|
journal.finishEffect({ ...header, stage: 'committed', result, code: null });
|
|
return result;
|
|
}
|
|
const done = name => journal.effects(business, request).filter(r => r.op === base(name) && r.stage === 'committed').at(-1)?.result ?? uncertain();
|
|
|
|
// 1. reserve. Everything the plan assumed is checked in one synchronous step, inside the organization lock, so
|
|
// no write lands between the check and the reservation. A mismatch is a stale plan and has no effect.
|
|
const reserve = ({ recovering }) => {
|
|
if (recovering && exists(marker)) { if (!markerOwns()) uncertain(); return { state: 'reserved' }; }
|
|
if (recovering && (exists(product) || exists(here.repo))) uncertain();
|
|
const stale = () => refuse('request-plan-stale');
|
|
return writer.hold(business, ({ revision, document }) => {
|
|
const source = document.projects?.[plan.source.project];
|
|
if (revision !== plan.organization_revision || document.human !== owner || document.id !== business) stale();
|
|
if (!plain(source) || source.kind === 'library' || (source.remote ?? null) !== plan.source.remote) stale();
|
|
if (Object.hasOwn(document.projects, project)) stale();
|
|
if (plan.code_root !== here.root || plan.records_root !== here.repo || overlaps(here.root, here.repo)) stale();
|
|
for (const declared of Object.values(document.projects))
|
|
for (const path of [declared?.root, declared?.repo]) if (typeof path === 'string' && (overlaps(path, here.root) || overlaps(path, here.repo))) stale();
|
|
if (services.chat.state({ business, project, name: plan.name, id: chatId }) !== 'free') stale();
|
|
for (const target of [product, here.repo]) {
|
|
if (!within(dataRoot, target) || target === dataRoot) stale();
|
|
for (let path = target; path !== dataRoot; path = dirname(path)) {
|
|
const st = exists(path);
|
|
if (st === null) continue;
|
|
if (path === target || st.isSymbolicLink() || !st.isDirectory()) stale();
|
|
}
|
|
}
|
|
if (headOf(source.root) !== plan.source.commit) stale();
|
|
mkdirSync(product, { recursive: true, mode: 0o700 });
|
|
mkdirSync(here.repo, { recursive: true, mode: 0o700 });
|
|
writeFileSync(marker, markerBytes({ state: 'reserved', request, plan_digest: planDigest, project }), { flag: 'wx', mode: 0o600 });
|
|
return { state: 'reserved' };
|
|
});
|
|
};
|
|
|
|
// 2. seed. The checkout is the source commit plus one commit that changes only the project file.
|
|
const seedBytes = JSON.stringify({ projectVersion: 1, id: project, vars: plan.project_vars }, null, 2) + '\n';
|
|
const seedFile = join(here.root, PROJECT_FILE), seedTemp = join(product, 'project.json.seed');
|
|
async function seeded() {
|
|
const code = here.root;
|
|
if (!confined(code)) uncertain();
|
|
if (metadataProblem(code)) refuse('bootstrap-metadata-refused');
|
|
const head = await out(code, ['rev-parse', 'HEAD']), remotes = await out(code, ['remote']);
|
|
const status = await out(code, ['status', '--porcelain=v1', '--untracked-files=all', '--ignored=matching']);
|
|
if (!['', 'origin'].includes(remotes)) uncertain();
|
|
if (head === plan.source.commit) {
|
|
// Cloned, or seeded but not yet committed. The only change allowed is the exact project file.
|
|
const onlyFile = status === '' || (/^( M|M ) \.mosaic\/project\.json$/.test(status) && readFileSync(seedFile, 'utf8') === seedBytes);
|
|
if (!onlyFile) uncertain();
|
|
const who = identity(human());
|
|
if (remotes === 'origin') await guarded(() => out(code, ['remote', 'remove', 'origin']));
|
|
if (status === '') guarded(() => publish(seedFile, seedTemp, seedBytes));
|
|
await guarded(() => out(code, ['add', '--', PROJECT_FILE]));
|
|
await guarded(() => out(code, ['commit', '-q', '-m', `Bootstrap ${project} from ${plan.source.project}`], who));
|
|
return { commit: await out(code, ['rev-parse', 'HEAD']), base: plan.source.commit };
|
|
}
|
|
const names = await tryOut(code, ['diff', '--name-status', `${head}~1`, head]);
|
|
if (await tryOut(code, ['rev-parse', `${head}~1`]) === plan.source.commit && names === 'M\t.mosaic/project.json' &&
|
|
status === '' && remotes === '' && readFileSync(seedFile, 'utf8') === seedBytes) return { commit: head, base: plan.source.commit };
|
|
return uncertain();
|
|
}
|
|
// The temporary checkout is this plan's only through a claim file made exclusively beside it, and only while the
|
|
// plan's own seed receipt says an earlier attempt began. A path that is already there on the first attempt, or
|
|
// that holds anything but an empty directory or a clean clone of exactly the source commit, is not ours to build
|
|
// in or remove: it is kept as it is and the step reports `bootstrap-uncertain` (C2).
|
|
const tmp = join(product, 'code.tmp'), claimFile = join(product, 'code.tmp.claim');
|
|
const claimBytes = JSON.stringify({ version: 1, kind: 'bootstrap-clone', request, plan_digest: planDigest, project, path: 'code.tmp' }) + '\n';
|
|
const claimed = () => { const st = exists(claimFile); return Boolean(st && st.isFile() && readFileSync(claimFile, 'utf8') === claimBytes); };
|
|
const dropClaim = () => { if (claimed()) unlinkSync(claimFile); };
|
|
async function clone(recovering) {
|
|
const document = writer.read(business).document, source = document.projects?.[plan.source.project];
|
|
if (!markerOwns() || !confined(product) || !plain(source) || source.kind === 'library' || (source.remote ?? null) !== plan.source.remote) uncertain();
|
|
const held = exists(tmp), claim = exists(claimFile);
|
|
if (!recovering && (held || claim)) uncertain();
|
|
if (claim && !claimed()) uncertain();
|
|
if (held && (!claim || held.isSymbolicLink() || !held.isDirectory())) uncertain();
|
|
if (!held) {
|
|
try {
|
|
guarded(() => {
|
|
if (!claim) writeFileSync(claimFile, claimBytes, { flag: 'wx', mode: 0o600 });
|
|
mkdirSync(tmp, { mode: 0o700 });
|
|
});
|
|
} catch (e) { if (e.code === 'EEXIST') uncertain(); throw e; }
|
|
}
|
|
if (!held || readdirSync(tmp).length === 0) {
|
|
await guarded(() => out(null, ['clone', '-q', '--no-hardlinks', '--template=', '--', source.root, tmp], {}, true));
|
|
}
|
|
await services.barrier?.('clone');
|
|
// A clean clone of exactly the source commit, with at most the remote the clone itself added.
|
|
const head = await tryOut(tmp, ['rev-parse', 'HEAD']), remotes = await tryOut(tmp, ['remote']);
|
|
const status = await tryOut(tmp, ['status', '--porcelain=v1', '--untracked-files=all', '--ignored=matching']);
|
|
if (head === null || remotes === null || status !== '' || !['', 'origin'].includes(remotes)) uncertain();
|
|
if (head !== plan.source.commit) refuse('request-plan-stale');
|
|
if (metadataProblem(tmp)) refuse('bootstrap-metadata-refused');
|
|
if (remotes === 'origin') await guarded(() => out(tmp, ['remote', 'remove', 'origin']));
|
|
guarded(() => {
|
|
if (exists(here.root) || !confined(product)) uncertain();
|
|
renameSync(tmp, here.root);
|
|
});
|
|
await services.barrier?.('cloned');
|
|
}
|
|
const seed = async ({ recovering }) => {
|
|
if (exists(here.root)) {
|
|
const code = exists(here.root);
|
|
if (!code.isDirectory() || code.isSymbolicLink() || !markerOwns()) uncertain();
|
|
} else await clone(recovering);
|
|
const seededAt = await seeded();
|
|
guarded(dropClaim);
|
|
return seededAt;
|
|
};
|
|
|
|
// 3. working. The working repository's main follows the checkout's HEAD, which is the seed commit. Nothing is made
|
|
// while a directory between the data root and the repository is a link or a file (N1: `working` linked to a
|
|
// sibling directory would take the repository and every file in it out of the data root). A repository that is
|
|
// already there on a first attempt stays refused on every retry. Recovery additionally requires the ownership
|
|
// claim written inside the exclusively created init directory before its rename, plus no foreign refs.
|
|
const workingClaim = JSON.stringify({ version: 1, kind: 'bootstrap-working', request, plan_digest: planDigest, project }) + '\n';
|
|
const workingExists = () => {
|
|
let at = dataRoot;
|
|
for (const name of relative(dataRoot, workingPath).split(sep)) {
|
|
at = join(at, name);
|
|
const st = exists(at);
|
|
if (!st) return false;
|
|
if (st.isSymbolicLink() || !st.isDirectory()) uncertain();
|
|
}
|
|
return true;
|
|
};
|
|
const working = async ({ recovering }) => {
|
|
const seedCommit = done('seed').commit;
|
|
if (workingExists()) {
|
|
if (!recovering) throw new ForeignWorking('bootstrap-uncertain');
|
|
inspectWorkingRepository(workingPath);
|
|
const claim = join(workingPath, 'mosaic-bootstrap.json'), owned = exists(claim);
|
|
if (!owned?.isFile() || readFileSync(claim, 'utf8') !== workingClaim) uncertain();
|
|
const at = [`--git-dir=${workingPath}`];
|
|
const refs = await tryOut(null, [...at, 'for-each-ref', '--format=%(refname) %(objectname)']);
|
|
const bare = await tryOut(null, [...at, 'rev-parse', '--is-bare-repository']);
|
|
const expected = new Set(['refs/heads/root', 'refs/heads/main'].map(ref => `${ref} ${seedCommit}`));
|
|
if (bare !== 'true' || refs === null || refs.split('\n').filter(Boolean).some(line => !expected.has(line))) uncertain();
|
|
}
|
|
const w = await initializeWorking({ dataRoot, business, project, root: here.root, around: guarded, claim: workingClaim });
|
|
if (w.commit !== seedCommit) uncertain();
|
|
return { commit: w.commit };
|
|
};
|
|
|
|
// 4. mapping. Only the private exact-add writer can publish it; a revision that moved needs a fresh preview.
|
|
const mapping = () => {
|
|
const found = writer.findAddition(business, { request, plan_digest: planDigest, project });
|
|
const now = writer.read(business);
|
|
if (found) {
|
|
if (canonicalJson(now.document.projects[project]) !== canonicalJson(entry)) uncertain();
|
|
return { organization_revision: found.after };
|
|
}
|
|
if (Object.hasOwn(now.document.projects, project)) uncertain();
|
|
try { writer.addProject(business, { revision: plan.organization_revision, project, entry, receipt }, now.document.human); }
|
|
catch (e) { if (e?.code === 'revision-conflict') refuse('request-plan-stale'); throw e; }
|
|
return { organization_revision: writer.findAddition(business, { request, plan_digest: planDigest, project })?.after ?? uncertain() };
|
|
};
|
|
|
|
// 5. records. The layout commit, by the owner, in the empty directory the reservation made.
|
|
const context = () => ({ business: writer.read(business).document, dataRoot, project });
|
|
const records = async () => {
|
|
const repo = here.repo, st = exists(repo);
|
|
if (!st || !st.isDirectory() || st.isSymbolicLink()) uncertain();
|
|
if (readdirSync(repo).length === 0) {
|
|
const where = context(), author = human();
|
|
const made = await guarded(() => initProject(where, { author }));
|
|
return { commit: made.commit };
|
|
}
|
|
const count = await tryOut(repo, ['rev-list', '--count', 'HEAD']);
|
|
const head = await tryOut(repo, ['log', '-1', '--format=%H|%an|%s', 'HEAD']);
|
|
if (count !== '1' || head === null) uncertain();
|
|
const [commit, author, subject] = head.split('|');
|
|
if (author !== human() || subject !== LAYOUT_SUBJECT || await tryOut(repo, ['status', '--porcelain=v1', '--untracked-files=all']) !== '') uncertain();
|
|
return { commit };
|
|
};
|
|
|
|
// 6. intent. The original displayed text, saved as the owner through the record writer.
|
|
const intent = async () => {
|
|
const repo = here.repo, init = done('records').commit;
|
|
const count = await tryOut(repo, ['rev-list', '--count', 'HEAD']), head = await tryOut(repo, ['rev-parse', 'HEAD']);
|
|
if (count === '1' && head === init) {
|
|
// Every read above and inside the writer is finished before `around` checks and publishes the file.
|
|
const saved = await writeHumanFile({ path: INTENT_PATH, content: plan.intent.text, base: init, around: guarded, ...context() });
|
|
return { commit: saved.commit };
|
|
}
|
|
const line = await tryOut(repo, ['log', '-1', '--format=%P|%an|%s', 'HEAD']);
|
|
if (count !== '2' || line === null) uncertain();
|
|
const [parent, author, subject] = line.split('|');
|
|
if (parent !== init || author !== human() || subject !== `Edit ${INTENT_PATH}` ||
|
|
await tryOut(repo, ['status', '--porcelain=v1', '--untracked-files=all']) !== '' ||
|
|
readFileSync(join(repo, INTENT_PATH), 'utf8') !== plan.intent.text) uncertain();
|
|
return { commit: head };
|
|
};
|
|
|
|
// 7. chat. The association is one row; a row that is not this plan's is a conflict, never replaced. No await sits
|
|
// between the step's own check and the association.
|
|
const chat = () => {
|
|
const args = { business, project, name: plan.name, id: chatId }, state = services.chat.state(args);
|
|
if (state === 'conflict') uncertain();
|
|
if (state === 'free') services.chat.associate(args);
|
|
return { chat_project: chatId };
|
|
};
|
|
|
|
// 8. activate. Publish and verify the complete marker, then commit the receipt before reloading the broker.
|
|
// A receipt failure leaves the live broker fenced; retries replay committed receipts and retry the reload.
|
|
const activate = async () => {
|
|
await services.barrier?.('activate');
|
|
const mapped = done('mapping');
|
|
guarded(() => {
|
|
publish(marker, `${marker}.tmp`, markerBytes({ state: 'complete', request, plan_digest: planDigest, project }));
|
|
if (!markerOwns() || readMarker(marker).state !== 'complete') uncertain();
|
|
});
|
|
return { project, organization_revision: mapped.organization_revision };
|
|
};
|
|
|
|
await services.barrier?.('begin');
|
|
await step('reserve', reserve);
|
|
await step('seed', seed);
|
|
await step('working', working);
|
|
await step('mapping', mapping);
|
|
await step('records', records);
|
|
const saved = await step('intent', intent);
|
|
const associated = await step('chat', chat);
|
|
const activated = await step('activate', activate, { after: false });
|
|
active();
|
|
try { services.activate({ business, project, receipt, organization_revision: activated.organization_revision }); }
|
|
catch (e) { if (e?.code === 'bootstrap-revision-stale') refuse('request-plan-stale'); throw e; }
|
|
return { project, chat_project: associated.chat_project, spec_commit: saved.commit, organization_revision: activated.organization_revision };
|
|
}
|