# Conflicts: # BUILD-LOG.md # docs/SESSIONS.md # packages/bus/tests/request-continuation.test.mjs # packages/webui/src/public/chat.js # packages/webui/src/public/index.html # packages/webui/src/serve.mjs # packages/webui/tests/browser.test.mjs
621 lines
46 KiB
JavaScript
621 lines
46 KiB
JavaScript
import { requestArchived } from './broker.mjs';
|
|
// Host controller for pre-task intake. Task 1 prepares and records selections only. Task 3 (#1839) adds the
|
|
// PM's question and the owner's Console answer, existing-project pick and cancellation. The owner's mode change is Task 4's
|
|
// modeConsole, which moves the project's mode revision and every request attached to it.
|
|
// Later executors must consume these exact immutable bindings, never approvalChoice.
|
|
import { createContinuations } from './request-continuation.mjs';
|
|
import { lstatSync } from 'node:fs';
|
|
import { randomUUID } from 'node:crypto';
|
|
import { basename } from 'node:path';
|
|
import { join, dirname } from 'node:path';
|
|
import { exact, object, id, key, text, digest, validatePlan, refuse, positive, optionList, QUESTION_PHASES, PICKER_CODES } from './request-store.mjs';
|
|
|
|
export function createRequestLifecycle({ journal, services }) {
|
|
if (!journal || !services || !['origin','authorize','raiseDecision','readDecision','project'].every(k => typeof services[k] === 'function')) refuse('request-services-unavailable');
|
|
const continuations = createContinuations({ journal, services });
|
|
let closing = false, recovery = null, recoveryAgain = false, cursor = 0;
|
|
const pending = new Map();
|
|
const serial = (business, request, fn) => {
|
|
const k = business + '/' + request;
|
|
const job = (pending.get(k) ?? Promise.resolve()).catch(() => {}).then(fn);
|
|
pending.set(k, job);
|
|
return job.finally(() => { if (pending.get(k) === job) pending.delete(k); });
|
|
};
|
|
const active = (state, ...projects) => {
|
|
if (requestArchived(state, services, projects)) refuse('project-archived');
|
|
};
|
|
const stateOf = (business, request) => journal.readRequest(business, request) ?? refuse('request-not-found');
|
|
const actor = identity => ({ role: identity?.role ?? null, run: identity?.run ?? null });
|
|
const authorize = (identity, state, operation) => services.authorize(identity, state, operation);
|
|
// `write` is journal.appendRequest outside a transaction and tx.appendRequest inside one.
|
|
const append = (state, kind, body, identity = null, write = journal.appendRequest) => write({ business: state.business, request: state.request,
|
|
expectedRevision: state.revision, kind, body, actor: actor(identity) });
|
|
const wait = (state, code, identity = null, proposal = {}, write = journal.appendRequest) => {
|
|
if (state.wait?.kind === 'setup' && state.wait.code === code && !proposal.op) return state;
|
|
return append(state, 'setup.wait', { code, subject: state.request, ...proposal }, identity, write);
|
|
};
|
|
async function open(identity, args) {
|
|
exact(args, ['request']); if (!id(args.request)) refuse('invalid-request');
|
|
return serial(identity.business, args.request, () => {
|
|
const source = services.origin(identity, args.request);
|
|
const old = journal.readRequest(identity.business, args.request);
|
|
if (old) { authorize(identity, old, 'get'); return old; }
|
|
const state = { business: identity.business, request: args.request, owner: source.owner, pm: source.pm };
|
|
authorize(identity, state, 'open');
|
|
active({ ...state, thread: source.thread });
|
|
return journal.transaction(tx => {
|
|
const result = tx.appendRequest({ business: state.business, request: state.request, expectedRevision: 0, kind: 'opened', actor: actor(identity),
|
|
body: { source_message: source.source_message, thread: source.thread, session: source.session, owner: source.owner, pm: source.pm,
|
|
intent: { text: source.text, sha256: digest(source.text), source_message: source.source_message, generated: false } } });
|
|
services.record?.(identity, 'request.open', result); return result;
|
|
});
|
|
});
|
|
}
|
|
async function get(identity, args) {
|
|
exact(args, ['request'], ['path']); if (!id(args.request) || (args.path !== undefined && !text(args.path, 256))) refuse('invalid-request');
|
|
const state = stateOf(identity.business, args.request); authorize(identity, state, 'get');
|
|
if (args.path === undefined) return state;
|
|
if (!state.candidate) refuse('prd-candidate-required');
|
|
const selected = args.path === state.candidate.prd_path ? { blob: state.candidate.prd_blob }
|
|
: state.candidate.requirements.find(r => r.path === args.path);
|
|
if (!selected) refuse('request-document-refused');
|
|
const material = await services.readCandidate(state.candidate, state.business);
|
|
const now = stateOf(state.business, state.request); authorize(identity, now, 'get');
|
|
if (now.revision !== state.revision) refuse('request-revision-conflict');
|
|
return { request: state.request, revision: state.revision, records_commit: state.candidate.records_commit, path: args.path, blob: selected.blob,
|
|
content: args.path === state.candidate.prd_path ? material.prd : material.requirements.find(r => r.id === selected.id) };
|
|
|
|
}
|
|
async function projects(identity, args, remember = true) {
|
|
exact(args, ['request']);
|
|
const state = await get(identity, args);
|
|
const rows = await services.listProjects?.(structuredClone(state), identity, { remember }) ?? [];
|
|
authorize(identity, stateOf(state.business, state.request), 'get');
|
|
if (!Array.isArray(rows)) refuse('invalid-request-projects');
|
|
return rows.filter(p => object(p) && p.business === state.business && key(p.project) && !services.projectArchived?.(state.business, p.project) && services.project(state.business, p.project) &&
|
|
text(p.name, 200) && object(p.tracker) && Number.isSafeInteger(p.tracker.root) && p.tracker.root > 0 && Number.isSafeInteger(p.tracker.project) && p.tracker.project > 0)
|
|
.map(p => ({ business: state.business, project: p.project, name: p.name, tracker: { root: p.tracker.root, project: p.tracker.project }, ...(p.mapping_revision ? { mapping_revision: p.mapping_revision } : {}) }));
|
|
}
|
|
function localPlan(p, state, args, source) {
|
|
validatePlan(p);
|
|
active(state, p.project, p.source.project, p.chat_project);
|
|
if (p.business !== state.business || p.request !== state.request || p.project !== args.project || p.name !== args.name ||
|
|
p.source.project !== args.source_project || p.tracker.project !== args.tracker_project || p.staff.pm !== state.pm ||
|
|
p.intent.text !== source.text || p.intent.source_message !== source.source_message || p.intent.generated !== false) refuse('request-plan-binding-refused');
|
|
const mapping = services.project(state.business, p.source.project);
|
|
if (!mapping || (mapping.remote ?? null) !== p.source.remote) refuse('request-plan-binding-refused');
|
|
// An existing project's code checkout is its mapping `root`; its records repository is `repo`, or the data root default.
|
|
if (p.existing && (p.code_root !== mapping.root || p.records_root !== (mapping.repo ?? join(services.dataRoot, 'projects', state.business, p.project)))) refuse('request-plan-binding-refused');
|
|
// No inferred resource names or filesystem effects: preparation must supply exact roots.
|
|
if (!p.existing) {
|
|
if (services.project(state.business, p.project)) refuse('request-project-collision');
|
|
if (!services.dataRoot || p.code_root !== join(services.dataRoot, 'products', p.business, p.project, 'code') ||
|
|
p.records_root !== join(services.dataRoot, 'projects', p.business, p.project)) refuse('request-plan-path-refused');
|
|
for (const path of [p.code_root, p.records_root]) {
|
|
for (const declared of services.projectPaths?.(state.business) ?? [])
|
|
if (path === declared || path.startsWith(declared + '/') || declared.startsWith(path + '/')) refuse('request-plan-path-collision');
|
|
for (let parent = path; ; parent = dirname(parent)) {
|
|
try {
|
|
const stat = lstatSync(parent);
|
|
if (stat.isSymbolicLink() || !stat.isDirectory() || parent === path || parent === dirname(p.code_root)) refuse('request-plan-path-collision');
|
|
} catch (e) { if (e.code !== 'ENOENT') throw e; }
|
|
if (parent === services.dataRoot) break;
|
|
if (parent === dirname(parent)) refuse('request-plan-path-refused');
|
|
}
|
|
}
|
|
}
|
|
return p;
|
|
}
|
|
// The host inventory and admission are asynchronous and neither bumps the request revision, so a
|
|
// plan can go stale while a call is in flight. `staleCode` is the guard for that: callers read the
|
|
// inventory as their last await and call it inside the synchronous journal transaction, so no
|
|
// mapping or board change can land between this check and the append. It never confirms a stale plan.
|
|
const associated = (rows, p) => Array.isArray(rows) && rows.some(m => object(m) && m.business === p.business && m.project === p.project &&
|
|
m.name === p.name && m.tracker?.root === p.tracker.root && m.tracker?.project === p.tracker.project);
|
|
function staleCode(plan, state, args, source, rows) {
|
|
try { active(state, plan.project, plan.source.project, plan.chat_project); }
|
|
catch (e) { if (e.code === 'project-archived') return e.code; throw e; }
|
|
if (plan.existing && !associated(rows, plan)) return 'request-existing-project-changed';
|
|
try { localPlan(plan, state, args, source); } catch (e) {
|
|
if (!e.code?.startsWith('request-')) throw e;
|
|
return e.code;
|
|
}
|
|
return null;
|
|
}
|
|
async function admission(plan, state) {
|
|
if (!services.admitPlan) return 'request-admission-unavailable';
|
|
const result = await services.admitPlan(structuredClone(plan), structuredClone(state));
|
|
if (!object(result) || typeof result.ready !== 'boolean' || Object.keys(result).some(k => !['ready','code'].includes(k)) ||
|
|
(result.ready && result.code !== undefined) || (!result.ready && !text(result.code, 128))) refuse('invalid-request-admission');
|
|
return result.ready ? null : result.code;
|
|
}
|
|
async function propose(identity, args) {
|
|
exact(args, ['request','revision','op','source_project','project','name','tracker_project']);
|
|
if (!id(args.request) || !Number.isSafeInteger(args.revision) || args.revision < 1 || !id(args.op) || !key(args.source_project) ||
|
|
!key(args.project) || !text(args.name, 200) || /[\r\n]/.test(args.name) || !Number.isSafeInteger(args.tracker_project) || args.tracker_project < 1) refuse('invalid-request');
|
|
return serial(identity.business, args.request, async () => {
|
|
let state = stateOf(identity.business, args.request); authorize(identity, state, 'propose');
|
|
const proposal_digest = digest(args), old = journal.proposal(state.business, state.request, args.op);
|
|
if (old) { if (old.proposal_digest !== proposal_digest) refuse('request-operation-conflict'); return state; }
|
|
if (state.revision !== args.revision) refuse('request-revision-conflict');
|
|
if (state.phase !== 'selection' || state.wait?.kind === 'decision') refuse('request-phase-refused');
|
|
active(state, args.source_project, args.project);
|
|
const source = services.origin(identity, args.request);
|
|
if (!services.project(state.business, args.source_project)) refuse('request-project-refused');
|
|
// The route is journaled when the owner stages it; no setup wait code can erase or imply it.
|
|
const existing = state.route === 'existing';
|
|
// The owner's pick binds the PM: it proposes the picked project or nothing (#1839).
|
|
if (existing && state.wait?.code === 'request-attachment-selected' && args.project !== state.wait.subject) refuse('request-attachment-mismatch');
|
|
if (!existing && services.project(state.business, args.project)) refuse('request-project-collision');
|
|
let candidate = null;
|
|
if (existing) {
|
|
candidate = (await projects(identity, { request: args.request }, false)).find(p => p.project === args.project && p.tracker.project === args.tracker_project && p.name === args.name);
|
|
if (!candidate || args.source_project !== args.project) refuse('request-project-refused');
|
|
}
|
|
const prepare = existing ? services.prepareExisting : services.preparePlans;
|
|
const recheck = () => {
|
|
const current = stateOf(state.business, state.request); authorize(identity, current, 'propose');
|
|
active(current, args.source_project, args.project);
|
|
if (current.revision !== args.revision) refuse('request-revision-conflict');
|
|
return current;
|
|
};
|
|
const pendingWait = (code, write) => wait(recheck(), code, identity, { op: args.op, proposal_digest }, write);
|
|
if (!prepare) return pendingWait('request-preparation-unavailable');
|
|
const prepared = await prepare(structuredClone(state), structuredClone(args), structuredClone(source));
|
|
recheck();
|
|
// Preparation may be unable to name real resources at all. It reports that before any
|
|
// proposal or decision exists; it must never substitute fabricated paths or tracker IDs.
|
|
if (object(prepared) && prepared.ready === false) {
|
|
exact(prepared, ['ready','code'], [], 'invalid-request-plan');
|
|
if (!text(prepared.code, 128)) refuse('invalid-request-plan');
|
|
return pendingWait(prepared.code);
|
|
}
|
|
const plans = existing ? [prepared] : prepared;
|
|
if (!Array.isArray(plans) || plans.length !== (existing ? 1 : 2)) refuse('invalid-request-plan');
|
|
// Validate every plan before the first admission await. A change after this point is not a
|
|
// malformed plan; the guard in the final transaction turns it into a stale wait.
|
|
for (let i = 0; i < plans.length; i++) {
|
|
const p = localPlan(plans[i], state, args, source);
|
|
if (p.existing !== existing || (!existing && p.mode !== ['autonomous','guided'][i]) || (existing && p.tracker.root !== candidate.tracker.root)) refuse('request-plan-binding-refused');
|
|
}
|
|
for (const p of plans) {
|
|
const missing = await admission(p, state); recheck(); if (missing) return pendingWait(missing);
|
|
}
|
|
// Both modes must display the same concrete resources and original intent.
|
|
if (!existing && digest({ ...plans[0], mode: null }) !== digest({ ...plans[1], mode: null })) refuse('request-plan-binding-refused');
|
|
state = recheck();
|
|
const { mode, ...resources } = plans[0];
|
|
const question = `Confirm the resource plan for ${args.name}. ${existing ? `Existing project mode: ${mode}.` : 'Both new project choices use these resources with the selected mode.'} Original user intent and exact resources:\n${JSON.stringify(resources)}`;
|
|
// Preserve the ordinary decision channel's existing display limit and all source bytes.
|
|
if (question.length > 4096) return pendingWait('request-plan-display-too-large');
|
|
// Last await. Preparation and admission may have outlived the association they bound, so read
|
|
// it again and let the synchronous guard in the transaction decide before any decision exists.
|
|
const rows = existing ? await projects(identity, { request: args.request }, false) : null;
|
|
return journal.transaction(tx => {
|
|
state = recheck();
|
|
for (const plan of plans) {
|
|
const late = staleCode(plan, state, args, source, rows);
|
|
if (late) return pendingWait(late, tx.appendRequest);
|
|
}
|
|
const options = existing ? [{ key: 'confirm', text: 'Confirm this existing project association' }, { key: 'back', text: 'Choose another existing project' }]
|
|
: [{ key: 'autonomous', text: 'New project — autonomous' }, { key: 'guided', text: 'New project — guided' }, { key: 'existing', text: 'Add to existing project' }];
|
|
const decision = services.raiseDecision(identity, { action: 'project.bootstrap', question, options, recommendation: options[0].key,
|
|
approvalChoice: options[0].key, blocking: false });
|
|
const result = tx.appendRequest({ business: state.business, request: state.request, expectedRevision: state.revision, kind: 'selection.proposed', actor: actor(identity),
|
|
body: { op: args.op, proposal_digest, decision: decision.id, kind: existing ? 'existing' : 'mode',
|
|
bindings: plans.map((plan, i) => ({ plan, digest: digest(plan), decision: decision.id, choice: options[i].key })) } });
|
|
services.record?.(identity, 'request.propose', result); return result;
|
|
});
|
|
});
|
|
}
|
|
// Runs the confirmed bootstrap plan through the host executor. The executor re-verifies the bound
|
|
// organization revision and association before every effect (#800). A plan found stale before any effect reverts
|
|
// to selection so the owner gets a fresh preview; one found stale after an effect waits with its evidence kept.
|
|
// Anything else waits as uncertain until recovery drives it again.
|
|
async function runBootstrap(state) {
|
|
if (!state.plan_digest) return state;
|
|
const binding = state.selection?.bindings.find(b => b.digest === state.plan_digest);
|
|
if (!binding) return state;
|
|
const executing = binding.plan.existing
|
|
? services.attachExisting && state.phase === 'discovery' && !state.attachment?.completed
|
|
: services.bootstrap && state.phase === 'bootstrap';
|
|
if (!executing) return state;
|
|
try { active(state, binding.plan.project, binding.plan.source?.project, binding.plan.chat_project); }
|
|
catch (e) { if (e.code !== 'project-archived') throw e; return wait(state, e.code); }
|
|
if (binding.plan.existing) {
|
|
const execute = async () => {
|
|
const missing = await admission(binding.plan, state); if (missing) return wait(state, missing);
|
|
active(state, binding.plan.project);
|
|
const outcome = await services.attachExisting(state, binding.plan);
|
|
return journal.transaction(tx => {
|
|
const now = stateOf(state.business, state.request);
|
|
active(now, binding.plan.project);
|
|
if (now.revision !== state.revision) refuse('request-revision-conflict');
|
|
const header = { version: 1, business: state.business, request: state.request, op: `bootstrap:${binding.digest}:attach`, kind: 'bootstrap', digest: binding.digest };
|
|
journal.prepareEffect({ ...header, stage: 'prepared', result: null, code: null });
|
|
journal.finishEffect({ ...header, stage: 'committed', result: { project: state.project, ...outcome }, code: null });
|
|
return append(now, 'bootstrap.completed', { digest: binding.digest, project: state.project, chat_project: state.chat_project,
|
|
organization_revision: binding.plan.organization_revision, ...outcome }, null, tx.appendRequest);
|
|
});
|
|
};
|
|
try { return await (services.withExisting ? services.withExisting(state, execute) : execute()); }
|
|
catch (e) { return wait(stateOf(state.business, state.request), e.code ?? 'request-attachment-unavailable'); }
|
|
}
|
|
let done;
|
|
try { done = await services.bootstrap({ binding: structuredClone(binding), state: structuredClone(state) }); }
|
|
catch (e) {
|
|
if (e?.code === 'project-archived') return wait(state, e.code);
|
|
if (e?.code === 'request-plan-stale') {
|
|
// Before any effect the plan is only stale and the owner gets a fresh preview. Once an effect has a committed receipt
|
|
// (#800 is checked before every effect, not only the first), what is done stays where it is and the request waits, so no
|
|
// later effect runs on a world the owner never confirmed and no fresh preview meets half-built paths.
|
|
const begun = journal.effects(state.business, state.request).some(r => r.kind === 'bootstrap' && r.digest === binding.digest && r.stage === 'committed');
|
|
return begun ? wait(state, 'request-plan-stale') : append(state, 'bootstrap.stale', { digest: binding.digest, code: 'request-plan-stale' });
|
|
}
|
|
return wait(state, 'bootstrap-uncertain');
|
|
}
|
|
return append(state, 'bootstrap.completed', { digest: binding.digest, project: done.project, chat_project: done.chat_project,
|
|
spec_commit: done.spec_commit, organization_revision: done.organization_revision });
|
|
}
|
|
async function submit(identity, args) {
|
|
exact(args, ['request','revision','op','prd_version','records_commit','prd_path','requirement_ids']);
|
|
if (!id(args.request) || !id(args.op) || !Number.isSafeInteger(args.revision) || args.revision < 1) refuse('invalid-request');
|
|
return serial(identity.business, args.request, async () => {
|
|
let state = stateOf(identity.business, args.request); authorize(identity, state, 'prd.submit');
|
|
const proposal_digest = digest(args), old = journal.proposal(state.business, state.request, args.op);
|
|
if (old) {
|
|
if (old.proposal_digest !== proposal_digest) refuse('request-operation-conflict');
|
|
if (!old.candidate) return state;
|
|
return { candidate: old.candidate, decision: services.prdDecision(state.business, old.decision) };
|
|
}
|
|
if (state.revision !== args.revision) refuse('request-revision-conflict');
|
|
if (!['discovery','prd-review','planning'].includes(state.phase) || state.wait?.code === 'prd-approval') refuse('request-phase-refused');
|
|
active(state);
|
|
const { revision, op, ...input } = args;
|
|
const material = await services.readCandidate({ ...input, project: state.project, mode_revision: state.mode_revision }, state.business);
|
|
const recheck = () => {
|
|
const now = stateOf(state.business, state.request); authorize(identity, now, 'prd.submit');
|
|
active(now);
|
|
if (now.revision !== args.revision) refuse('request-revision-conflict');
|
|
if (journal.projectState(state.business, state.project)?.revision !== state.mode_revision) refuse('prd-admission-revoked');
|
|
return now;
|
|
};
|
|
return journal.transaction(tx => {
|
|
state = recheck();
|
|
let route;
|
|
try { route = services.prdAuthority(state, { authors: material.authors }); }
|
|
catch (e) { if (!['prd-arbiter-unavailable','prd-self-approval'].includes(e.code)) throw e; return wait(state, e.code, identity, {}, tx.appendRequest); }
|
|
const candidate = material.candidate;
|
|
const decision = services.raisePrdDecision(identity, { action: 'prd.approve', domain: 'technical', project: state.project,
|
|
target: `prd-${digest(candidate)}`, question: `Approve product PRD ${candidate.prd_version} for ${state.project}, exact candidate ${digest(candidate)} at ${candidate.records_commit}?`,
|
|
options: [{ key: 'yes', text: 'Approve this exact product PRD version' }, { key: 'no', text: 'Request changes' }], recommendation: 'yes', approvalChoice: 'yes', blocking: false,
|
|
...(state.mode === 'autonomous' ? { spec_path: 'spec/north-star.md', spec_commit: candidate.spec_commit } : {}) },
|
|
state.mode === 'autonomous' ? { path: 'spec/north-star.md', commit: candidate.spec_commit } : null);
|
|
const header = { version: 1, business: state.business, request: state.request, op, kind: 'prd-submit', digest: proposal_digest };
|
|
journal.prepareEffect({ ...header, stage: 'prepared', result: null, code: null });
|
|
// A replacement retires existing admissions without changing their immutable evidence.
|
|
if (state.snapshot) services.catalog.invalidate(state.business, state.project, 'prd-replaced');
|
|
state = stateOf(state.business, state.request);
|
|
append(state, 'prd.submitted', { candidate, decision: decision.id, op, proposal_digest, authors: material.authors, route }, identity, tx.appendRequest);
|
|
journal.finishEffect({ ...header, stage: 'committed', result: { decision: decision.id }, code: null });
|
|
services.recordPrd?.(identity, state.project, decision.id);
|
|
return { candidate, decision };
|
|
});
|
|
});
|
|
}
|
|
async function modeConsole(identity, args) {
|
|
exact(args, ['request','revision','mode_revision','mode','op']);
|
|
if (!id(args.request) || !id(args.op) || !Number.isSafeInteger(args.revision) || !Number.isSafeInteger(args.mode_revision) || !['guided','autonomous'].includes(args.mode)) refuse('invalid-request');
|
|
return serial(identity.business, args.request, () => journal.transaction(() => {
|
|
let state = stateOf(identity.business, args.request); authorize(identity, state, 'mode');
|
|
const proposal_digest = digest(args), old = journal.proposal(state.business, state.request, args.op);
|
|
if (old) { if (old.proposal_digest !== proposal_digest) refuse('request-operation-conflict'); return state; }
|
|
if (state.revision !== args.revision) refuse('request-revision-conflict');
|
|
if (['cancelled','delivered','complete'].includes(state.phase)) refuse('request-phase-refused');
|
|
if (!state.project || args.mode_revision !== state.mode_revision) refuse('request-mode-revision-conflict');
|
|
const mode_revision = journal.changeMode({ business: state.business, project: state.project, revision: args.mode_revision, mode: args.mode, op: args.op, request: args.request });
|
|
services.catalog.invalidate(state.business, state.project, 'request-mode-changed');
|
|
for (const row of journal.listRequests()) {
|
|
if (row.business !== state.business) continue;
|
|
const attached = stateOf(row.business, row.request);
|
|
if (attached.project === state.project && !['cancelled','delivered','complete'].includes(attached.phase)) append(attached, 'mode.changed', { mode: args.mode, mode_revision, op: args.op, proposal_digest });
|
|
}
|
|
return stateOf(state.business, state.request);
|
|
}));
|
|
}
|
|
async function settle(business, request) {
|
|
const state = stateOf(business, request);
|
|
if (state.wait?.code === 'prd-approval') {
|
|
try { await services.catalog.activate({ request, decision: state.wait.subject }); return stateOf(business, request); }
|
|
catch (e) {
|
|
if (e.code === 'prd-not-approved') return state;
|
|
return append(stateOf(business, request), 'prd.invalidated', { code: e.code ?? 'prd-activation-failed' });
|
|
}
|
|
}
|
|
if (state.wait?.kind !== 'decision') return runBootstrap(state);
|
|
const close = services.readDecision(business, state.selection.decision);
|
|
if (!close || close.op === 'seen') return state;
|
|
if (close.op === 'withdrawn' || close.op === 'expired') return append(state, 'cancelled', { decision: state.selection.decision });
|
|
if (close.op !== 'resolved' || close.by !== state.owner || !['cli','console'].includes(close.via)) refuse('request-selection-refused');
|
|
if (close.choice === 'existing' || close.choice === 'back') return append(state, 'selection.staged', { decision: state.selection.decision, choice: close.choice });
|
|
const binding = state.selection.bindings.find(b => b.choice === close.choice);
|
|
if (!binding) refuse('request-selection-refused');
|
|
const p = binding.plan;
|
|
try { active(state, p.project, p.source.project, p.chat_project); }
|
|
catch (e) { return wait(state, e.code); }
|
|
const planArgs = { project: p.project, name: p.name, source_project: p.source.project, tracker_project: p.tracker.project };
|
|
const planSource = { text: p.intent.text, source_message: state.source_message };
|
|
const inventory = async () => p.existing ? await services.listProjects?.(structuredClone(state)) ?? [] : null;
|
|
// Check before asking admission, so a plan that is already stale never reaches it.
|
|
const early = staleCode(p, state, planArgs, planSource, await inventory());
|
|
if (early) return wait(state, early);
|
|
const missing = await admission(p, state);
|
|
if (missing) return wait(state, missing);
|
|
// Admission is the last slow call. Read the association once more and confirm only if it still
|
|
// matches, in the same synchronous step as the append.
|
|
const rows = await inventory();
|
|
const confirmed = journal.transaction(tx => {
|
|
const late = staleCode(p, state, planArgs, planSource, rows);
|
|
if (late) return wait(state, late, null, {}, tx.appendRequest);
|
|
return append(state, 'selection.confirmed', { decision: binding.decision, choice: binding.choice, digest: binding.digest }, null, tx.appendRequest);
|
|
});
|
|
return runBootstrap(confirmed);
|
|
}
|
|
async function resume(business, request) {
|
|
return serial(business, request, async () => {
|
|
for (;;) {
|
|
const state = await settle(business, request);
|
|
const quote = await quoteFor(state);
|
|
// Resolving the catalog can revoke approval and append prd.invalidated. Never
|
|
// dispatch the pre-lookup state: discard its quote and re-settle current bindings.
|
|
const current = stateOf(business, request);
|
|
if (current.revision !== state.revision || current.phase !== state.phase || current.snapshot !== state.snapshot) continue;
|
|
// No await between this journal read and the synchronous continuation writes.
|
|
continuations.resume(current, quote);
|
|
return stateOf(business, request);
|
|
}
|
|
});
|
|
}
|
|
// D3 (#797): implementation/review continuations quote the task-cited approved requirement texts.
|
|
// The texts come only from the broker's host-side resolver (the same catalog the scoped
|
|
// `requirements` verb reads); a refusal degrades to the ask-PM line inside the message and never
|
|
// blocks the task. Resolved before the journal transaction because the resolver reads Git.
|
|
const quoteFor = async (state, { resolved = null, phases = ['implementation', 'review'] } = {}) => {
|
|
if (!services.continuationQuote || !state?.snapshot || !phases.includes(state.phase)) return null;
|
|
try { return await services.continuationQuote(state, resolved); } catch { return { unavailable: true }; }
|
|
};
|
|
// The Task 3 verbs share one shape: validate, authorize, replay a recorded op, then check revision and phase in
|
|
// that order, so a lost response can be retried and a stale client always learns the revision moved.
|
|
const need = name => typeof services[name] === 'function' ? services[name] : refuse('request-services-unavailable');
|
|
const replay = (state, op, proposal_digest) => {
|
|
const old = journal.proposal(state.business, state.request, op);
|
|
if (old && old.proposal_digest !== proposal_digest) refuse('request-operation-conflict');
|
|
return old !== null;
|
|
};
|
|
const ended = state => { if (['cancelled', 'delivered', 'complete'].includes(state.phase)) refuse('request-phase-refused'); };
|
|
// The PM's one outstanding question. It is a journal event, not a decision: an answer is text and approves nothing.
|
|
async function question(identity, args) {
|
|
exact(args, ['request','revision','op','text'], ['options']);
|
|
if (!id(args.request) || !positive(args.revision) || !id(args.op) || !text(args.text, 2000) || ('options' in args && !optionList(args.options))) refuse('invalid-request');
|
|
return serial(identity.business, args.request, () => {
|
|
const state = stateOf(identity.business, args.request); authorize(identity, state, 'question');
|
|
const proposal_digest = digest(args);
|
|
if (replay(state, args.op, proposal_digest)) return state;
|
|
if (state.revision !== args.revision) refuse('request-revision-conflict');
|
|
if (!QUESTION_PHASES.includes(state.phase) || state.wait?.kind === 'decision') refuse('request-phase-refused');
|
|
if (state.question && state.question.answer === null) refuse('request-question-open');
|
|
return journal.transaction(tx => {
|
|
const result = append(state, 'question.asked', { op: args.op, proposal_digest, id: 'q-' + proposal_digest.slice(0, 16), text: args.text,
|
|
options: structuredClone(args.options ?? []) }, identity, tx.appendRequest);
|
|
services.record?.(identity, 'request.question', result); return result;
|
|
});
|
|
});
|
|
}
|
|
async function answer(identity, args) {
|
|
exact(args, ['request','revision','question','op','text']);
|
|
if (!id(args.request) || !positive(args.revision) || !id(args.question) || !id(args.op) || !text(args.text, 8000)) refuse('invalid-request');
|
|
return serial(identity.business, args.request, () => {
|
|
const state = stateOf(identity.business, args.request); authorize(identity, state, 'answer');
|
|
const proposal_digest = digest(args);
|
|
if (replay(state, args.op, proposal_digest)) return state;
|
|
if (state.revision !== args.revision) refuse('request-revision-conflict');
|
|
ended(state);
|
|
if (!state.question || state.question.answer !== null) refuse('request-question-closed');
|
|
if (state.question.id !== args.question) refuse('request-question-mismatch');
|
|
// The event, the message to the PM and the journal row commit together, or none does.
|
|
return journal.transaction(tx => {
|
|
const event = need('recordAnswer')(identity, structuredClone(state), { question: args.question, op: args.op, text: args.text });
|
|
return append(state, 'question.answered', { op: args.op, proposal_digest, question: args.question, answer: event }, identity, tx.appendRequest);
|
|
});
|
|
});
|
|
}
|
|
// The owner's pick of one project the picker offers. The pick is evidence and a wait; the PM still proposes it and the
|
|
// owner still confirms the decision that proposal raises, so nothing is attached here.
|
|
async function attach(identity, args) {
|
|
exact(args, ['request','revision','project','op']);
|
|
if (!id(args.request) || !positive(args.revision) || !key(args.project) || !id(args.op)) refuse('invalid-request');
|
|
return serial(identity.business, args.request, async () => {
|
|
const state = stateOf(identity.business, args.request); authorize(identity, state, 'attach');
|
|
const proposal_digest = digest(args);
|
|
if (replay(state, args.op, proposal_digest)) return state;
|
|
if (state.revision !== args.revision) refuse('request-revision-conflict');
|
|
if (state.phase !== 'selection' || state.route !== 'existing' || state.wait?.kind !== 'setup' || !PICKER_CODES.includes(state.wait.code)) refuse('request-phase-refused');
|
|
active(state, args.project);
|
|
// The inventory is asynchronous; the transaction below rereads the journal and the check is repeated there.
|
|
const picked = await services.pickExisting?.(structuredClone(state), args.project, identity);
|
|
const rows = await projects(identity, { request: args.request }, false);
|
|
active(state, args.project);
|
|
if (!rows.some(p => p.project === args.project)) refuse('request-project-refused');
|
|
return journal.transaction(tx => {
|
|
const current = tx.readRequest(state.business, state.request) ?? refuse('request-not-found');
|
|
authorize(identity, current, 'attach');
|
|
active(current, args.project);
|
|
if (current.revision !== args.revision) refuse('request-revision-conflict');
|
|
need('recordAttach')(identity, structuredClone(current), { project: args.project, op: args.op });
|
|
return append(current, 'attach.selected', { op: args.op, proposal_digest, project: args.project, ...(picked ? { mapping_revision: picked.mapping_revision } : {}) }, identity, tx.appendRequest);
|
|
});
|
|
});
|
|
}
|
|
// Withdraws the open selection decision, if any, and appends the cancellation. A project, mapping or receipt that
|
|
// already exists stays as evidence; nothing is deleted. A bootstrap in flight holds this request's queue, so a
|
|
// cancel waits for it to finish instead of racing it.
|
|
async function cancel(identity, args) {
|
|
exact(args, ['request','revision','op']);
|
|
if (!id(args.request) || !positive(args.revision) || !id(args.op)) refuse('invalid-request');
|
|
return serial(identity.business, args.request, () => {
|
|
const state = stateOf(identity.business, args.request); authorize(identity, state, 'cancel');
|
|
const proposal_digest = digest(args);
|
|
if (replay(state, args.op, proposal_digest)) return state;
|
|
if (state.revision !== args.revision) refuse('request-revision-conflict');
|
|
ended(state);
|
|
const decision = state.wait?.kind === 'decision' ? state.wait.subject : null;
|
|
return journal.transaction(tx => {
|
|
if (decision !== null) need('withdrawDecision')(identity, structuredClone(state), decision);
|
|
need('recordCancel')(identity, structuredClone(state), { op: args.op, decision });
|
|
return append(state, 'cancelled', { decision, op: args.op, proposal_digest }, identity, tx.appendRequest);
|
|
});
|
|
});
|
|
}
|
|
async function advance(identity, args) {
|
|
exact(args, ['request','revision','op']);
|
|
if (!id(args.request) || !id(args.op) || !Number.isSafeInteger(args.revision) || args.revision < 1) refuse('invalid-request');
|
|
return serial(identity.business, args.request, async () => {
|
|
let state = stateOf(identity.business, args.request); authorize(identity, state, 'advance');
|
|
const proposal_digest = digest(args), old = journal.proposal(state.business, state.request, args.op);
|
|
if (old) { if (old.proposal_digest !== proposal_digest) refuse('request-operation-conflict'); return state; }
|
|
if (state.revision !== args.revision) refuse('request-revision-conflict');
|
|
if (state.phase === 'delivery') { services.progress(state); refuse('request-delivery-required'); }
|
|
if (!state.snapshot || !services.progress) refuse('request-evidence-required');
|
|
const resolved = await services.catalog.resolve({ business: state.business, project: state.project, snapshot: state.snapshot });
|
|
// The post-advance coder/review continuation quotes the approved texts; resolve it here (Git
|
|
// reads) and hand it into the transaction-built message. planning→implementation and
|
|
// implementation→review dispatch those steps, and a review phase can loop back to
|
|
// implementation on a changes verdict, so every advance out of those three phases resolves.
|
|
// The pre-append state carries the same product, snapshot and task citations as the next one.
|
|
const quote = await quoteFor(state, { resolved, phases: ['planning', 'implementation', 'review'] });
|
|
return journal.transaction(tx => {
|
|
state = stateOf(state.business, state.request); authorize(identity, state, 'advance');
|
|
if (state.revision !== args.revision) refuse('request-revision-conflict');
|
|
const progress = services.progress(state);
|
|
const result = append(state, 'advanced', { op: args.op, proposal_digest, from: state.phase, ...progress }, identity, tx.appendRequest);
|
|
services.record?.(identity, 'request.advance', result);
|
|
continuations.resume(result, quote);
|
|
return result;
|
|
});
|
|
});
|
|
}
|
|
async function deliver(identity, args) {
|
|
exact(args, ['request','revision','op','task_ref','verdict','path','verification_record']);
|
|
exact(args.verification_record, ['path','commit']);
|
|
if (!id(args.request) || !id(args.op) || !id(args.verdict) || !text(args.task_ref, 160) || !text(args.path, 4096) ||
|
|
!text(args.verification_record.path, 256) || !/^[a-f0-9]{40}$/.test(args.verification_record.commit) || !Number.isSafeInteger(args.revision) || args.revision < 1) refuse('invalid-request');
|
|
return serial(identity.business, args.request, async () => {
|
|
let state = stateOf(identity.business, args.request); authorize(identity, state, 'deliver');
|
|
const proposal = digest(args), old = journal.effects(state.business, state.request).filter(e => e.kind === 'delivery');
|
|
const committed = old.find(e => e.stage === 'committed');
|
|
if (committed) {
|
|
if (committed.op === args.op && committed.digest !== proposal) refuse('request-operation-conflict');
|
|
const d = committed.result;
|
|
if (d.task_ref !== args.task_ref || d.verdict !== args.verdict || d.artifact.path !== args.path || d.verification.record_path !== args.verification_record.path || d.verification.record_commit !== args.verification_record.commit) refuse('request-operation-conflict');
|
|
return d;
|
|
}
|
|
if (state.revision !== args.revision) refuse('request-revision-conflict');
|
|
if (state.phase !== 'delivery') refuse('request-phase-refused');
|
|
const header = { version: 1, business: state.business, request: state.request, op: args.op, kind: 'delivery', digest: proposal };
|
|
journal.prepareEffect({ ...header, stage: 'prepared', result: null, code: null });
|
|
const evidence = services.deliveryEvidence(state, args);
|
|
const [verification, artifact] = await Promise.all([services.readVerification(state, args.verification_record), services.readReviewedArtifact(state, evidence.commit, args.path)]);
|
|
let record; try { record = JSON.parse(verification.content); } catch { refuse('request-verification-refused'); }
|
|
exact(record, ['version','task_ref','review_request','commit','results'], [], 'request-verification-refused');
|
|
if (verification.commit !== args.verification_record.commit || record.version !== 1 || record.task_ref !== args.task_ref || record.review_request !== evidence.review_request || record.commit !== evidence.commit || record.results !== evidence.results || !text(record.results)) refuse('request-verification-refused');
|
|
if (artifact.mime !== 'text/html') refuse('artifact-type-refused');
|
|
await services.catalog.resolve({ business: state.business, project: state.project, snapshot: state.snapshot });
|
|
const filename = basename(args.path);
|
|
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(filename)) refuse('artifact-path-invalid');
|
|
return journal.transaction(tx => {
|
|
state = stateOf(state.business, state.request); authorize(identity, state, 'deliver');
|
|
if (state.revision !== args.revision || state.phase !== 'delivery') refuse('request-revision-conflict');
|
|
const again = services.deliveryEvidence(state, args);
|
|
if (digest(again) !== digest(evidence)) refuse('request-evidence-required');
|
|
const value = { version: 1, id: randomUUID(), business: state.business, request: state.request, project: state.project, snapshot: state.snapshot,
|
|
task_ref: args.task_ref, commit: evidence.commit, review_request: evidence.review_request, verdict: evidence.verdict,
|
|
artifact: { path: args.path, blob: artifact.blob, sha256: artifact.sha256, bytes: artifact.bytes.length, mime: artifact.mime },
|
|
verification: { record_path: args.verification_record.path, record_commit: args.verification_record.commit }, message: null };
|
|
const result = append(state, 'advanced', { op: args.op, proposal_digest: proposal, from: 'delivery', phase: 'complete', tasks: state.tasks, evidence: evidence.evidence }, identity, tx.appendRequest);
|
|
continuations.resume({ ...result, delivery: value.id, delivery_evidence: value });
|
|
const notice = journal.effects(state.business, state.request).find(e => e.kind === 'continuation' && e.stage === 'uncertain' && e.result?.intent?.phase === 'complete' && e.result.intent.revision === result.revision && e.result.intent.step === 'send_message');
|
|
if (!notice?.result?.message) refuse('request-notification-unavailable');
|
|
value.message = notice.result.message;
|
|
services.record?.(identity, 'request.deliver', result);
|
|
journal.finishEffect({ ...header, stage: 'committed', result: value, code: null });
|
|
return value;
|
|
});
|
|
});
|
|
}
|
|
async function artifactConsole(identity, args) {
|
|
exact(args, ['request','delivery']);
|
|
if (!id(args.request) || !id(args.delivery)) refuse('invalid-request');
|
|
const state = stateOf(identity.business, args.request); authorize(identity, state, 'artifactConsole');
|
|
const d = state.delivery_evidence;
|
|
if (!d || d.id !== args.delivery) refuse('request-not-found');
|
|
const artifact = await services.readReviewedArtifact(state, d.commit, d.artifact.path);
|
|
const current = stateOf(identity.business, args.request); authorize(identity, current, 'artifactConsole');
|
|
if (current.delivery !== d.id || artifact.sha256 !== d.artifact.sha256 || artifact.blob !== d.artifact.blob || artifact.bytes.length !== d.artifact.bytes) refuse('request-evidence-required');
|
|
return { mime: d.artifact.mime, filename: basename(d.artifact.path), base64: artifact.bytes.toString('base64'), sha256: artifact.sha256 };
|
|
}
|
|
return Object.freeze({ open, get, projects, propose, submit, question, answer, attach, cancel, advance, deliver, artifactConsole, modeConsole,
|
|
reviewScope: (business, request, task, project, snapshot, coder, reviewer) => {
|
|
if (typeof request !== 'string') return false;
|
|
const row = journal.listRequests().find(r => r.business === business && r.request === request);
|
|
if (!row) return false;
|
|
const state = journal.readRequest(business, request);
|
|
const staff = state.selection?.bindings.find(b => b.digest === state.plan_digest)?.plan.staff;
|
|
return ['planning', 'implementation', 'review', 'delivery'].includes(state.phase) && state.project === project &&
|
|
state.snapshot === snapshot && !!snapshot && staff?.coder === coder && staff?.reviewer === reviewer &&
|
|
(state.phase === 'planning' || state.tasks.includes(task));
|
|
},
|
|
hasWork: () => journal.listRequests().length > 0, launches: continuations.launches, launchResult: continuations.launchResult, manifestNeeded: continuations.manifestNeeded,
|
|
draftConsole: async (identity, args) => {
|
|
exact(args, ['request']); if (!id(args.request)) refuse('invalid-request');
|
|
const state = stateOf(identity.business, args.request); authorize(identity, state, 'draft');
|
|
const material = state.candidate ? await services.readCandidate(state.candidate, state.business)
|
|
: { candidate: null, prd: null, requirements: [] };
|
|
const current = stateOf(state.business, state.request); authorize(identity, current, 'draft');
|
|
if (current.revision !== state.revision) refuse('request-revision-conflict');
|
|
const revision = current.project ? journal.snapshotEvents(current.business, current.project).at(-1)?.revision ?? 0 : 0;
|
|
return { candidate: material.candidate, prd: material.prd, requirements: material.requirements,
|
|
snapshot: { id: current.snapshot, revision } };
|
|
}, resume, catalog: services.catalog,
|
|
decisionClosed: (business, decision) => {
|
|
if (closing) return Promise.resolve();
|
|
for (const row of journal.listRequests()) if (row.business === business && journal.readRequest(business, row.request).wait?.subject === decision)
|
|
return resume(business, row.request);
|
|
},
|
|
close: async () => { closing = true; await recovery; await Promise.allSettled([...pending.values()]); await services.catalog?.drain(); },
|
|
recover: ({ limit = Infinity } = {}) => {
|
|
if (closing) return Promise.resolve([]);
|
|
// An overlapping event may concern any already-inspected request. Keep a
|
|
// full reinspection cycle pending, using the same per-batch limit.
|
|
if (recovery) { recoveryAgain = true; return recovery; }
|
|
recovery = (async () => {
|
|
const states = [];
|
|
let remaining = Math.min(journal.listRequests().length, limit);
|
|
do {
|
|
recoveryAgain = false;
|
|
const rows = journal.listRequests();
|
|
const count = Math.min(rows.length, limit, remaining), start = cursor % (rows.length || 1);
|
|
for (let n = 0; n < count; n++) {
|
|
if (closing) break;
|
|
const { business, request } = rows[(start + n) % rows.length];
|
|
states.push(await resume(business, request));
|
|
}
|
|
cursor = (start + count) % (rows.length || 1);
|
|
remaining = recoveryAgain ? journal.listRequests().length : Math.max(0, remaining - count);
|
|
if (count === 0) break;
|
|
} while (remaining > 0 && !closing);
|
|
return states;
|
|
})().finally(() => { recovery = null; });
|
|
return recovery;
|
|
} });
|
|
}
|