crewCards.ts

src/simulation/crewCards.ts

crewCards.ts434 lines← Lessons
1import {createMachine, defineReducer, dispatch, freeze, type Reducer} from './engine';2import type {ActionData, DispatchTrace, RecordedBlock, Snapshot} from './types';34/** Executable Crew Cards teaching design. It models app policy and the evidence5 * the architect can observe. It does not instantiate native Takt or Reactor. */6type Actor = 'school' | 'registry';7type Checkpoint = {type: 'Checkpoint'};8type RollAction = ActionData & (Checkpoint9  | {type: 'Enroll'; student: number; course: number}10  | {type: 'Score'; student: number; course: number; score: number; passMark: number}11  | {type: 'OpenAward'; award: number; student: number; course: number}12  | {type: 'CloseAward'; award: number; card?: number}13  | {type: 'RefuseAward'; award: number; reason: string});14type RegistryAction = ActionData & (Checkpoint15  | {type: 'Issue'; school: string; award: number; student: number; course: number}16  | {type: 'Suspend' | 'Reinstate'; school: string}17  | {type: 'Revoke'; card: number});1819type RollRecord = {kind: 'Enrolled'}20  | {kind: 'Passed' | 'NotPassed' | 'Completed'; score: number}21  | {kind: 'Awarding'; ticket: number; score: number}22  | {kind: 'Carded'; score: number; card: number};23type RollTicket = {student: number; course: number; status: CrewAward['status']; card?: number; reason?: string};24type RollState = {records: Record<string, RollRecord>; tickets: Record<string, RollTicket>; 'open awards': number};25type StandingState = {status: 'Good' | 'Suspended'; courses: number[]; issued: number};26type CardRecord = {school: string; award: number; student: number; course: number; status: 'Valid' | 'Revoked'};27type CardsState = {records: Record<string, CardRecord>; byAward: Record<string, number>; valid: number; latest: number | null};2829export type CrewReceipt = {kind: 'Issued'; card: number; block: number} | {kind: 'Rejected'; reason: string};30export type CrewRequest = {issuer: 'harbour'; destination: 'registry'; route: 'card.issue';31  award: number; student: number; course: number; schoolBlock: number; createdAt: number; expiresAt: number};32export type CrewAward = {ticket: number; student: number; course: number; route: 'remote' | 'local';33  status: 'Pending' | 'Carded' | 'Completed' | 'Refused'; phase: 'Ready' | 'IssueCard' | 'Blocked' | 'Done' | 'Refused';34  delivery: 'not-sent' | 'sent' | 'stored'; responsePending: boolean; attempt: number;35  request?: CrewRequest; attemptDeadline?: number; unreadable?: boolean; receiverResult?: CrewReceipt; receipt?: CrewReceipt};36export type CrewMoment = {school: Snapshot; registry: Snapshot; awards: Record<number, CrewAward>};37export type CrewOutcome = CrewReceipt | {kind: 'Ok' | 'Enrolled' | 'Pending' | 'Completed' | 'Ignored' | 'NotYet' | 'Trapped'}38  | {kind: 'Scored'; passed: boolean} | {kind: 'Ticket'; ticket: number} | {kind: 'Carded'; card: number}39  | {kind: 'Refused'; reason: string};40type CrewEvent<R extends CrewOutcome = CrewOutcome> = {before: CrewMoment; after: CrewMoment; result: R; trace?: DispatchTrace};41type CrewEvidence = {source: string; issuer: string; award: number; student: number; course: number; receipt: CrewReceipt};4243const harbour = 'harbour';44const passMark = 70;45const students: Readonly<Record<string, number>> = {mira: 340, ode: 341, pau: 342, kit: 343, sol: 344};46const studentFor = (caller: string) => Object.hasOwn(students, caller) ? students[caller] : undefined;47const courses: Readonly<Record<number, {instructor: string; carded: boolean}>> = {48  12: {instructor: 'tov', carded: true}, 15: {instructor: 'tov', carded: false},49};50const courseKey = (student: number, course: number) => `${student}:${course}`;51const awardKey = (school: string, award: number) => `${school}:${award}`;52const hour = 60 * 60 * 1000;53const replyTimeout = 30_000;54const allowedRetries = 3;55const retryDeadline = (request: CrewRequest) => Math.min(request.expiresAt, request.createdAt + 24 * hour);5657const roll = defineReducer<RollState, RollAction>('roll', {58  records: {59    '340:12': {kind: 'Passed', score: 82}, '341:12': {kind: 'NotPassed', score: 55},60    '342:15': {kind: 'Passed', score: 90}, '343:12': {kind: 'Passed', score: 74},61  },62  tickets: {}, 'open awards': 0,63}, (state, action) => {64  switch (action.type) {65    case 'Enroll': {66      const key = courseKey(action.student, action.course);67      if (state.records[key]) return {error: 'AlreadyEnrolled'};68      return {ok: own => {own.records[key] = {kind: 'Enrolled'};}};69    }70    case 'Score': {71      const key = courseKey(action.student, action.course);72      const row = state.records[key];73      if (!row) return {error: 'NotEnrolled'};74      if (row.kind !== 'Enrolled') return {error: 'AlreadyScored'};75      if (!Number.isInteger(action.score) || action.score < 0 || action.score > 100) return {error: 'InvalidScore'};76      return {ok: own => {own.records[key] = {kind: action.score >= action.passMark ? 'Passed' : 'NotPassed', score: action.score};}};77    }78    case 'OpenAward': {79      const key = courseKey(action.student, action.course);80      const row = state.records[key];81      if (row?.kind === 'Awarding') return {error: 'AwardOpen'};82      if (row?.kind === 'Carded' || row?.kind === 'Completed') return {error: 'AwardComplete'};83      if (row?.kind !== 'Passed') return {error: 'NotPassed'};84      if (state.tickets[action.award]) return {error: 'TicketTaken'};85      return {ok: own => {86        own.records[key] = {kind: 'Awarding', ticket: action.award, score: row.score};87        own.tickets[action.award] = {student: action.student, course: action.course, status: 'Pending'};88        own['open awards']++;89      }};90    }91    case 'CloseAward':92    case 'RefuseAward': {93      const ticket = state.tickets[action.award];94      if (ticket?.status !== 'Pending') return {error: 'AwardNotOpen'};95      const key = courseKey(ticket.student, ticket.course);96      const row = state.records[key];97      if (row?.kind !== 'Awarding' || row.ticket !== action.award) return {error: 'AwardMismatch'};98      return {ok: own => {99        own['open awards']--;100        if (action.type === 'RefuseAward') {101          own.records[key] = {kind: 'Passed', score: row.score};102          own.tickets[action.award] = {...ticket, status: 'Refused', reason: action.reason};103        } else if (typeof action.card === 'number') {104          own.records[key] = {kind: 'Carded', score: row.score, card: action.card};105          own.tickets[action.award] = {...ticket, status: 'Carded', card: action.card};106        } else {107          own.records[key] = {kind: 'Completed', score: row.score};108          own.tickets[action.award] = {...ticket, status: 'Completed'};109        }110      }};111    }112    default: return null;113  }114}, {status: state => state.records['344:12'] ?? null});115116const standing = defineReducer<StandingState, RegistryAction>('standing', {status: 'Good', courses: [12], issued: 5}, (state, action) => {117  if (action.type === 'Suspend' || action.type === 'Reinstate') {118    if (action.school !== harbour) return {error: 'UnknownSchool'};119    return {ok: own => {own.status = action.type === 'Suspend' ? 'Suspended' : 'Good';}};120  }121  if (action.type !== 'Issue') return null;122  if (action.school !== harbour) return {error: 'UnknownSchool'};123  if (state.status !== 'Good') return {error: 'SchoolSuspended'};124  if (!state.courses.includes(action.course)) return {error: 'NotAccredited'};125  return {ok: own => {own.issued++;}};126}, {standing: state => state.status});127128const cards = defineReducer<CardsState, RegistryAction>('cards', {records: {}, byAward: {}, valid: 31, latest: null}, (state, action) => {129  if (action.type === 'Revoke') {130    if (state.records[action.card]?.status !== 'Valid') return {error: 'NoValidCard'};131    return {ok: own => {132      own.records[action.card].status = 'Revoked';133      own.valid--;134    }};135  }136  if (action.type !== 'Issue') return null;137  const key = awardKey(action.school, action.award);138  if (state.byAward[key] !== undefined) return {error: 'AwardAlreadyIssued'};139  return {ok: (own, blockId) => {140    if (own.records[blockId]) throw new Error('Card number already in use');141    own.records[blockId] = {school: action.school, award: action.award, student: action.student, course: action.course, status: 'Valid'};142    own.byAward[key] = blockId;143    own.latest = blockId;144    own.valid++;145  }};146}, {card: state => state.latest});147148const rollState = (state: CrewMoment) => state.school.state.roll as RollState;149const cardState = (state: CrewMoment) => state.registry.state.cards as CardsState;150const refusal = (state: CrewMoment, reason: string): CrewEvent<{kind: 'Refused'; reason: string}> =>151  ({before: state, after: state, result: {kind: 'Refused', reason}});152const event = <R extends CrewOutcome>(before: CrewMoment, after: CrewMoment, result: R, trace?: DispatchTrace): CrewEvent<R> =>153  ({before, after, result, ...(trace ? {trace} : {})});154155function requireRefusal(command: CrewEvent, reason: string) {156  if (command.result.kind !== 'Refused' || command.result.reason !== reason) throw new Error(`Expected ${reason}`);157  return {...command, result: command.result};158}159160function requireTrace<R extends CrewOutcome>(command: CrewEvent<R>) {161  if (!command.trace) throw new Error(`Expected dispatch trace for ${command.result.kind}`);162  return {...command, trace: command.trace};163}164165// The prior prefix is outside the lesson. Its checkpoint fixes the starting166// state and previous hash so the displayed suffix has genuine linked traces.167function checkpoint<A extends ActionData>(reducers: Reducer<A>[], startIndex: number, action: A): Snapshot {168  return dispatch({...createMachine(reducers), nextIndex: startIndex}, reducers, action).after;169}170171export function createCrewCards(): CrewMoment {172  return {school: checkpoint<RollAction>([roll], 115, {type: 'Checkpoint'}),173    registry: checkpoint<RegistryAction>([standing, cards], 40, {type: 'Checkpoint'}), awards: {}};174}175176function applyRoll(state: CrewMoment, action: RollAction, result: CrewOutcome): CrewEvent {177  const trace = dispatch(state.school, [roll], action);178  return trace.accepted ? event(state, {...state, school: trace.after}, result, trace)179    : {...refusal(state, trace.error!), trace};180}181182export function enrollCrew(state: CrewMoment, caller: string, course: number): CrewEvent {183  const student = studentFor(caller);184  if (student === undefined) return refusal(state, 'NotStudent');185  if (!courses[course]) return refusal(state, 'NoSuchCourse');186  return applyRoll(state, {type: 'Enroll', student, course}, {kind: 'Enrolled'});187}188189export function scoreCrew(state: CrewMoment, caller: string, student: number, course: number, score: number): CrewEvent {190  if (courses[course]?.instructor !== caller) return refusal(state, 'NotInstructor');191  return applyRoll(state, {type: 'Score', student, course, score, passMark}, {kind: 'Scored', passed: score >= passMark});192}193194export function setCrewStanding(state: CrewMoment, caller: string, suspended: boolean): CrewEvent {195  if (caller !== 'board') return refusal(state, 'NotController');196  const trace = dispatch(state.registry, [standing, cards], {type: suspended ? 'Suspend' : 'Reinstate', school: harbour});197  return event(state, {...state, registry: trace.after}, {kind: 'Ok'}, trace);198}199200export function revokeCrewCard(state: CrewMoment, caller: string, card: number): CrewEvent {201  if (caller !== 'board') return refusal(state, 'NotController');202  const trace = dispatch(state.registry, [standing, cards], {type: 'Revoke', card});203  return trace.accepted ? event(state, {...state, registry: trace.after}, {kind: 'Ok'}, trace)204    : {...refusal(state, trace.error!), trace};205}206207export function requestCrewAward(state: CrewMoment, caller: string, course: number,208  options: {capacity?: number; failAfterAdmission?: boolean} = {}): CrewEvent {209  const student = studentFor(caller);210  if (student === undefined) return refusal(state, 'NotStudent');211  if (!(course in courses)) return refusal(state, 'NoSuchCourse');212  const pending = Object.values(state.awards).filter(award => award.status === 'Pending').length;213  if (pending >= (options.capacity ?? 16)) return refusal(state, 'Busy');214  const ticket = 7 + Object.keys(state.awards).length;215  const award: CrewAward = {ticket, student, course, route: courses[course].carded ? 'remote' : 'local',216    status: 'Pending', phase: 'Ready', delivery: 'not-sent', responsePending: false, attempt: 0};217  // Stage both changes in one teaching transaction. A trap publishes neither.218  const admitted = updateAward(state, award);219  if (options.failAfterAdmission) return event(state, state, {kind: 'Trapped'});220  const attempted = applyRoll(state, {type: 'OpenAward', award: ticket, student, course}, {kind: 'Ticket', ticket});221  return attempted.trace?.accepted ? {...attempted, after: {...admitted, school: attempted.after.school}} : attempted;222}223224const updateAward = (state: CrewMoment, award: CrewAward): CrewMoment =>225  ({...state, awards: {...state.awards, [award.ticket]: award}});226227export function sendCrewAward(state: CrewMoment, ticket: number, now: number): CrewEvent {228  const award = state.awards[ticket];229  if (award?.phase !== 'Ready' || award.route !== 'remote') return refusal(state, 'CannotSend');230  const schoolBlock = state.school.blocks.find(block => block.action.type === 'OpenAward' && block.action.award === ticket)!.id;231  const request: CrewRequest = {issuer: harbour, destination: 'registry', route: 'card.issue', award: ticket,232    student: award.student, course: award.course, schoolBlock, createdAt: now, expiresAt: now + 23 * hour};233  return event(state, updateAward(state, {...award, phase: 'IssueCard', delivery: 'sent', attempt: 1,234    responsePending: true, request, attemptDeadline: now + replyTimeout}), {kind: 'Pending'});235}236237export function acknowledgeCrewAward(state: CrewMoment, ticket: number): CrewEvent {238  const award = state.awards[ticket];239  if (award?.delivery !== 'sent' || !award.responsePending) return event(state, state, {kind: 'Ignored'});240  return event(state, updateAward(state, {...award, delivery: 'stored'}), {kind: 'Pending'});241}242243/** The registry trusts authenticated issuer identity, not application body fields.244 * Its durable domain key also protects issuance once live replay records expire. */245export function issueCrewCard(state: CrewMoment, issuer: string, request: CrewRequest, now: number): CrewEvent<CrewReceipt> {246  const reject = (reason: string) => event(state, state, {kind: 'Rejected', reason});247  if (issuer !== harbour || issuer !== request.issuer) return reject('UnauthorizedPeer');248  if (now < request.createdAt) return reject('FutureRequest');249  const id = cardState(state).byAward[awardKey(issuer, request.award)];250  if (id !== undefined) {251    const recorded = cardState(state).records[id];252    return recorded.student === request.student && recorded.course === request.course253      ? event(state, state, {kind: 'Issued', card: id, block: id}) : reject('ConflictingAward');254  }255  if (now >= retryDeadline(request)) return reject('Expired');256  const trace = dispatch(state.registry, [standing, cards], {257    type: 'Issue', school: issuer, award: request.award, student: request.student, course: request.course,258  });259  if (!trace.accepted) return {...reject(trace.error!), trace};260  const card = trace.after.blocks.at(-1)!.id;261  return event(state, {...state, registry: trace.after}, {kind: 'Issued', card, block: card}, trace);262}263264export function decideCrewAward(state: CrewMoment, ticket: number, now: number): CrewEvent {265  const award = state.awards[ticket];266  if (!award?.request || award.delivery !== 'stored' || award.receiverResult) return refusal(state, 'NoStoredRequest');267  const decided = issueCrewCard(state, harbour, award.request, now);268  return {...decided, after: updateAward(decided.after, {...award, receiverResult: decided.result})};269}270271export function timeoutCrewAward(state: CrewMoment, ticket: number, now: number): CrewEvent {272  const award = state.awards[ticket];273  if (award?.phase !== 'IssueCard' || !award.responsePending || award.attemptDeadline === undefined274    || now < award.attemptDeadline) return event(state, state, {kind: 'Ignored'});275  return event(state, updateAward(state, {...award, phase: 'Blocked'}), {kind: 'Pending'});276}277278/** A delivered but unreadable response consumes the address. A logical timeout alone never does. */279export function receiveUnreadableCrewResult(state: CrewMoment, ticket: number): CrewEvent {280  const award = state.awards[ticket];281  if (!award?.responsePending || !award.receiverResult) return event(state, state, {kind: 'Ignored'});282  return event(state, updateAward(state, {...award, phase: 'Blocked', responsePending: false, unreadable: true}), {kind: 'Pending'});283}284285export function retryCrewAward(state: CrewMoment, ticket: number, now: number): CrewEvent {286  const award = state.awards[ticket];287  if (award?.phase !== 'Blocked' || !award.request) return refusal(state, 'NotBlocked');288  if (award.responsePending) return refusal(state, 'PendingAddress');289  if (!award.unreadable || now < award.request.createdAt || now >= retryDeadline(award.request)) return refusal(state, 'UnsafeRetry');290  if (award.attempt > allowedRetries) return refusal(state, 'RetriesExhausted');291  const {receiverResult: _, ...next} = award;292  return event(state, updateAward(state, {...next, phase: 'IssueCard', delivery: 'sent', responsePending: true,293    unreadable: false, attempt: award.attempt + 1, attemptDeadline: now + replyTimeout}), {kind: 'Pending'});294}295296function finishCrewAward(state: CrewMoment, award: CrewAward, receipt?: CrewReceipt): CrewEvent {297  const settled: Pick<CrewAward, 'status' | 'phase'> = receipt?.kind === 'Rejected' ? {status: 'Refused', phase: 'Refused'}298    : {status: receipt ? 'Carded' : 'Completed', phase: 'Done'};299  const action: RollAction = receipt?.kind === 'Rejected' ? {type: 'RefuseAward', award: award.ticket, reason: receipt.reason}300    : {type: 'CloseAward', award: award.ticket, ...(receipt?.kind === 'Issued' ? {card: receipt.card} : {})};301  const result: CrewOutcome = receipt?.kind === 'Issued' ? {kind: 'Carded', card: receipt.card}302    : receipt?.kind === 'Rejected' ? {kind: 'Refused', reason: receipt.reason} : {kind: 'Completed'};303  const committed = applyRoll(state, action, result);304  return committed.trace?.accepted ? {...committed, after: updateAward(committed.after, {...award, ...settled,305    responsePending: false, ...(receipt ? {receipt} : {})})} : committed;306}307308export function finishLocalCrewAward(state: CrewMoment, ticket: number): CrewEvent {309  const award = state.awards[ticket];310  return award?.route === 'local' && award.phase === 'Ready' ? finishCrewAward(state, award) : refusal(state, 'CannotCloseLocally');311}312313export function receiveCrewResult(state: CrewMoment, ticket: number): CrewEvent {314  const award = state.awards[ticket];315  return award?.responsePending && award.receiverResult ? finishCrewAward(state, award, award.receiverResult)316    : event(state, state, {kind: 'Ignored'});317}318319export function lookupCrewIssuance(state: CrewMoment, issuer: string, ticket: number): CrewEvidence | undefined {320  if (issuer !== harbour) return undefined;321  const card = cardState(state).byAward[awardKey(issuer, ticket)];322  if (card === undefined) return undefined;323  const row = cardState(state).records[card];324  return {source: 'registry', issuer, award: ticket, student: row.student, course: row.course,325    receipt: {kind: 'Issued', card, block: card}};326}327328export function reconcileCrewAward(state: CrewMoment, caller: string, ticket: number, evidence?: CrewEvidence): CrewEvent {329  if (caller !== 'dean') return refusal(state, 'NotController');330  const award = state.awards[ticket];331  if (award?.phase !== 'Blocked') return refusal(state, 'NotBlocked');332  if (!evidence) return event(state, state, {kind: 'NotYet'});333  const authentic = lookupCrewIssuance(state, harbour, ticket);334  if (!authentic || evidence.source !== 'registry' || evidence.issuer !== harbour || evidence.award !== ticket335    || evidence.student !== award.student || evidence.course !== award.course336    || evidence.receipt.kind !== 'Issued' || authentic.receipt.kind !== 'Issued'337    || evidence.receipt.card !== authentic.receipt.card || evidence.receipt.block !== authentic.receipt.block) {338    return refusal(state, 'EvidenceMismatch');339  }340  return finishCrewAward(state, award, evidence.receipt);341}342343export function readCrewAward(state: CrewMoment, caller: string, ticket: number): CrewOutcome {344  const stored = rollState(state).tickets[ticket];345  if (!stored || (caller !== 'dean' && studentFor(caller) !== stored.student)) return {kind: 'Refused', reason: 'NotYours'};346  if (stored.status === 'Carded') return {kind: 'Carded', card: stored.card!};347  if (stored.status === 'Refused') return {kind: 'Refused', reason: stored.reason!};348  return {kind: stored.status};349}350351export function replayCrewRoll(initial: Snapshot, blocks: RecordedBlock[]): DispatchTrace[] {352  let current = initial;353  return blocks.map(block => {354    const trace = dispatch(current, [roll], block.action as RollAction);355    const recorded = trace.after.blocks.at(-1);356    if (!trace.accepted || recorded?.id !== block.id || recorded.phash !== block.phash || recorded.hash !== block.hash) {357      throw new Error(`Invalid school block ${block.id}`);358    }359    current = trace.after;360    return trace;361  });362}363364function createCrewDay() {365  const school: Record<number, DispatchTrace> = {};366  const registry: Record<number, DispatchTrace> = {};367  const commit = (actor: Actor, command: CrewEvent, id: number) => {368    const trace = command.trace;369    if (!trace?.accepted || trace.after.blocks.at(-1)?.id !== id) throw new Error(`Expected ${actor} block ${id}`);370    (actor === 'school' ? school : registry)[id] = trace;371    return command.after;372  };373  const initial = createCrewCards();374  const enrolled = commit('school', enrollCrew(initial, 'sol', 12), 116);375  const scored = commit('school', scoreCrew(enrolled, 'tov', 344, 12, 91), 117);376  const miraAdmitted = commit('school', requestCrewAward(scored, 'mira', 12), 118);377  const miraSent = sendCrewAward(miraAdmitted, 7, 9 * hour).after;378  const miraStored = acknowledgeCrewAward(miraSent, 7).after;379  const miraIssued = commit('registry', decideCrewAward(miraStored, 7, 9 * hour + 1000), 41);380  const miraClosed = commit('school', receiveCrewResult(miraIssued, 7), 119);381  const pauAdmitted = commit('school', requestCrewAward(miraClosed, 'pau', 15), 120);382  const pauClosed = commit('school', finishLocalCrewAward(pauAdmitted, 8), 121);383  const suspended = commit('registry', setCrewStanding(pauClosed, 'board', true), 42);384  const kitAdmitted = commit('school', requestCrewAward(suspended, 'kit', 12), 122);385  const kitSent = sendCrewAward(kitAdmitted, 9, 10 * hour + 5 * 60_000).after;386  const kitStored = acknowledgeCrewAward(kitSent, 9).after;387  const registrySuspended = decideCrewAward(kitStored, 9, 10 * hour + 5 * 60_000 + 1000);388  const kitRejected = registrySuspended.after;389  const kitClosed = commit('school', receiveCrewResult(kitRejected, 9), 123);390  const reinstated = commit('registry', setCrewStanding(kitClosed, 'board', false), 43);391  const solAdmitted = commit('school', requestCrewAward(reinstated, 'sol', 12), 124);392  const solSent = sendCrewAward(solAdmitted, 10, 11.5 * hour).after;393  const solStored = acknowledgeCrewAward(solSent, 10).after;394  const solIssued = commit('registry', decideCrewAward(solStored, 10, 11.5 * hour + 1000), 44);395  const solBlocked = timeoutCrewAward(solIssued, 10, 11.5 * hour + replyTimeout).after;396  const solEvidence = lookupCrewIssuance(solBlocked, harbour, 10)!;397  const reconciled = reconcileCrewAward(solBlocked, 'dean', 10, solEvidence);398  const solClosed = commit('school', reconciled, 125);399  const originalRequest = miraSent.awards[7].request!;400  const unreadable = receiveUnreadableCrewResult(miraIssued, 7).after;401  const repeat = retryCrewAward(unreadable, 7, 9 * hour + 2000).after;402  const repeatStored = acknowledgeCrewAward(repeat, 7).after;403  return freeze({404    initial, final: solClosed, school, registry,405    moments: {initial, enrolled, scored, miraAdmitted, miraSent, miraStored, miraIssued, miraClosed,406      pauAdmitted, pauClosed, suspended, kitAdmitted, kitSent, kitStored, kitRejected, kitClosed,407      reinstated, solAdmitted, solSent, solStored, solIssued, solBlocked, solClosed},408    rejections: {409      wrongInstructor: requireRefusal(scoreCrew(scored, 'mira', 344, 12, 100), 'NotInstructor'),410      alreadyScored: requireTrace(requireRefusal(scoreCrew(scored, 'tov', 344, 12, 60), 'AlreadyScored')),411      notPassed: requireTrace(requireRefusal(requestCrewAward(miraClosed, 'ode', 12), 'NotPassed')),412      busy: requireRefusal(requestCrewAward(scored, 'mira', 12, {capacity: 0}), 'Busy'),413      registrySuspended: requireTrace(registrySuspended),414      registryNotAccredited: requireTrace(issueCrewCard(miraStored, harbour, {...originalRequest, course: 15}, 9 * hour + 1000)),415      awardOpen: requireTrace(requireRefusal(requestCrewAward(solBlocked, 'sol', 12), 'AwardOpen')),416      wrongReconciler: requireRefusal(reconcileCrewAward(solBlocked, 'tov', 10, solEvidence), 'NotController'),417      wrongController: requireRefusal(setCrewStanding(scored, 'mira', true), 'NotController'),418      notYours: requireRefusal(event(miraAdmitted, miraAdmitted, readCrewAward(miraAdmitted, 'ode', 7)), 'NotYours'),419    },420    replay: replayCrewRoll(initial.school, Object.values(school).slice(0, 4).map(trace => trace.after.blocks.at(-1)!)),421    retry: {unreadable, repeat, repeatStored},422    duplicate: requireIdempotentReceipt(decideCrewAward(repeatStored, 7, 9 * hour + 3000)),423    reconciled,424    lateReply: receiveCrewResult(solClosed, 10),425  });426}427428function requireIdempotentReceipt(command: CrewEvent) {429  if (command.result.kind !== 'Issued' || command.trace) throw new Error('Expected original receipt without dispatch');430  return {...command, result: command.result};431}432433export const crewDay = createCrewDay();434export type CrewDay = typeof crewDay;