Lifecycle Task 2 (#797). A confirmed new-project selection now becomes a usable product: the code checkout, the organization mapping, the records repository with the original intent as the owner's spec commit, the chat association and the working repository, each journaled as its own receipt (bootstrap:<plan_digest>:<step>) and recoverable after a kill. - business: addProject is a private exact-add writer under the existing organization lock and receipt discipline; hold runs a synchronous check under that lock; findAddition recovers a prepared receipt. Ordinary writers still refuse every project change. - bus: prepareBootstrap and executeBootstrap; activateManagedProject reloads only a receipt-backed additive root and admits it to the broker after readiness; request.admission host IPC op for the launcher. - #800: the bound organization revision and association are re-verified inside the organization lock at the start of execution; a mismatch records request-plan-stale and performs no effect. - cli: trackerFor skips reserved products; the launcher refuses to clone a product the bus has not admitted. - seat: initializeWorking seeds the working repository, host-only, with no work ref or push authority. - schema: append-only migration 3o to 3p widens the request_events kind list with bootstrap.stale and bootstrap.completed.
209 lines
17 KiB
JavaScript
209 lines
17 KiB
JavaScript
// Trusted host journal. No SQL, transition or effect interface is exposed to workers.
|
|
import { createHash } from 'node:crypto';
|
|
import { isAbsolute, normalize } from 'node:path';
|
|
import { ID_PATTERN, parseGiteaUrl } from '../../business/src/vocabulary.mjs';
|
|
import { checkVars } from '../../business/src/vars.mjs';
|
|
|
|
export class RequestError extends Error {
|
|
constructor(code) { super(code); this.code = code; }
|
|
}
|
|
export const refuse = code => { throw new RequestError(code); };
|
|
export const object = x => x !== null && typeof x === 'object' && !Array.isArray(x);
|
|
export const text = (x, max = 32768) => typeof x === 'string' && x.length > 0 && x.length <= max && !x.includes('\0');
|
|
export const id = x => text(x, 160) && /^[a-zA-Z0-9][a-zA-Z0-9_.:/-]*$/.test(x);
|
|
export const key = x => typeof x === 'string' && ID_PATTERN.test(x);
|
|
const hash = x => typeof x === 'string' && /^[a-f0-9]{64}$/.test(x);
|
|
const oid = x => typeof x === 'string' && /^[a-f0-9]{40}([a-f0-9]{24})?$/.test(x);
|
|
const positive = x => Number.isSafeInteger(x) && x > 0;
|
|
export function exact(x, keys, optional = [], code = 'invalid-request') {
|
|
if (!object(x) || keys.some(k => !Object.hasOwn(x, k)) || Object.keys(x).some(k => !keys.includes(k) && !optional.includes(k))) refuse(code);
|
|
}
|
|
const canonical = x => Array.isArray(x) ? x.map(canonical) : object(x)
|
|
? Object.fromEntries(Object.keys(x).sort().map(k => [k, canonical(x[k])])) : x;
|
|
export const digest = x => createHash('sha256').update(typeof x === 'string' ? x : JSON.stringify(canonical(x))).digest('hex');
|
|
const equal = (a, b) => digest(a) === digest(b);
|
|
const nullableId = x => x === null || id(x);
|
|
export function validatePlan(p) {
|
|
const code = 'invalid-request-plan', shape = (x, keys) => exact(x, keys, [], code);
|
|
shape(p, ['version','business','request','project','name','chat_project','mode','organization_revision','source','code_root','records_root','tracker','staff','intent','project_vars','existing']);
|
|
if (p.version !== 1 || !key(p.business) || !id(p.request) || !key(p.project) || !text(p.name, 200) || /[\r\n]/.test(p.name) ||
|
|
!nullableId(p.chat_project) || !['autonomous','guided'].includes(p.mode) || !text(p.organization_revision, 256) || typeof p.existing !== 'boolean') refuse(code);
|
|
shape(p.source, ['project','commit','remote','forks']);
|
|
if (!key(p.source.project) || !oid(p.source.commit) || (p.source.remote !== null && !parseGiteaUrl(p.source.remote, { repo: true }).url) || !Array.isArray(p.source.forks)) refuse(code);
|
|
const instances = new Set();
|
|
for (const f of p.source.forks) {
|
|
shape(f, ['instance','url','grant','state']);
|
|
if (!key(f.instance) || instances.has(f.instance) || !parseGiteaUrl(f.url, { repo: true }).url || !nullableId(f.grant) || !['verified','not-granted'].includes(f.state)) refuse(code);
|
|
instances.add(f.instance);
|
|
}
|
|
for (const path of [p.code_root, p.records_root]) if (!text(path, 4096) || !isAbsolute(path) || normalize(path) !== path) refuse(code);
|
|
if (p.code_root === p.records_root || p.code_root.startsWith(p.records_root + '/') || p.records_root.startsWith(p.code_root + '/')) refuse(code);
|
|
shape(p.tracker, ['root','project']);
|
|
if (!positive(p.tracker.root) || !positive(p.tracker.project)) refuse(code);
|
|
shape(p.staff, ['pm','technical_reviewer','coder','reviewer','chief']);
|
|
if (!Object.values(p.staff).every(key) || p.staff.pm === p.staff.technical_reviewer) refuse(code);
|
|
shape(p.intent, ['text','sha256','source_message','generated']);
|
|
if (!text(p.intent.text) || !hash(p.intent.sha256) || digest(p.intent.text) !== p.intent.sha256 || !id(p.intent.source_message) || typeof p.intent.generated !== 'boolean') refuse(code);
|
|
if (!object(p.project_vars) || Object.hasOwn(p.project_vars, 'tracker.project')) refuse(code);
|
|
try { checkVars(p.project_vars, 'project', 'request resource plan'); } catch { refuse(code); }
|
|
return p;
|
|
}
|
|
function initial(business, request, b) {
|
|
exact(b, ['source_message','thread','session','owner','pm','intent'], [], 'invalid-request-event');
|
|
if (!id(b.source_message) || !nullableId(b.thread) || !nullableId(b.session) || !id(b.owner) || !key(b.pm)) refuse('invalid-request-event');
|
|
exact(b.intent, ['text','sha256','source_message','generated'], [], 'invalid-request-event');
|
|
if (!text(b.intent.text) || digest(b.intent.text) !== b.intent.sha256 || b.intent.source_message !== b.source_message || b.intent.generated !== false) refuse('invalid-request-event');
|
|
return { version: 1, request, business, revision: 1, source_message: b.source_message, thread: b.thread, session: b.session,
|
|
owner: b.owner, pm: b.pm, phase: 'selection', project: null, chat_project: null, mode: null, mode_revision: 0,
|
|
plan_digest: null, spec_commit: null, snapshot: null, tasks: [], delivery: null, question: null, candidate: null, selection: null,
|
|
// The owner's chosen route survives every setup wait; a wait code never says which route was chosen.
|
|
route: null, wait: null };
|
|
}
|
|
function reduce(state, e) {
|
|
const code = 'invalid-request-event', b = e.body;
|
|
if (e.kind === 'opened') { if (state || e.revision !== 1) refuse(code); return initial(e.business, e.request, b); }
|
|
if (!state || e.revision !== state.revision + 1 || state.phase === 'cancelled') refuse(code);
|
|
const s = structuredClone(state); s.revision = e.revision;
|
|
if (e.kind === 'setup.wait') {
|
|
exact(b, ['code','subject'], ['op','proposal_digest'], code);
|
|
if (!text(b.code, 128) || !id(b.subject) || ('op' in b && (!id(b.op) || !hash(b.proposal_digest)))) refuse(code);
|
|
s.wait = { kind: 'setup', code: b.code, subject: b.subject, resume_phase: s.phase, observed_revision: s.revision };
|
|
} else if (e.kind === 'selection.proposed') {
|
|
exact(b, ['op','proposal_digest','decision','bindings','kind'], [], code);
|
|
if (s.phase !== 'selection' || s.wait?.kind === 'decision' || !id(b.op) || !hash(b.proposal_digest) || !id(b.decision) || !['mode','existing'].includes(b.kind) || !Array.isArray(b.bindings)) refuse(code);
|
|
const choices = b.kind === 'mode' ? ['autonomous','guided'] : ['confirm'];
|
|
if (b.bindings.length !== choices.length) refuse(code);
|
|
for (let i = 0; i < choices.length; i++) {
|
|
const binding = b.bindings[i]; exact(binding, ['plan','digest','decision','choice'], [], code); validatePlan(binding.plan);
|
|
if (binding.choice !== choices[i] || binding.decision !== b.decision || binding.digest !== digest(binding.plan) ||
|
|
binding.plan.business !== s.business || binding.plan.request !== s.request || binding.plan.staff.pm !== s.pm ||
|
|
binding.plan.intent.source_message !== s.source_message || binding.plan.existing !== (b.kind === 'existing') ||
|
|
(b.kind === 'mode' && binding.plan.mode !== binding.choice)) refuse(code);
|
|
}
|
|
s.selection = { decision: b.decision, bindings: structuredClone(b.bindings) };
|
|
s.wait = { kind: 'decision', code: b.kind === 'mode' ? 'request-mode' : 'request-existing-confirmation', subject: b.decision, resume_phase: 'selection', observed_revision: s.revision };
|
|
} else if (e.kind === 'selection.staged') {
|
|
exact(b, ['decision','choice'], [], code);
|
|
if (s.wait?.kind !== 'decision' || s.selection?.decision !== b.decision || !['existing','back'].includes(b.choice) ||
|
|
(b.choice === 'existing') !== (s.wait.code === 'request-mode')) refuse(code);
|
|
s.selection = null; s.route = 'existing';
|
|
s.wait = { kind: 'setup', code: 'request-existing-project', subject: s.request, resume_phase: 'selection', observed_revision: s.revision };
|
|
} else if (e.kind === 'selection.confirmed') {
|
|
exact(b, ['decision','choice','digest'], [], code);
|
|
const binding = s.selection?.bindings.find(p => p.decision === b.decision && p.choice === b.choice && p.digest === b.digest);
|
|
if (s.wait?.kind !== 'decision' || !binding) refuse(code);
|
|
const p = binding.plan;
|
|
s.project = p.project; s.chat_project = p.chat_project; s.mode = p.mode; s.mode_revision = 1; s.plan_digest = binding.digest;
|
|
s.phase = p.existing ? 'discovery' : 'bootstrap';
|
|
s.wait = { kind: 'setup', code: p.existing ? 'request-attachment-unavailable' : 'request-bootstrap-unavailable', subject: s.request, resume_phase: s.phase, observed_revision: s.revision };
|
|
} else if (e.kind === 'bootstrap.stale') {
|
|
// The confirmed plan no longer matches the world (#800). Nothing was bound; the owner gets a fresh preview.
|
|
exact(b, ['digest','code'], [], code);
|
|
if (s.phase !== 'bootstrap' || s.plan_digest !== b.digest || b.code !== 'request-plan-stale') refuse(code);
|
|
s.project = null; s.chat_project = null; s.mode = null; s.mode_revision = 0; s.plan_digest = null; s.selection = null; s.phase = 'selection';
|
|
s.wait = { kind: 'setup', code: b.code, subject: s.request, resume_phase: 'selection', observed_revision: s.revision };
|
|
} else if (e.kind === 'bootstrap.completed') {
|
|
exact(b, ['digest','project','chat_project','spec_commit','organization_revision'], [], code);
|
|
if (s.phase !== 'bootstrap' || s.plan_digest !== b.digest || b.project !== s.project || !id(b.chat_project) || !oid(b.spec_commit) || !text(b.organization_revision, 256)) refuse(code);
|
|
s.chat_project = b.chat_project; s.spec_commit = b.spec_commit; s.phase = 'discovery';
|
|
s.wait = { kind: 'setup', code: 'request-discovery-unavailable', subject: s.request, resume_phase: 'discovery', observed_revision: s.revision };
|
|
} else if (e.kind === 'cancelled') {
|
|
exact(b, ['decision'], [], code);
|
|
if (s.wait?.kind !== 'decision' || s.selection?.decision !== b.decision) refuse(code);
|
|
s.phase = 'cancelled'; s.wait = null; s.selection = null;
|
|
} else refuse(code);
|
|
return s;
|
|
}
|
|
export function createRequestStore(store) {
|
|
const validateIntent = (event, origin) => {
|
|
if (event.kind === 'selection.proposed' && (!Array.isArray(event.body.bindings) ||
|
|
event.body.bindings.some(b => !object(b?.plan?.intent) || !equal(b.plan.intent, origin?.intent)))) refuse('invalid-request-event');
|
|
};
|
|
const readRequest = (business, request) => {
|
|
if (!key(business) || !id(request)) refuse('invalid-request');
|
|
const events = store.all('SELECT * FROM request_events WHERE business=? AND request=? ORDER BY revision', business, request)
|
|
.map(e => ({ ...e, body: JSON.parse(e.body) }));
|
|
return events.reduce((s, e) => { validateIntent(e, events[0].body); return reduce(s, e); }, null);
|
|
};
|
|
// appendInTransaction is only for composing the decision and journal atomically on the host.
|
|
const appendInTransaction = e => {
|
|
exact(e, ['business','request','expectedRevision','kind','body','actor']);
|
|
exact(e.actor, ['role','run']);
|
|
if (!key(e.business) || !id(e.request) || !Number.isSafeInteger(e.expectedRevision) || e.expectedRevision < 0 ||
|
|
!((e.actor.role === null && e.actor.run === null) || (key(e.actor.role) && id(e.actor.run)))) refuse('invalid-request-event');
|
|
const state = readRequest(e.business, e.request);
|
|
if ((state?.revision ?? 0) !== e.expectedRevision) refuse('request-revision-conflict');
|
|
const next = reduce(state, { ...e, revision: e.expectedRevision + 1 });
|
|
if (e.kind === 'opened') {
|
|
const source = store.get(`SELECT m.id,m.body,mt.thread,mt.session FROM events e JOIN messages m ON m.id=e.subject
|
|
AND m.id=json_extract(e.body,'$.message') AND m.business=e.business
|
|
LEFT JOIN message_threads mt ON mt.message=m.id
|
|
WHERE e.business=? AND e.id=? AND e.kind='human.input' AND e.actor_role IS NULL AND e.actor_run IS NULL
|
|
AND json_extract(e.body,'$.kind')='instruction' AND m.from_role='human'`, e.business, e.request);
|
|
if (!source || source.id !== e.body.source_message || source.body !== e.body.intent?.text ||
|
|
(source.thread ?? null) !== e.body.thread || (source.session ?? null) !== e.body.session) refuse('request-origin-refused');
|
|
}
|
|
if (e.kind === 'selection.proposed') {
|
|
const origin = JSON.parse(store.get("SELECT body FROM request_events WHERE business=? AND request=? AND kind='opened'", e.business, e.request).body);
|
|
validateIntent(e, origin);
|
|
const d = store.get('SELECT * FROM decisions WHERE business=? AND id=?', e.business, e.body.decision);
|
|
if (!d || d.action !== 'project.bootstrap' || d.route_to !== 'human' || d.blocking !== 0 || d.task_ref !== null || d.requirement_ref !== null ||
|
|
d.raised_by_role !== state.pm || store.get("SELECT 1 FROM decision_events WHERE decision=? AND op IN ('resolved','withdrawn','expired')", d.id)) refuse('invalid-request-event');
|
|
}
|
|
// A bootstrap outcome follows only from the receipts it names, so the journal cannot claim a project
|
|
// that was not activated, or retreat from one whose mapping already landed.
|
|
if (e.kind === 'bootstrap.completed' || e.kind === 'bootstrap.stale') {
|
|
const op = step => store.get("SELECT result FROM request_effects WHERE business=? AND request=? AND op=? AND kind='bootstrap' AND stage='committed'",
|
|
e.business, e.request, `bootstrap:${e.body.digest}:${step}`);
|
|
if (e.kind === 'bootstrap.completed') {
|
|
const done = op('activate');
|
|
if (!done || JSON.parse(done.result).project !== e.body.project) refuse('invalid-request-event');
|
|
} else if (op('mapping')) refuse('invalid-request-event');
|
|
}
|
|
store.run('INSERT INTO request_events(business,request,revision,kind,actor_role,actor_run,at,body) VALUES(?,?,?,?,?,?,?,?)',
|
|
e.business, e.request, next.revision, e.kind, e.actor.role, e.actor.run, new Date().toISOString(), JSON.stringify(e.body));
|
|
return next;
|
|
};
|
|
function receipt(r, prepare) {
|
|
exact(r, ['version','business','request','op','kind','digest','stage','result','code'], [], 'invalid-request-effect');
|
|
if (r.version !== 1 || !key(r.business) || !id(r.request) || !id(r.op) || !hash(r.digest) ||
|
|
!['bootstrap','prd-submit','prd-activate','task-create','continuation','delivery'].includes(r.kind) ||
|
|
!(prepare ? r.stage === 'prepared' && r.result === null && r.code === null : ['committed','uncertain','refused'].includes(r.stage)) ||
|
|
!(r.result === null || object(r.result)) || !(r.code === null || text(r.code, 128))) refuse('invalid-request-effect');
|
|
return store.transaction(() => {
|
|
if (!readRequest(r.business, r.request)) refuse('request-not-found');
|
|
const rows = store.all('SELECT version,business,request,op,kind,digest,stage,result,code FROM request_effects WHERE business=? AND request=? AND op=? ORDER BY seq', r.business, r.request, r.op)
|
|
.map(x => ({ ...x, result: x.result === null ? null : JSON.parse(x.result) }));
|
|
if (rows.some(x => x.digest !== r.digest || x.kind !== r.kind)) refuse('request-effect-conflict');
|
|
// A retry must see committed/uncertain/refused evidence instead of executing again.
|
|
if (prepare && rows.length) return structuredClone(rows.at(-1));
|
|
const old = rows.find(x => x.stage === r.stage);
|
|
if (old) { if (!equal(old, r)) refuse('request-effect-conflict'); return structuredClone(r); }
|
|
if (!prepare && !rows.some(x => x.stage === 'prepared')) refuse('request-effect-unprepared');
|
|
if (rows.some(x => ['committed','refused'].includes(x.stage))) refuse('request-effect-conflict');
|
|
store.run('INSERT INTO request_effects(at,version,business,request,op,kind,digest,stage,result,code) VALUES(?,?,?,?,?,?,?,?,?,?)',
|
|
new Date().toISOString(), r.version, r.business, r.request, r.op, r.kind, r.digest, r.stage, r.result === null ? null : JSON.stringify(r.result), r.code);
|
|
return structuredClone(r);
|
|
});
|
|
}
|
|
return Object.freeze({ readRequest, appendRequest: e => store.transaction(() => appendInTransaction(e)),
|
|
prepareEffect: r => receipt(r, true), finishEffect: r => receipt(r, false),
|
|
transaction: fn => store.transaction(() => fn({ appendRequest: appendInTransaction, readRequest })),
|
|
// Receipts read back, parsed. Hosts use these to resume a bootstrap and to rebuild readiness.
|
|
effects: (business, request) => {
|
|
if (!key(business) || !id(request)) refuse('invalid-request');
|
|
return store.all('SELECT version,business,request,op,kind,digest,stage,result,code FROM request_effects WHERE business=? AND request=? ORDER BY seq', business, request)
|
|
.map(x => ({ ...x, result: x.result === null ? null : JSON.parse(x.result) }));
|
|
},
|
|
committed: (business, kind) => {
|
|
if (!key(business)) refuse('invalid-request');
|
|
return store.all("SELECT request,op,digest,result FROM request_effects WHERE business=? AND kind=? AND stage='committed' ORDER BY seq", business, kind)
|
|
.map(x => ({ ...x, result: x.result === null ? null : JSON.parse(x.result) }));
|
|
},
|
|
listRequests: () => store.all('SELECT DISTINCT business,request FROM request_events ORDER BY business,request'),
|
|
proposal: (business, request, op) => {
|
|
const row = store.get("SELECT body FROM request_events WHERE business=? AND request=? AND json_extract(body,'$.op')=? ORDER BY seq DESC LIMIT 1", business, request, op);
|
|
return row ? JSON.parse(row.body) : null;
|
|
} });
|
|
}
|