// Shared integration code copied into each standalone example. The SDK owns // workflow history, input admission and assessment; this module owns the small // operating record around it. It never books freight or performs production. import { commitment, hashing, WORKFLOW_ANSWER_STATUS, WORKFLOW_REVIEW_STATUS, WORKFLOW_STEP_STATUS } from '@decision-lab/sdk'; export const JOURNEY_OPERATION = Object.freeze({ DECISION: 'decision', AUTHORIZATION: 'authorization', RESERVATION: 'reservation', DELIVERY: 'delivery', CORRECTION: 'correction', REHEARSAL: 'rehearsal', HANDOFF: 'handoff', ESCALATION: 'escalation', }); const INPUTS = 'inputs', CONTEXT = 'journey-context', OPERATIONS = 'journey-operations'; const atTime = at => at ?? new Date().toISOString(); const equal = (a, b) => a === undefined || b === undefined ? a === b : hashing.canonicalHash(a) === hashing.canonicalHash(b); const requireValue = (condition, message, code = 'REVIEW_JOURNEY_INVALID') => { if (!condition) throw Object.assign(new Error(message), { code }); }; const named = value => typeof value === 'string' && value.trim().length > 0; const settings = run => run.definition.metadata.reviewJourney; export const isCalculationJourney = run => run.definition.execution?.mode === 'calculation'; const resultIsCurrent = (run, state) => isCalculationJourney(run) ? state.status === WORKFLOW_STEP_STATUS.COMPLETE : [WORKFLOW_STEP_STATUS.ACCEPTED, WORKFLOW_STEP_STATUS.AWAITING_REVIEW].includes(state.status); const choiceIsReady = (run, state) => isCalculationJourney(run) ? state.status === WORKFLOW_STEP_STATUS.COMPLETE : state.status === WORKFLOW_STEP_STATUS.ACCEPTED; const readPath = (value, path) => path.split('.').reduce((current, key) => current?.[key], value); function defaultDefinition(lab, app) { return lab.workflows.create({ id: `${app.app.id}-operating-review`, version: '1.0.0', title: app.app.name, question: 'Which response is supported, and what must happen next?', description: 'Continue one reviewed case from screening through a recorded operating handoff.', dependencies: [{ id: 'planner', app, packageHash: app.contentHash }], questions: [{ id: INPUTS, path: 'inputs', label: 'Current case records', question: 'Do these records describe the current commitment and available responses?', meaning: 'Review the imported facts, their original scope and assessment time before using a finding.', role: 'case-owner', type: 'object', required: true }], steps: [{ id: 'planning', title: 'Review complete responses', app: 'planner', role: 'case-owner', requires: [INPUTS], dependsOn: [], input: { ref: 'case.inputs' }, output: { finding: { ref: 'assessment.finding' }, recommendation: { ref: 'assessment.recommendation' } }, acceptWhen: { op: 'eq', args: [{ ref: 'assessment.status' }, 'complete'] } }], brief: { sections: [{ id: 'finding', title: 'Reviewed response', value: { ref: 'steps.planning.output' } }], actions: [], completion: { op: 'eq', args: [{ ref: 'steps.planning.status' }, 'accepted'] } }, }); } /** Add application records outside the questions that determine plan feasibility. * A booking receipt must not cause the planner to reserve the same shipment again. * Domain authors may reference these records in a separate release/closure gate. */ function withOperatingRecords(lab, definition, planningStepId, caseIdPath) { const source = structuredClone(lab.workflows.open(definition)); delete source.contentHash; if (!source.metadata?.reviewJourney) source.id += '-journey'; source.metadata = { ...source.metadata, reviewJourney: { ...source.metadata?.reviewJourney, version: 1, planningStepId, caseIdPath: caseIdPath ?? source.metadata?.reviewJourney?.caseIdPath ?? 'inputs.id', } }; if (source.metadata.caseSchema?.type === 'object') { source.metadata.caseSchema.properties = { ...source.metadata.caseSchema.properties, journeyContext: { type: 'object' }, journeyOperations: { type: 'array', items: { type: 'object' } } }; } const additions = [ { id: CONTEXT, path: 'journeyContext', label: 'Screening and source basis', question: 'Who owns this review and where did its records come from?', meaning: 'Imported source receipts and provisional screening are retained for inspection, not accepted findings.', role: 'case-owner', type: 'object' }, { id: OPERATIONS, path: 'journeyOperations', label: 'Operating records', question: 'What decision or actual operating record has been supplied?', meaning: 'Record a selection, external authority or actual event separately from accepting an analytical finding. A recorded assertion does not authenticate its source.', role: 'case-owner', type: 'array' }, ]; for (const question of additions) { const existing = source.questions.find(row => row.id === question.id || row.path === question.path); requireValue(!existing || existing.id === question.id && existing.path === question.path && existing.type === question.type, `The workflow conflicts with the reserved ${question.id} record.`); if (!existing) source.questions.push(question); } requireValue(source.steps.some(step => step.id === planningStepId), 'The planning step is missing.'); return lab.workflows.create(source); } export function createReviewJourney({ lab, app, inputs, owner, sources = [], screeningRun = null, previousRun = null, createdAt, definition, case: sharedCase, planningStepId = 'planning', caseIdPath, runId }) { requireValue(named(owner), 'Name the person responsible for this case.'); const openedApp = app ? lab.apps.open(app) : null; const authored = definition ?? defaultDefinition(lab, openedApp); const extended = withOperatingRecords(lab, authored, planningStepId, caseIdPath); for (const record of [screeningRun, previousRun].filter(Boolean)) requireValue(lab.runs.validate(record).valid, 'The screening run is invalid.'); const { journeyContext: ignoredContext, journeyOperations: ignoredOperations, ...originalCase } = sharedCase ?? { inputs }; const currentCase = { ...originalCase, journeyContext: { owner, sources, screeningRun, previousRun, originalCase }, journeyOperations: [] }; const run = lab.workflows.start({ definition: extended, case: currentCase, ...(createdAt ? { createdAt } : {}), ...(runId ? { runId } : {}) }); return openReviewJourney({ lab, value: run, ...(openedApp ? { app: openedApp } : {}) }); } export function openReviewJourney({ lab, value, app, definition, compatibleDefinitions = [] }) { const run = lab.workflows.openRun(value); requireValue(run.definition.metadata?.reviewJourney?.version === 1, 'Open a continuing operating review.'); const config = settings(run), step = run.definition.steps.find(row => row.id === config.planningStepId); requireValue(step && run.answers[CONTEXT] && run.answers[OPERATIONS], 'The review is missing its operating records.'); requireValue(named(config.caseIdPath), 'Declare the path identifying the business case.'); if (definition) { const allowed = [definition, ...compatibleDefinitions].map(value => { const authored = lab.workflows.open(value); return withOperatingRecords(lab, authored, authored.metadata?.reviewJourney?.planningStepId ?? 'planning', authored.metadata?.reviewJourney?.caseIdPath ?? 'inputs.id').contentHash; }); requireValue(allowed.includes(run.definition.contentHash), 'This review uses a different authored workflow.', 'REVIEW_DEFINITION_MISMATCH'); } const caseId = readPath(run.history[0].case, config.caseIdPath); const identityUnavailable = entry => run.definition.questions.some(question => (config.caseIdPath === question.path || config.caseIdPath.startsWith(`${question.path}.`)) && [WORKFLOW_ANSWER_STATUS.UNKNOWN, WORKFLOW_ANSWER_STATUS.UNANSWERED].includes(entry.answers[question.id]?.status)); requireValue(named(caseId) && run.history.every(entry => readPath(entry.case, config.caseIdPath) === caseId || readPath(entry.case, config.caseIdPath) == null && identityUnavailable(entry)), 'A different business case needs its own review; keep the case identity throughout its history.', 'REVIEW_CASE_MISMATCH'); const { journeyContext: firstContext, journeyOperations: firstOperations, ...originalCase } = run.history[0].case; requireValue(run.history.every(entry => equal(entry.case.journeyContext.originalCase, originalCase)), 'Preserve the original case commitment separately from later revisions.', 'REVIEW_ORIGINAL_CASE_MISMATCH'); if (app) { const opened = lab.apps.open(app), dependency = run.definition.dependencies.find(row => row.id === step.app); requireValue(dependency.packageHash === opened.contentHash, 'This review belongs to a different app release.', 'REVIEW_APP_MISMATCH'); } for (const screening of [run.case.journeyContext.screeningRun, run.case.journeyContext.previousRun].filter(Boolean)) { requireValue(lab.runs.validate(screening).valid, 'The retained screening run is invalid.'); const dependency = run.definition.dependencies.find(row => row.id === step.app); requireValue(screening.identity.packageHash === dependency.packageHash, 'The screening used different planning rules.'); requireValue(screening.input.model.case.id === caseId, 'The retained calculation belongs to a different business case.', 'REVIEW_CASE_MISMATCH'); } const firstInputs = run.history[0].case.inputs; if (firstInputs && run.case.journeyContext.screeningRun) requireValue(equal(firstInputs, run.case.journeyContext.screeningRun.input.model.case), 'The screening must describe the exact imported inputs at the beginning of this review.', 'REVIEW_SCREENING_MISMATCH'); return run; } /** Applied imports change only the supplied values. Equal data retains current * findings; changed data stales dependents. Historical reviewed runs still await * their original explicit input review. */ export function updateReviewInputs({ lab, run, inputs, values, at }) { let next = openReviewJourney({ lab, value: run }); const updates = values ?? { [INPUTS]: inputs }; for (const [questionId, value] of Object.entries(updates)) { requireValue(![CONTEXT, OPERATIONS].includes(questionId), 'Use the operating record methods for this question.'); requireValue(next.answers[questionId], `Unknown question ${questionId}.`); if (!equal(next.answers[questionId].value, value)) next = lab.workflows.answer({ run: next, questionId, value, status: isCalculationJourney(next) ? WORKFLOW_ANSWER_STATUS.SUPPLIED : WORKFLOW_ANSWER_STATUS.AWAITING_REVIEW, at: atTime(at) }); } return openReviewJourney({ lab, value: next }); } /** Call only from an explicit input-review action, never automatically on import. */ export function reviewJourneyInputs({ lab, run, actor, at, questionIds }) { let next = openReviewJourney({ lab, value: run }); if (isCalculationJourney(next)) return next; requireValue(named(actor), 'Name the person reviewing the inputs.'); for (const question of next.definition.questions) { if ([CONTEXT, OPERATIONS].includes(question.id) || questionIds && !questionIds.includes(question.id)) continue; const answer = next.answers[question.id]; if (answer.status === WORKFLOW_ANSWER_STATUS.AWAITING_REVIEW) next = lab.workflows.answer({ run: next, questionId: question.id, value: answer.value, status: WORKFLOW_ANSWER_STATUS.ACCEPTED, actor, role: question.role, at: atTime(at) }); } return next; } export async function evaluateReviewJourney({ lab, run, execution, at, stepId }) { const current = openReviewJourney({ lab, value: run }); if (isCalculationJourney(current)) return solveReviewJourney({ lab, run: current, execution, at }); const id = stepId ?? settings(current).planningStepId; const state = lab.workflows.prepare({ run: current, stepId: id }); // Reopening or pressing Review twice does not abandon an unchanged booking. // A changed premise becomes stale through the native workflow before this gate. if ([WORKFLOW_STEP_STATUS.ACCEPTED, WORKFLOW_STEP_STATUS.AWAITING_REVIEW].includes(state.status)) return current; return lab.workflows.evaluate({ run: current, stepId: id, ...(execution ? { execution } : {}), createdAt: atTime(at) }); } /** Calculate all applicable assessments in dependency order. Native supplied answers * and current result states replace analytical acceptance, never operating authority. */ export async function solveReviewJourney({ lab, run, execution, at }) { const current = openReviewJourney({ lab, value: run }); requireValue(isCalculationJourney(current), 'This retained definition requires its explicit reviewed execution.'); return lab.workflows.solve({ run: current, ...(execution ? { execution } : {}), createdAt: atTime(at) }); } export function acceptReviewFinding({ lab, run, actor, at, stepId }) { const current = openReviewJourney({ lab, value: run }); requireValue(!isCalculationJourney(current), 'Calculation findings are not accepted by a reviewer; calculate the current supplied inputs.'); const state = lab.workflows.prepare({ run: current, stepId: stepId ?? settings(current).planningStepId }); requireValue(state.status === WORKFLOW_STEP_STATUS.AWAITING_REVIEW, 'Review a current completed finding; stale or unavailable results cannot be accepted.'); return lab.workflows.review({ run: current, evaluationId: state.evaluationId, status: WORKFLOW_REVIEW_STATUS.ACCEPTED, actor, role: state.role, at: atTime(at) }); } export function inspectReviewJourney({ lab, run }) { const current = openReviewJourney({ lab, value: run }); const output = lab.workflows.output({ run: current }); const planningStep = output.steps.find(row => row.id === settings(current).planningStepId); const evaluations = current.evaluations.filter(row => row.stepId === planningStep.id); const evaluation = evaluations.at(-1) ?? null; const currentRun = evaluation && !planningStep.stale && planningStep.evaluationId === evaluation.id && resultIsCurrent(current, planningStep) ? evaluation.run : null; const operations = current.case.journeyOperations; const lastDecision = operations.findLast(row => row.kind === JOURNEY_OPERATION.DECISION) ?? null; const decision = choiceIsReady(current, planningStep) && lastDecision?.evaluationHash === evaluation?.contentHash ? lastDecision : null; return { output, planningStep, evaluation, currentRun, previousRun: evaluations.at(-2)?.run ?? current.case.journeyContext.previousRun ?? current.case.journeyContext.screeningRun ?? null, latestRun: evaluation?.run ?? null, context: current.case.journeyContext, operations, decision, staleDecision: lastDecision && !decision ? lastDecision : null, currentOperations: decision ? operations.filter(row => row.evaluationHash === decision.evaluationHash && row.planId === decision.planId) : [], }; } function appendOperation(lab, run, operation, actor, at) { requireValue(named(actor), 'Name the person recording this event.'); return lab.workflows.answer({ run, questionId: OPERATIONS, value: [...run.case.journeyOperations, operation], status: isCalculationJourney(run) ? WORKFLOW_ANSWER_STATUS.SUPPLIED : WORKFLOW_ANSWER_STATUS.ACCEPTED, ...(isCalculationJourney(run) ? {} : { actor, role: 'case-owner' }), at: atTime(at) }); } export function recordJourneyDecision({ lab, run, optionId, actor, at }) { const current = openReviewJourney({ lab, value: run }); const view = inspectReviewJourney({ lab, run: current }); requireValue(choiceIsReady(current, view.planningStep) && view.currentRun, isCalculationJourney(current) ? 'Calculate a current complete finding before recording an operating decision.' : 'Accept the current finding before recording an operating decision.'); const assessment = commitment.resolveCommitmentAssessment(view.currentRun.assessment, view.currentRun.report); requireValue(commitment.isAssessmentComplete(assessment) && commitment.hasFeasibleWitness(assessment), 'No complete feasible response is available. Record escalation or revise the commitment.'); let candidates = assessment.plans.filter(plan => plan.complete && plan.feasible && (plan.id === optionId || Object.values(plan.choices).includes(optionId))); const exact = candidates.find(plan => plan.id === optionId); if (exact) candidates = [exact]; if (candidates.length > 1) { const preferred = candidates.filter(plan => assessment.recommendation?.tiedPlanIds?.includes(plan.id)); if (preferred.length === 1) candidates = preferred; } requireValue(candidates.length === 1, 'Choose one exact feasible complete plan, including its start time.'); const plan = candidates[0]; return appendOperation(lab, current, { kind: JOURNEY_OPERATION.DECISION, caseId: current.identity.runId, caseRevision: current.revision, evaluationHash: view.evaluation.contentHash, evaluationId: view.evaluation.id, runHash: view.planningStep.runHash, planId: plan.id, optionId, choices: plan.choices, expense: plan.expense, actor, at: atTime(at) }, actor, at); } /** This records an externally supplied assertion. Domain-authored closure gates * must check its scope, timing, result and source; recording is not execution. */ export function recordJourneyOperation({ lab, run, kind, record, actor, at }) { const current = openReviewJourney({ lab, value: run }); requireValue(Object.values(JOURNEY_OPERATION).includes(kind) && kind !== JOURNEY_OPERATION.DECISION, 'Choose a supported operating event.'); requireValue(record && typeof record === 'object' && !Array.isArray(record) && named(record.reference), 'Supply the original external record reference.'); const view = inspectReviewJourney({ lab, run: current }); requireValue(kind === JOURNEY_OPERATION.ESCALATION || view.decision, 'Record a response based on the current supported finding first.'); if (view.decision && kind !== JOURNEY_OPERATION.ESCALATION) { if (record.optionId !== undefined) requireValue(record.optionId === view.decision.planId || Object.values(view.decision.choices).includes(record.optionId), 'The external record identifies a different selected response.'); if (record.choices !== undefined) requireValue(equal(record.choices, view.decision.choices), 'The external record identifies different complete choices.'); } const prior = view.operations.find(row => row.kind === kind && row.record?.reference === record.reference); if (prior) { requireValue(equal(prior.record, record) && prior.evaluationHash === (view.decision?.evaluationHash ?? null) && prior.planId === (view.decision?.planId ?? null), 'This reference already records a different event or assessment basis.', 'REVIEW_RECORD_CONFLICT'); return current; } const operation = { kind, record, caseId: current.identity.runId, caseRevision: current.revision, evaluationHash: view.decision?.evaluationHash ?? null, planId: view.decision?.planId ?? null, evaluationId: view.decision?.evaluationId ?? null, optionId: view.decision?.optionId ?? null, actor, at: atTime(at) }; return appendOperation(lab, current, operation, actor, at); } /** Local storage is an example boundary, not an SDK database. Expected hashes * prevent another tab's saved review from being overwritten silently. */ export function saveReviewJourney({ lab, run, storage, key, expectedHash = null }) { const current = openReviewJourney({ lab, value: run }); const priorText = storage.getItem(key); const prior = priorText === null ? null : openReviewJourney({ lab, value: priorText }); requireValue(!prior || prior.contentHash === current.contentHash || prior.contentHash === expectedHash, 'Another saved revision exists. Reopen it before saving this review.', 'REVIEW_SAVE_CONFLICT'); requireValue(!prior || prior.identity.runId === current.identity.runId, 'This storage key belongs to another case.'); storage.setItem(key, lab.sources.renderJSON(current, { maxBytes: 50000000 })); return current.contentHash; }