@byok-sdk/bot-collaboration 0.0.0-stage → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2075 -2
  3. package/dist/adapter-steps.d.ts +49 -0
  4. package/dist/channel.d.ts +111 -0
  5. package/dist/chunk-33YA66U7.js +7 -0
  6. package/dist/chunk-33YA66U7.js.map +1 -0
  7. package/dist/chunk-6Y2B2XCP.js +12 -0
  8. package/dist/chunk-6Y2B2XCP.js.map +1 -0
  9. package/dist/chunk-QZRWFFHM.js +12 -0
  10. package/dist/chunk-QZRWFFHM.js.map +1 -0
  11. package/dist/chunk-ZX6C5U2S.js +27 -0
  12. package/dist/chunk-ZX6C5U2S.js.map +1 -0
  13. package/dist/coalesce.d.ts +18 -0
  14. package/dist/commit-vectors.test-support.d.ts +173 -0
  15. package/dist/commit.d.ts +53 -0
  16. package/dist/compaction.d.ts +13 -0
  17. package/dist/delegation.d.ts +12 -0
  18. package/dist/delivery-routing.d.ts +63 -0
  19. package/dist/delivery-vectors.test-support.d.ts +78 -0
  20. package/dist/delivery.d.ts +20 -0
  21. package/dist/dream.d.ts +88 -0
  22. package/dist/home-projections.d.ts +5 -0
  23. package/dist/host-kit.d.ts +60 -0
  24. package/dist/host-kit.js +11 -0
  25. package/dist/host-kit.js.map +1 -0
  26. package/dist/host.d.ts +472 -0
  27. package/dist/inbound.d.ts +17 -0
  28. package/dist/index.d.ts +6 -0
  29. package/dist/index.js +19 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/k4-fixtures.test-support.d.ts +10 -0
  32. package/dist/l-test-host.test-support.d.ts +72 -0
  33. package/dist/migration.d.ts +251 -0
  34. package/dist/model.d.ts +89 -0
  35. package/dist/persona.d.ts +2 -0
  36. package/dist/retention-vectors.test-support.d.ts +17 -0
  37. package/dist/retention.d.ts +61 -0
  38. package/dist/rooms.d.ts +22 -0
  39. package/dist/routine-vectors.test-support.d.ts +81 -0
  40. package/dist/routines.d.ts +110 -0
  41. package/dist/rules/autonomy.d.ts +67 -0
  42. package/dist/rules/cards.d.ts +31 -0
  43. package/dist/rules/coalesce.d.ts +111 -0
  44. package/dist/rules/commands.d.ts +306 -0
  45. package/dist/rules/commit.d.ts +82 -0
  46. package/dist/rules/compaction.d.ts +33 -0
  47. package/dist/rules/context.d.ts +484 -0
  48. package/dist/rules/delegation.d.ts +366 -0
  49. package/dist/rules/due.d.ts +15 -0
  50. package/dist/rules/frame.d.ts +4 -0
  51. package/dist/rules/history.d.ts +34 -0
  52. package/dist/rules/inbound.d.ts +53 -0
  53. package/dist/rules/index.d.ts +13 -0
  54. package/dist/rules/index.js +4 -0
  55. package/dist/rules/index.js.map +1 -0
  56. package/dist/rules/message.d.ts +31 -0
  57. package/dist/rules/outcome.d.ts +45 -0
  58. package/dist/rules/priority.d.ts +52 -0
  59. package/dist/rules/rooms.d.ts +187 -0
  60. package/dist/rules/schema.d.ts +110 -0
  61. package/dist/rules/sync.d.ts +157 -0
  62. package/dist/rules/team.d.ts +119 -0
  63. package/dist/rules/turn.d.ts +129 -0
  64. package/dist/schema.d.ts +154 -0
  65. package/dist/store-compatibility.d.ts +3 -0
  66. package/dist/switch.d.ts +53 -0
  67. package/dist/team-model.d.ts +54 -0
  68. package/dist/team.d.ts +56 -0
  69. package/dist/testing.d.ts +6 -0
  70. package/dist/testing.js +20 -0
  71. package/dist/testing.js.map +1 -0
  72. package/dist/toolset-policy.d.ts +2 -0
  73. package/dist/topology.d.ts +49 -0
  74. package/package.json +80 -4
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/coalesce.ts","../src/delivery.ts","../src/delivery-routing.ts","../src/rules/inbound.ts","../src/dream.ts","../src/inbound.ts","../src/adapter-steps.ts","../src/delegation.ts","../src/compaction.ts","../src/migration.ts","../src/topology.ts","../src/switch.ts","../src/commit.ts","../src/rooms.ts"],"names":["sealDueBatches","admitUserInput","taskId","hash","route","definition","taskIdOf","observeDevices","settleDelegations","time","json","run","occurrenceIntentKey","same","keys","optional","canonical","isOccurrenceIntentKey","routineWakeKey","promoteOccurrence"],"mappings":";;;;;;;AAQA,SAAS,SAAS,KAAA,CAA2B,KAAA,CAA2C,CACtF,MAAM,IAAM,KAAA,CAAM,IAAA,CAAK,IAAA,CAAK,KAAK,EACjC,OAAO,GAAA,EAAO,CAAE,IAAA,CAAM,OAAO,MAAA,CAAO,KAAA,CAAM,KAAK,CAAA,CAAE,KAAK,IAAA,EAAQ,IAAA,CAAK,KAAA,GAAU,KAAA,EAAS,CAAC,IAAA,CAAK,UAAA,EAAc,IAAA,CAAK,MAAA,GAAW,SAAS,CAAA,CACjI,SAAA,CAAW,CAAC,GAAA,CAAI,SAAU,GAAA,CAAI,KAAK,CAAA,CAAG,QAAA,CAAU,IAAI,QAAS,CACjE,CAEO,SAASA,gBAAe,KAAA,CAA2B,MAAA,CAA0C,GAAA,CAAmB,CACrH,MAAM,IAAA,CAAuC,EAAC,CAC9C,IAAA,MAAW,SAAS,MAAA,CAAO,MAAA,CAAO,KAAA,CAAM,YAAA,EAAgB,EAAE,CAAA,CAAG,CAC3D,MAAM,MAAQ,KAAA,CAAM,KAAA,GAAU,MAAA,CAAS,QAAA,CAAS,MAAO,KAAA,CAAM,KAAK,EAAI,MAAA,CACtE,GAAI,MAAO,IAAA,CAAK,KAAA,CAAM,KAAK,CAAA,CAAI,MACjC,CACA,aAAA,CAAc,KAAA,CAAa,cAAA,CAAe,MAAO,IAAA,CAAM,MAAA,CAAQ,GAAG,CAAC,EACrE,CAMO,SAAS,mBAAA,CAAoB,KAAA,CAA2B,KAAgD,CAC7G,IAAA,MAAW,KAAA,IAAS,MAAA,CAAO,OAAO,KAAA,CAAM,YAAA,EAAgB,EAAE,EAAG,CAC3D,MAAM,QAAA,CAAW,KAAA,CAAM,QAAU,MAAA,CAAS,CAAA,CAAI,CAAA,CAC9C,GAAA,CAAK,MAAM,QAAA,EAAY,CAAA,GAAM,QAA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OAAA,CAAQA,KAAK,EAAE,CAAC,CAAA,CAAG,SAAA,CAAY,QAAU,CAAA,CAAE,UAAA,CAAW,MAAA,CAAO,MAAM,EACpF,KAAA,CAAM,EAAE,CAAA,CAAI,CAAE,SAAU,CAAC,CAAC,MAAA,CAAQ,OAAA,CAAS,CAAC,CAAC,SAAA,EAAW,OAAA,CAAS,UAAA,CAAY,QAAQ,UAAW,EAClG,CACA,IAAA,MAAW,MAAA,IAAgB,iBAAiB,KAAA,CAAO,KAAA,CAAO,GAAA,CAAK,GAAA,CAAK,OAAO,CAAA,CAAG,CAAA,CAAE,OAAA,CAAQA,IAAAA,CAAK,MAAM,CAAC,CAAA,CAAG,YAAA,CAAe,YACxH,CAOO,SAAS,oBAAA,CAAqB,CAAA,CAAgB,KAAA,CAA2B,IAAa,IAAA,CAC3F,OAAA,CAA2B,CAC3B,MAAM,SAAW,IAAM,MAAA,CAAO,MAAA,CAAO,KAAA,CAAM,KAAK,KAAK,CAAA,CAAE,MAAA,CAAO,IAAA,EAAQ,KAAK,QAAQ,CAAA,CAAE,OACrF,IAAI,OAAA,CAAU,MAAO,MAAA,CACrB,EAAG,CACD,YAAA,CAAa,EAAG,KAAA,CAAO,GAAA,CAAK,CAAC,EAAA,CAAI,MAAO,OAAA,GAAY,OAAA,CAAQ,KAAA,CAAa,QAAA,CAAS,GAAI,KAAA,CAAO,OAAO,CAAC,CAAA,CAAG,OAAO,CAAA,CAC/G,MAAA,CAAS,QAAA,EAAS,CAClB,UAAW,IAAA,IAAQ,MAAA,CAAO,MAAA,CAAO,KAAA,CAAM,KAAK,CAAA,CAAG,OAAA,CAAU,IAAA,CAAK,IAAI,GAAK,QACzE,CAAA,MAAS,UAAS,CAAI,MAAA,EACtB,OAAO,OACT","file":"chunk-QZRWFFHM.js","sourcesContent":["import type { Json } from '@byok-sdk/server/execution-core';\nimport { addBatchTurns, addTurn, json, type CollaborationState } from './model.js';\nimport * as rules from './rules/coalesce.js';\n\n// K8 adapter for the pure coalescing rules in `rules/coalesce.ts`, and the input batch projection.\nexport { COALESCE_DEFAULTS, batchRequest, coalescePolicy, type CoalescePolicy, type InputFields } from './rules/coalesce.js';\n\n/** Bot facts from the team and the Turns. An absent Bot has none. */\nfunction botFacts(state: CollaborationState, botId: string): rules.BotFacts | undefined {\n const bot = state.team.bots[botId];\n return bot && { busy: Object.values(state.turns).some(turn => turn.botId === botId && !turn.conclusion && turn.status !== 'blocked'),\n configKey: [bot.revision, bot.model], archived: bot.archived };\n}\n/** Runs first in each Host sync. The window counts from the first input; later inputs never extend it. */\nexport function sealDueBatches(state: CollaborationState, policy: rules.CoalescePolicy | undefined, now: number): void {\n const bots: Record<string, rules.BotFacts> = {};\n for (const batch of Object.values(state.inputBatches ?? {})) {\n const facts = batch.state === 'open' ? botFacts(state, batch.botId) : undefined;\n if (facts) bots[batch.botId] = facts;\n }\n addBatchTurns(state, rules.sealDueBatches(state, bots, policy, now));\n}\n\n/**\n * Runs last in each Host sync, so it sees every seal of that pass and of earlier transactions.\n * Revision 1 shows the batch at its first projection while open. A batch that seals before then projects only revision 2.\n */\nexport function projectInputBatches(state: CollaborationState, emit: (key: string, value: Json) => void): void {\n for (const batch of Object.values(state.inputBatches ?? {})) {\n const revision = batch.state === 'open' ? 1 : 2;\n if ((batch.revision ?? 0) >= revision) continue;\n batch.revision = revision;\n emit(`input-batch:${batch.id}:${revision}`, json({ owner: batch.botId, id: batch.id, revision, state: batch.state, sealReason: batch.sealReason,\n inputIds: batch.inputIds, openedAt: batch.openedAt, sealAt: batch.sealAt }));\n }\n}\n\n/**\n * Admit one user input before K4 enqueue. Returns the id of the Turn that answers it: the batch id.\n * Without a policy, each input keeps its own Turn, as before coalescing.\n */\nexport function admitUserInput(state: CollaborationState, input: rules.InputFields, policy: rules.CoalescePolicy | undefined, now: number): string {\n const admission = rules.admitUserInput(state, input, { bot: botFacts(state, input.botId), turn: state.turns[input.id] }, policy, now);\n addBatchTurns(state, admission.sealed);\n if (admission.turn) {\n state.budgets[input.id] ??= { continuation: 0, delegation: 0 };\n addTurn(state, { id: input.id, root: input.id, source: 'user', request: input.request, botId: input.botId, hop: 0, authority: input.authority });\n }\n return admission.id;\n}\n/** `cancelTurn` accepts a batch id or a member input id. An open batch seals first, so the whole batch cancels. */\nexport function sealBatchForCancel(state: CollaborationState, id: string): string {\n const { id: target, sealed } = rules.sealBatchForCancel(state, id);\n if (sealed) addBatchTurns(state, [sealed]);\n return target;\n}\n","import { hash } from '@byok-sdk/server/execution-core';\nimport type { ChannelPort, Delivery } from './channel.js';\n\nconst MAX_ATTEMPTS = 3;\nconst MAX_WAIT_MS = 60_000;\ntype SendResult = Awaited<ReturnType<ChannelPort['send']>>;\ntype ReadbackResult = Awaited<ReturnType<NonNullable<ChannelPort['readback']>>>;\n\n/** Manual resend supplies a nonce. The original delivery keeps its audit identity. */\nexport function deliveryId(taskId: string, messageId: string, route: Delivery['route'], nonce?: string): string {\n const key = route.kind === 'reply' ? ['reply', route.inboundId] : ['push', route.pushRouteId];\n return hash(nonce === undefined ? [taskId, messageId, key] : [taskId, messageId, key, nonce]);\n}\n\n/** The caller persists this claim before it calls the channel. */\nexport function startDelivery(row: Delivery, now: number): boolean {\n if (row.state !== 'pending' || row.attempts >= MAX_ATTEMPTS || (row.nextAttemptAt !== undefined && now < row.nextAttemptAt)) return false;\n row.state = 'sending';\n row.attempts++;\n delete row.nextAttemptAt;\n delete row.code;\n return true;\n}\n\nfunction currentAttempt(row: Delivery, attempt: number): boolean {\n return row.state === 'sending' && row.attempts === attempt;\n}\n\nfunction retryDelivery(row: Delivery, now: number, retryAfterMs: number): void {\n const wait = Math.max(retryAfterMs, 1_000 * 2 ** (row.attempts - 1));\n if (wait > MAX_WAIT_MS) {\n row.state = 'rejected';\n return;\n }\n row.state = 'pending';\n row.nextAttemptAt = now + wait;\n}\n\n/** A stale completion cannot replace an echo or a later attempt's outcome. */\nexport function settleDelivery(row: Delivery, attempt: number, result: SendResult, now: number): void {\n if (!currentAttempt(row, attempt)) return;\n if (result?.result === 'accepted' && typeof result.platformMessageId === 'string' && result.platformMessageId.length > 0) {\n row.state = 'accepted';\n row.platformMessageId = result.platformMessageId;\n delete row.code;\n return;\n }\n if (result?.result !== 'rejected' || typeof result.code !== 'string' || result.code.length === 0 || typeof result.retryable !== 'boolean') {\n unknownDelivery(row, attempt, 'invalid_send_result');\n return;\n }\n row.code = result.code;\n if (!result.retryable || row.attempts >= MAX_ATTEMPTS) {\n row.state = 'rejected';\n return;\n }\n const retryAfter = result.retryAfterMs === undefined ? 0 : result.retryAfterMs;\n if (!Number.isFinite(retryAfter) || retryAfter < 0) {\n row.state = 'rejected';\n row.code = 'invalid_retry_after';\n return;\n }\n retryDelivery(row, now, retryAfter);\n}\n\nexport function unknownDelivery(row: Delivery, attempt: number, code: string): void {\n if (!currentAttempt(row, attempt)) return;\n row.state = 'unknown';\n row.code = code;\n delete row.nextAttemptAt;\n}\n\n/** A persisted send claim does not prove that the platform received the message. */\nexport function recoverDelivery(row: Delivery): void {\n if (row.state === 'sending') unknownDelivery(row, row.attempts, 'interrupted');\n}\n\n/**\n * Only authoritative absence permits a new attempt after uncertain I/O. `attempt` is the attempt that the readback observed:\n * a result that comes after a later attempt changes nothing, as `settleDelivery` is fenced by its attempt.\n */\nexport function readbackDelivery(row: Delivery, attempt: number, result: ReadbackResult, now: number): void {\n if (row.state !== 'unknown' || row.attempts !== attempt) return;\n if (result === 'accepted') {\n row.state = 'accepted';\n delete row.code;\n } else if (result === 'absent') {\n if (row.attempts >= MAX_ATTEMPTS) {\n row.state = 'rejected';\n row.code = 'attempts_exhausted';\n } else {\n delete row.code;\n retryDelivery(row, now, 0);\n }\n }\n}\n\n/** The caller has already checked the verified self principal and exact identity. */\nexport function acceptDeliveryEcho(row: Delivery, platformMessageId: string): boolean {\n if (!platformMessageId) return false;\n if (row.state === 'accepted') {\n if (row.platformMessageId && row.platformMessageId !== platformMessageId) return false;\n row.platformMessageId = platformMessageId;\n return true;\n }\n // A readback can report absence before a delayed platform echo arrives.\n const waitingRetry = row.state === 'pending' && row.attempts > 0;\n if (row.state !== 'sending' && row.state !== 'unknown' && !waitingRetry) return false;\n row.state = 'accepted';\n row.platformMessageId = platformMessageId;\n delete row.code;\n delete row.nextAttemptAt;\n return true;\n}\n","import { hash, type Conclusion } from '@byok-sdk/server/execution-core';\nimport type { CollaborationState, Turn } from './model.js';\nimport { inboundKey, type Conversation, type Delivery, type InboundMessage, type PushRoute, type ReplyRoute } from './channel.js';\nimport { deliveryId } from './delivery.js';\n\n/** The intent conclusions a delivery rule reads. A K4 `LedgerState` fits; H passes its intent rows. */\nexport interface IntentConclusions { readonly intents: Readonly<Record<string, { readonly conclusion?: Conclusion }>> }\n\ninterface StoredInbound {\n id: string; conversation: Conversation; channel: string; sequence: number;\n /** The Turn or open input batch that answers the message. Absent on a filtered message. */\n root?: string;\n /** The classification that refused the message before any Turn (#1229 item 3). */\n filtered?: string;\n reply?: Omit<ReplyRoute, 'token'> & { token?: string };\n}\nexport interface ChannelState {\n inbounds: Record<string, StoredInbound>;\n pushRoutes: Record<string, PushRoute>;\n deliveries: Record<string, Delivery>;\n}\nexport function channelState(state: CollaborationState): ChannelState {\n return state.channel ??= { inbounds: {}, pushRoutes: {}, deliveries: {} };\n}\nconst sameConversation = (a: Conversation, b: Conversation): boolean => a.kind === b.kind && a.id === b.id;\nexport function turnConversation(state: CollaborationState, turn: Turn): Conversation {\n const seat = state.team.seats[turn.id];\n return seat ? { kind: 'group', id: state.team.rounds[seat.roundId]!.roomId } : { kind: 'direct', id: turn.botId };\n}\nfunction turnRoot(state: CollaborationState, turn: Turn): string {\n const seat = state.team.seats[turn.id];\n return seat ? state.team.rounds[seat.roundId]!.root : turn.root;\n}\nfunction rootOpen(ledger: IntentConclusions, state: CollaborationState, root: string, conversation: Conversation): boolean {\n return Object.values(state.turns).some(turn => turnRoot(state, turn) === root && sameConversation(turnConversation(state, turn), conversation)\n && !turn.conclusion && !ledger.intents[hash(turn.id)]?.conclusion && !['blocked', 'failed', 'delivered'].includes(turn.status))\n || Object.values(state.inputBatches ?? {}).some(batch => batch.id === root && batch.state === 'open')\n || Object.values(state.team.seats).some(seat => state.team.rounds[seat.roundId]?.root === root && !seat.released);\n}\n/** Save with input admission, before any process pass can accept its reply. Redelivery never refreshes a token. */\nexport function rememberInbound(state: CollaborationState, message: InboundMessage, root: string): void {\n if (typeof message.channel !== 'string' || !message.channel.trim() || typeof message.platformMessageId !== 'string' || !message.platformMessageId) throw new Error('Invalid inbound identity');\n const route = message.replyRoute;\n if (route && (route.kind !== 'reply' || route.channel !== message.channel || route.inboundId !== message.platformMessageId\n || typeof route.token !== 'string' || !route.token || !Number.isSafeInteger(route.expiresAt) || route.expiresAt < 0)) {\n throw new Error('Invalid reply route binding');\n }\n const channels = channelState(state), id = inboundKey(message);\n channels.inbounds[id] ??= { id, root, conversation: { ...message.conversation }, channel: message.channel,\n sequence: ++state.sequence, ...(route ? { reply: { ...route } } : {}) };\n}\n/**\n * Records a message that the Host refused before any Turn (#1229 item 3), so its disposition is visible in the Host UI.\n * An adapter identity that cannot name the message records nothing: the audit row is still the authority for it.\n */\nexport function rememberFilteredInbound(state: CollaborationState, message: InboundMessage, code: string): void {\n if (typeof message.channel !== 'string' || !message.channel.trim() || typeof message.platformMessageId !== 'string' || !message.platformMessageId) return;\n const channels = channelState(state), id = inboundKey(message);\n channels.inbounds[id] ??= { id, conversation: { ...message.conversation }, channel: message.channel,\n sequence: ++state.sequence, filtered: code };\n}\nexport function enablePush(state: CollaborationState, conversation: Conversation, channel: string, target: string, owner: string, now: number): PushRoute {\n if (!conversation.id || !channel.trim() || !target.trim()) throw new Error('Invalid push route');\n const channels = channelState(state);\n for (const route of Object.values(channels.pushRoutes)) {\n if (sameConversation(route.conversation, conversation) && route.revokedAt === undefined) revokePush(state, route.id, now);\n }\n const id = hash(['push-route', conversation, channel, target, ++state.sequence]);\n const route: PushRoute = { kind: 'push', id, conversation: { ...conversation }, channel, target, optedInBy: owner, optedInAt: now };\n channels.pushRoutes[id] = route;\n return route;\n}\nexport function revokePush(state: CollaborationState, id: string, now: number): void {\n const routes = state.channel?.pushRoutes;\n const route = routes && Object.hasOwn(routes, id) ? routes[id] : undefined;\n if (!route) throw new Error('Push route not found');\n route.revokedAt ??= now;\n for (const delivery of Object.values(state.channel!.deliveries)) {\n if (delivery.state === 'pending' && delivery.route.kind === 'push' && delivery.route.pushRouteId === id) refuseRoute(state, delivery);\n }\n}\nfunction activePush(state: CollaborationState, conversation: Conversation): PushRoute | undefined {\n return Object.values(state.channel?.pushRoutes ?? {}).find(route => route.revokedAt === undefined && sameConversation(route.conversation, conversation));\n}\nfunction insert(state: CollaborationState, input: Pick<Delivery, 'taskId' | 'turnId' | 'messageId' | 'body' | 'conversation' | 'channel' | 'route'>,\n staged = false): Delivery {\n const id = deliveryId(input.taskId, input.messageId, input.route);\n return channelState(state).deliveries[id] ??= { id, ...input, state: staged ? 'staged' : 'pending', attempts: 0 };\n}\n/**\n * Called in the content acceptance transaction. No external call or projection contains the token. A `staged` delivery\n * waits for `promoteStaged` in its Turn's outcome transaction (#1762).\n */\nexport function queueDelivery(ledger: IntentConclusions, state: CollaborationState, turn: Turn, taskId: string, messageId: string, body: string, now: number,\n staged = false): Delivery | undefined {\n const conversation = turnConversation(state, turn), root = turnRoot(state, turn);\n const inbound = Object.values(state.channel?.inbounds ?? {}).filter(row => row.root === root && sameConversation(row.conversation, conversation))\n .sort((a, b) => b.sequence - a.sequence)[0];\n if (inbound?.reply?.token && inbound.reply.expiresAt > now && rootOpen(ledger, state, root, conversation)) {\n return insert(state, { taskId, turnId: turn.id, messageId, body, conversation, channel: inbound.reply.channel, route: { kind: 'reply', inboundId: inbound.id } }, staged);\n }\n const push = activePush(state, conversation);\n if (push) return insert(state, { taskId, turnId: turn.id, messageId, body, conversation, channel: push.channel, route: { kind: 'push', pushRouteId: push.id } }, staged);\n state.audit.push(`Delivery ${inbound?.reply ? 'reply_route_expired' : 'no_push_route'}: ${taskId} ${messageId}`);\n return undefined;\n}\n/** The outcome transaction of task `taskId` makes its staged deliveries sendable. The only promotion (#1762). */\nexport function promoteStaged(state: CollaborationState, taskId: string): string[] {\n const rows = Object.values(state.channel?.deliveries ?? {}).filter(row => row.state === 'staged' && row.taskId === taskId);\n for (const row of rows) row.state = 'pending';\n return rows.map(row => row.id);\n}\n/**\n * A staged delivery whose intent concluded was not promoted by that conclusion's outcome: the Turn failed, or another task\n * generation concluded it. Its reply is withheld and stays only as an audit fact (#1762).\n */\nexport function withholdStaged(ledger: IntentConclusions, state: CollaborationState): void {\n for (const row of Object.values(state.channel?.deliveries ?? {})) {\n if (row.state !== 'staged' || !ledger.intents[hash(row.turnId)]?.conclusion) continue;\n row.state = 'rejected'; row.code = 'outcome_not_applied';\n state.audit.push(`Delivery outcome_not_applied: ${row.taskId} ${row.messageId}`);\n }\n}\n/** A pending delivery already owns its reply slot, including across terminal settlement. */\nexport function deliveryRoute(state: CollaborationState, row: Delivery, now: number): ReplyRoute | PushRoute | undefined {\n if (row.route.kind === 'push') {\n const route = state.channel?.pushRoutes[row.route.pushRouteId];\n return route && route.revokedAt === undefined && sameConversation(route.conversation, row.conversation) ? structuredClone(route) : undefined;\n }\n const stored = state.channel?.inbounds[row.route.inboundId], route = stored?.reply;\n return route?.token && route.expiresAt > now && sameConversation(stored!.conversation, row.conversation)\n ? { ...route, token: route.token } : undefined;\n}\n/** Route expiry is certain non-delivery for a pending row. Any fallback gets its own route-bound id. */\nexport function refuseRoute(state: CollaborationState, row: Delivery): void {\n if (row.state !== 'pending') return;\n row.state = 'rejected'; delete row.nextAttemptAt;\n row.code = row.route.kind === 'reply' ? 'reply_route_expired' : 'push_route_revoked';\n state.audit.push(`Delivery ${row.code}: ${row.taskId} ${row.messageId}`);\n const push = row.route.kind === 'reply' ? activePush(state, row.conversation) : undefined;\n if (push) insert(state, { taskId: row.taskId, turnId: row.turnId, messageId: row.messageId, body: row.body, conversation: row.conversation,\n channel: push.channel, route: { kind: 'push', pushRouteId: push.id } });\n}\n/**\n * A reply is sent after its Turn concluded (#1762), so an open delivery keeps its token until expiry: a staged row waits for\n * promotion, and an unknown row can return to pending after a readback.\n */\nexport function cleanReplyTokens(ledger: IntentConclusions, state: CollaborationState, now: number): void {\n for (const row of Object.values(state.channel?.inbounds ?? {})) {\n if (!row.reply?.token || row.root === undefined) continue;\n const reserved = Object.values(state.channel!.deliveries).some(delivery => delivery.route.kind === 'reply'\n && delivery.route.inboundId === row.id && ['staged', 'pending', 'sending', 'unknown'].includes(delivery.state));\n if (now >= row.reply.expiresAt || !reserved && !rootOpen(ledger, state, row.root, row.conversation)) delete row.reply.token;\n }\n}\n/** A manual resend is an explicit owner action, not an automatic retry of the unknown row. */\nexport function resendUnknown(state: CollaborationState, id: string, now: number): Delivery {\n const deliveries = state.channel?.deliveries;\n const old = deliveries && Object.hasOwn(deliveries, id) ? deliveries[id] : undefined;\n if (!old || old.state !== 'unknown') throw new Error('Only an unknown delivery can be resent');\n const available = deliveryRoute(state, old, now) ?? activePush(state, old.conversation);\n if (!available) throw new Error('No active delivery route');\n const route: Delivery['route'] = available.kind === 'reply' ? old.route : { kind: 'push', pushRouteId: available.id };\n const nextId = deliveryId(old.taskId, old.messageId, route, String(++state.sequence));\n const row: Delivery = { id: nextId, taskId: old.taskId, turnId: old.turnId, messageId: old.messageId, body: old.body, conversation: { ...old.conversation },\n channel: available.channel, route: { ...route }, state: 'pending', attempts: 0, resendOf: old.id };\n state.channel!.deliveries[nextId] = row;\n return row;\n}\nexport function echoCandidates(state: CollaborationState, message: InboundMessage): Delivery[] {\n return Object.values(state.channel?.deliveries ?? {}).filter(row => row.channel === message.channel\n && sameConversation(row.conversation, message.conversation) && row.state !== 'rejected'\n && (message.deliveryId !== undefined ? row.id === message.deliveryId : row.platformMessageId === message.platformMessageId));\n}\n","/**\n * The inbound disposition projection as pure rules (#1229 item 3). It reads the existing inbound, input-batch and Turn\n * rows and returns one destination per recorded inbound human message. It writes nothing and keeps no disposition of its\n * own, so the ledger stays the only authority.\n */\n/** The five destinations of #1229 item 3. */\nexport type InboundDisposition =\n | { id: string; disposition: 'filtered'; code: string }\n | { id: string; disposition: 'coalesced' | 'answered' | 'failed' | 'cancelled'; turnId: string };\n/** The inbound fields that the projection reads. The delivery adapter stores more. */\nexport interface InboundRow {\n readonly id: string;\n /** The Turn or open input batch that answers the message. Absent on a filtered message. */\n readonly root?: string;\n /** The classification that refused the message before any Turn. */\n readonly filtered?: string;\n /** The ledger sequence, for the oldest-first order. */\n readonly sequence?: number;\n}\n/** The Turn fields that decide a message's destination. */\nexport interface InboundTurn {\n readonly id: string; readonly root: string; readonly status: string;\n readonly conclusion?: string; readonly inputIds?: readonly string[];\n}\nexport interface InboundState {\n readonly channel?: { readonly inbounds?: Readonly<Record<string, InboundRow>> };\n readonly turns: Readonly<Record<string, InboundTurn>>;\n readonly inputBatches?: Readonly<Record<string, { readonly state: string }>>;\n}\nconst ANSWERED = new Set(['succeeded', 'delivered']);\nconst FAILED = new Set(['failed', 'expired', 'declined', 'superseded', 'abandoned']);\n/**\n * One message's current destination.\n * - `filtered` is the classification that refused it before a Turn.\n * - `coalesced` means it is in `turnId`: an open input batch, or a Turn that has not reached a terminal.\n * - `answered` is a succeeded Turn, `cancelled` a cancel, and every other terminal is `failed`.\n * A recorded message with no live Turn and no open batch is `failed`, never silent: retention or a crash cannot make\n * the Host UI report that the message has no destination.\n */\nexport function inboundDisposition(state: InboundState, row: InboundRow): InboundDisposition {\n if (row.filtered !== undefined) return { id: row.id, disposition: 'filtered', code: row.filtered };\n const root = row.root;\n if (root === undefined) return { id: row.id, disposition: 'failed', turnId: row.id };\n const turn = Object.hasOwn(state.turns, root) ? state.turns[root] : undefined;\n if (!turn) {\n // An open batch has no Turn yet. It is still the Turn that will answer the message.\n const batch = state.inputBatches && Object.hasOwn(state.inputBatches, root) ? state.inputBatches[root] : undefined;\n return batch?.state === 'open'\n ? { id: row.id, disposition: 'coalesced', turnId: root }\n : { id: row.id, disposition: 'failed', turnId: root };\n }\n const conclusions = [turn.conclusion, turn.status];\n if (conclusions.includes('cancelled')) return { id: row.id, disposition: 'cancelled', turnId: turn.id };\n if (conclusions.some(value => value !== undefined && ANSWERED.has(value))) return { id: row.id, disposition: 'answered', turnId: turn.id };\n if (conclusions.some(value => value !== undefined && FAILED.has(value))) return { id: row.id, disposition: 'failed', turnId: turn.id };\n return { id: row.id, disposition: 'coalesced', turnId: turn.id };\n}\n/** Every recorded inbound human message, oldest first. The order is the ledger sequence, never insertion order. */\nexport function inboundDispositions(state: InboundState): InboundDisposition[] {\n return Object.values(state.channel?.inbounds ?? {})\n .filter(row => row.filtered !== undefined || row.root !== undefined)\n .sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))\n .map(row => inboundDisposition(state, row));\n}\n","import { buildDreamInstruction, buildHandoffPack, checkRoutineSchedule } from '@byok-sdk/protocol';\nimport { concludeOccurrence, hash, occurrenceIntentKey, occurrenceOfIntentKey, promoteOccurrence, routineCommands, setLifecycle, time,\n type ExecutionTemplate, type HostOccurrenceRoutineDefinition, type HostOccurrenceRun, type LedgerState, type Routine } from '@byok-sdk/server/execution-core';\nimport { json, stateOf, type CollaborationState, type Turn } from './model.js';\nimport { BOT_DREAM, dreamTable, ROUTINE_LATE_AFTER_MS, routineCalendar } from './routines.js';\nimport { handoffFrameBytes, handoffTurn, type ContextTurn } from './rules/context.js';\nimport { inactive } from './rules/team.js';\n\n// Dreaming (#1475): each Bot gets a daily routine that tidies its memory. K8 owns the schedule and K4 owns the FIFO position,\n// supersede and deadline of the dream intent. A dream is a fresh writer with `agentMemory: 'none'` and no `agentMemoryCommit`\n// on every platform, so its cwd is the Bot's home and the device injects neither `MEMORY.md` nor memory guidance.\n\n/** The time limit of a dream task. A user Turn behind a running dream waits at most this long. */\nexport const DEFAULT_DREAM_MAX_DURATION_MS = 900_000;\n/** A dream can sit behind a night of Bot work, so it waits longer than a routine Turn. */\nexport const DREAM_WAIT_MS = 3_600_000;\nconst DREAM_HOUR = 3;\nconst MIN_PACK_BYTES = 1024;\n\n/** `dreaming` of `BotOptions`. Absent means on with these defaults; `false` turns dreaming off for the whole Host. */\nexport interface DreamingOptions {\n /** IANA time zone of the daily 03:00 slot. Absent: this process's local zone when the routine is created, stored in its definition. */\n timeZone?: string;\n /**\n * Host model template names, preferred first. A dream takes the first that exists now and is on the Bot's device, else\n * the Bot's own template. Only this list decides what is cheap: K8 infers nothing from a runtime or vendor name.\n */\n models?: readonly string[];\n /** Default `DEFAULT_DREAM_MAX_DURATION_MS`. */\n maxDurationMs?: number;\n /** Request native session input when the device advertises it. Default true. This applies only to runtime templates: a harness template, like a device that does not advertise native sessions, receives no request and the dream runs without that input. */\n nativeSessions?: boolean;\n}\nexport interface DreamPolicy { timeZone?: string; models: readonly string[]; maxDurationMs: number; nativeSessions: boolean }\nconst scheduleIn = (tz: string) => ({ minute: 0, hour: DREAM_HOUR, tz });\nconst localZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;\n/** Checks the option once, at construction. `undefined`: dreaming is off. */\nexport function dreamPolicy(options: DreamingOptions | false | undefined): DreamPolicy | undefined {\n if (options === false) return undefined;\n // The local zone is checked here too, because a routine created later could not fail any better than the constructor.\n const check = checkRoutineSchedule(scheduleIn(options?.timeZone ?? localZone()));\n if (!check.ok) throw new Error(`dreaming: ${check.code}: ${check.message}`);\n const maxDurationMs = time(options?.maxDurationMs ?? DEFAULT_DREAM_MAX_DURATION_MS);\n if (maxDurationMs < 1) throw new Error('dreaming: maxDurationMs must be positive');\n return { ...(options?.timeZone === undefined ? {} : { timeZone: options.timeZone }), models: [...options?.models ?? []], maxDurationMs, nativeSessions: options?.nativeSessions ?? true };\n}\n\nexport type DreamSkip = 'superseded' | 'dreaming_off' | 'bot_archived' | 'bot_suspended' | 'device_unavailable' | 'bot_not_ready' | 'no_new_turns'\n | 'model_unavailable' | 'history_unavailable';\n/** How one occurrence ended. `template` and `fallback` are set once a dream was offered. */\nexport interface DreamRecord {\n occurrenceKey: string; at: number; outcome: 'skipped' | 'succeeded' | 'failed' | 'declined' | 'cancelled' | 'expired' | 'superseded';\n reason?: string; template?: string; fallback?: boolean;\n}\n/** `since` starts the next window. `throughTurn` is the last Turn of the settled run of Turns that the last successful dream covered. */\nexport interface DreamBot { since: number; throughTurn?: string; last?: DreamRecord }\n/** An occurrence that K8 has not closed. `template` is set when it joined the FIFO. */\nexport interface OpenDream { botId: string; windowEnd: number; template?: string; fallback?: boolean; throughTurn?: string }\n/** The dream table. It owns each dream intent, as `hostIntents` owns a Host intent, and the Host intent API never reads it. */\nexport interface DreamState { bots: Record<string, DreamBot>; open: Record<string, OpenDream> }\n\nconst ownerOf = (routine: Routine): string | undefined => {\n const spec = routine.definition.hostOccurrence;\n return spec?.type === BOT_DREAM ? (spec.input as unknown as { owner: string }).owner : undefined;\n};\n/** The occurrence of a dream intent, or `undefined` for any other key. */\nexport function dreamOf(state: CollaborationState, intentKey: string): OpenDream | undefined {\n const key = occurrenceOfIntentKey(intentKey);\n return key !== undefined && state.dreams && Object.hasOwn(state.dreams.open, key) ? state.dreams.open[key] : undefined;\n}\n/** The intent ids of open dreams: background work that user input goes ahead of. */\nexport function dreamIntentIds(state: CollaborationState): string[] {\n return Object.keys(state.dreams?.open ?? {}).map(key => hash(occurrenceIntentKey(key)));\n}\n/** The `bot-dream` occurrence hook. A hook gets no K4 state, so the sync decides and promotes, as for a routine Turn. */\nexport function recordDream(state: CollaborationState, run: HostOccurrenceRun, now: number): void {\n dreamTable(state).open[run.occurrenceKey] = { botId: (run.input as { owner: string }).owner, windowEnd: now };\n}\n\n/** One dream routine for each unarchived Bot with a usable template, and no other. It runs in every sync, so it covers each way a Bot starts or ends. */\nexport function reconcileDreamRoutines(s: LedgerState, policy: DreamPolicy | undefined, models: Readonly<Record<string, ExecutionTemplate>>, now: number): void {\n const state = stateOf(s.application), rows = Object.values(s.routines).flatMap(row => { const owner = ownerOf(row); return owner === undefined ? [] : [{ row, owner }]; });\n const open = new Map<string, Routine>();\n for (const { row, owner } of rows) {\n if (row.lifecycle === 'completed') continue;\n const bot = state.team.bots[owner];\n if (policy && bot && !bot.archived && !open.has(owner)) open.set(owner, row);\n else setLifecycle(s, row.definition.id, 'completed', now, routineCalendar);\n }\n if (!policy) return;\n const commands = routineCommands(s, { now: () => now, nextTime: routineCalendar, hostJobs: new Map(), occurrenceHooks: new Map([[BOT_DREAM, recordDream]]), executionRoutines: 'refuse' });\n const definition = (id: string, version: number, owner: string, tz: string): HostOccurrenceRoutineDefinition => ({ id, version, timeZone: tz,\n rule: json(scheduleIn(tz)), waitMs: DREAM_WAIT_MS, lateAfterMs: ROUTINE_LATE_AFTER_MS, hostOccurrence: { type: BOT_DREAM, input: { owner } } });\n for (const bot of Object.values(state.team.bots)) {\n if (bot.archived) continue;\n const routine = open.get(bot.id), latest = routine?.pending ?? routine?.definition;\n if (latest) {\n // A routine keeps the local zone it was created with, so only an explicit zone moves it.\n if (policy.timeZone !== undefined && latest.timeZone !== policy.timeZone) commands.update(definition(latest.id, latest.version + 1, bot.id, policy.timeZone));\n } else if (models[bot.model]) {\n // A completed routine cannot resume, so turning dreaming back on takes a new id.\n commands.create(definition(`dream:${bot.id}:${rows.filter(row => row.owner === bot.id).length + 1}`, 1, bot.id, policy.timeZone ?? localZone()));\n dreamTable(state).bots[bot.id] ??= { since: now };\n }\n }\n}\n\nconst completed = (row: Pick<Turn, 'status'>) => row.status === 'succeeded' || row.status === 'delivered';\n/**\n * The rows after the mark, oldest first, up to the first that is still open. User input can overtake an older Turn, so a\n * dream never moves its mark past an open one, or that Turn would finish behind the mark and no dream would see it. A mark\n * that retention removed counts every remaining row as new.\n */\nfunction settledAfter<T extends Pick<Turn, 'id' | 'status'>>(rows: readonly T[], mark: string | undefined): T[] {\n const after = rows.slice(rows.findIndex(row => row.id === mark) + 1);\n const open = after.findIndex(row => row.status === 'queued' || row.status === 'processing');\n return open < 0 ? after : after.slice(0, open);\n}\nfunction chooseModel(policy: DreamPolicy, models: Readonly<Record<string, ExecutionTemplate>>, botModel: string, deviceId: string) {\n const name = policy.models.find(model => Object.hasOwn(models, model) && models[model]!.deviceId === deviceId);\n if (name !== undefined) return { template: name, fallback: false, base: models[name]! };\n return models[botModel] ? { template: botModel, fallback: true, base: undefined } : undefined;\n}\n/** The template's runtime and limits with the Bot's Agent, and none of what a Bot Turn offers. */\nfunction dreamExecution(base: ExecutionTemplate, bot: ExecutionTemplate, instruction: string, maxDurationMs: number, window: { fromMs: number; toMs: number }, nativeSessions: boolean): ExecutionTemplate {\n const { messageEgress: _egress, requiredToolsets: _toolsets, agentMemoryCommit: _commit, homeAccess: _home, preparation: _preparation, nativeSessions: _nativeSessions, ...payload } = base.payload;\n return { deviceId: bot.deviceId, payload: { ...payload, instruction, session: { mode: 'fresh' }, agentRef: bot.payload.agentRef, agentMemory: 'none',\n limits: { ...payload.limits, maxDurationMs }, terminalProjection: { mode: 'none' }, ...(nativeSessions && payload.harnessId === undefined ? { nativeSessions: { ...window, ifAdvertised: true } } : {}) } };\n}\n/** The pack fills what `instructionMaxBytes` leaves after the fixed text of the instruction. */\nfunction dreamInstruction(rows: readonly (Turn | ContextTurn)[], window: { fromMs: number; toMs: number }, maxDurationMs: number, instructionMaxBytes: number): string {\n const budget = { maxDurationMs }, frame = { omittedTurns: 0, earlier: [], recent: [] };\n const fixed = Buffer.byteLength(buildDreamInstruction({ history: frame, window, budget }), 'utf8') - Buffer.byteLength(JSON.stringify(frame), 'utf8');\n const totalBytes = Math.max(instructionMaxBytes - fixed, handoffFrameBytes(rows.length));\n const history = buildHandoffPack(rows.map(handoffTurn), { recentBytes: Math.floor(totalBytes / 4 * 3), earlyBytes: totalBytes, totalBytes });\n return buildDreamInstruction({ history, window, budget });\n}\n/** Refuses an `instructionMaxBytes` that leaves a dream no room for history. */\nexport function checkDreamInstruction(instructionMaxBytes: number): void {\n const room = instructionMaxBytes - Buffer.byteLength(dreamInstruction([], { fromMs: 0, toMs: 0 }, 1, 0), 'utf8');\n if (room < MIN_PACK_BYTES) throw new Error(`instructionMaxBytes leaves a dream ${room} bytes of history, under ${MIN_PACK_BYTES}`);\n}\n\nexport interface DreamSync {\n tenant: string; policy: DreamPolicy | undefined; models: Readonly<Record<string, ExecutionTemplate>>; instructionMaxBytes: number; now: number;\n /** The device of a Bot refuses new work. */\n refused(botId: string): boolean;\n /** Absent: the ledger's Turns are the history. Present: the rows an external history read returned by occurrence key, `null` for a failed read. */\n history?: ReadonlyMap<string, readonly ContextTurn[] | null> | undefined;\n historyMode: boolean;\n}\n/** Decides each new occurrence and closes each settled dream. Returns true when a dream joined the FIFO or an occurrence concluded. */\nexport function syncDreams(s: LedgerState, sync: DreamSync): boolean {\n const state = stateOf(s.application), dreams = state.dreams;\n if (!dreams) return false;\n let changed = false;\n const close = (key: string, run: OpenDream, outcome: DreamRecord['outcome'], reason?: string) => {\n const bot = dreams.bots[run.botId] ??= { since: run.windowEnd };\n bot.last = { occurrenceKey: key, at: run.windowEnd, outcome, ...(reason === undefined ? {} : { reason }),\n ...(run.template === undefined ? {} : { template: run.template, fallback: run.fallback! }) };\n if (outcome === 'succeeded') {\n bot.since = run.windowEnd;\n if (run.throughTurn !== undefined) bot.throughTurn = run.throughTurn;\n }\n delete dreams.open[key];\n };\n const skip = (key: string, run: OpenDream, reason: DreamSkip) => {\n const occurrence = s.occurrences[key];\n if (occurrence && !occurrence.conclusion) { concludeOccurrence(s, key, reason === 'superseded' ? 'superseded' : 'cancelled'); changed = true; }\n close(key, run, reason === 'superseded' ? 'superseded' : 'skipped', reason);\n };\n for (const [key, run] of Object.entries(dreams.open)) {\n const bot = state.team.bots[run.botId], stopped = !bot ? 'archived' : inactive(bot);\n if (run.template !== undefined) {\n const intent = s.intents[hash(occurrenceIntentKey(key))];\n if (!intent) close(key, run, 'failed', 'intent_compacted');\n else if (intent.conclusion) close(key, run, intent.conclusion);\n else if (stopped && intent.phase !== 'inflight' && !intent.cancelReason) intent.cancelReason = 'cancelled';\n continue;\n }\n if (s.occurrences[key]?.hook?.executionSuperseded) { skip(key, run, 'superseded'); continue; }\n if (!sync.policy) { skip(key, run, 'dreaming_off'); continue; }\n if (!bot || stopped) { skip(key, run, stopped === 'suspended' ? 'bot_suspended' : 'bot_archived'); continue; }\n if (sync.refused(bot.id)) { skip(key, run, 'device_unavailable'); continue; }\n if (bot.readyRevision !== bot.revision) { skip(key, run, 'bot_not_ready'); continue; }\n const record = dreams.bots[bot.id] ??= { since: run.windowEnd };\n const settled = settledAfter(Object.values(state.turns).filter(turn => turn.botId === bot.id), record.throughTurn), fresh = settled.filter(completed);\n if (!fresh.length) { skip(key, run, 'no_new_turns'); continue; }\n const model = chooseModel(sync.policy, sync.models, bot.model, bot.execution.deviceId);\n if (!model) { skip(key, run, 'model_unavailable'); continue; }\n let rows: readonly (Turn | ContextTurn)[] = fresh;\n let throughTurn = settled.at(-1)!.id;\n if (sync.historyMode) {\n const read = sync.history?.get(key);\n if (read === undefined) continue;\n if (read === null) { skip(key, run, 'history_unavailable'); continue; }\n const readSettled = settledAfter(read, record.throughTurn);\n rows = readSettled.filter(completed);\n if (!rows.length) { skip(key, run, 'no_new_turns'); continue; }\n throughTurn = readSettled.at(-1)!.id;\n }\n const window = { fromMs: Math.min(record.since, run.windowEnd), toMs: run.windowEnd };\n const instruction = dreamInstruction(rows, window, sync.policy.maxDurationMs, sync.instructionMaxBytes);\n Object.assign(run, { template: model.template, fallback: model.fallback, throughTurn });\n promoteOccurrence(s, sync.tenant, key, dreamExecution(model.base ?? bot.execution, bot.execution, instruction, sync.policy.maxDurationMs, window, sync.policy.nativeSessions));\n changed = true;\n }\n return changed;\n}\n/** The dreams that wait for an external history read, by occurrence key, with the Bot and the intent key of the read. */\nexport function dreamReads(state: CollaborationState): { key: string; botId: string; turnId: string }[] {\n return Object.entries(state.dreams?.open ?? {}).filter(([, run]) => run.template === undefined)\n .map(([key, run]) => ({ key, botId: run.botId, turnId: occurrenceIntentKey(key) }));\n}\n","import { json, type CollaborationState, type Turn } from './model.js';\nimport type { Json } from './rules/turn.js';\nimport type { Round } from './team-model.js';\nimport { inboundDisposition, inboundDispositions, type InboundDisposition, type InboundState, type InboundTurn } from './rules/inbound.js';\n\n/**\n * The K8 adapter for the inbound disposition projection (#1229 item 3). The pure rule reads Turn and batch rows; this\n * adapter adds one synthetic row per round root, because a round input stores its round id as the inbound root and its\n * seat Turns have their own roots.\n */\n/** A round root answers a room input when any seat Turn concluded; otherwise the round is still open. */\nfunction roundTurn(state: CollaborationState, round: Round): InboundTurn {\n const turns = round.seats.map(id => state.turns[id]).filter((turn): turn is Turn => turn !== undefined);\n const conclusions = turns.map(turn => turn.conclusion).filter((value): value is string => value !== undefined);\n if (conclusions.includes('cancelled')) return { id: round.id, root: round.root, status: 'failed', conclusion: 'cancelled' };\n if (turns.some(turn => turn.status === 'succeeded' || turn.conclusion === 'succeeded' || turn.conclusion === 'delivered')) {\n return { id: round.id, root: round.root, status: 'succeeded', conclusion: 'succeeded' };\n }\n const failed = new Set(['failed', 'expired', 'declined', 'superseded', 'abandoned']);\n if (conclusions.some(conclusion => failed.has(conclusion)) || turns.some(turn => turn.status === 'failed')) {\n return { id: round.id, root: round.root, status: 'failed', conclusion: 'failed' };\n }\n return { id: round.id, root: round.root, status: 'queued' };\n}\n/** The rows that the pure rule reads. A round with no seat Turn is still the round root that answers its input. */\nexport function inboundState(state: CollaborationState): InboundState {\n const turns: Record<string, InboundTurn> = { ...state.turns };\n for (const round of Object.values(state.team.rounds)) if (round.root === round.id) turns[round.id] ??= roundTurn(state, round);\n return { channel: state.channel, turns, inputBatches: state.inputBatches };\n}\n/** The Host UI read (#1229): every recorded inbound human message and its current destination, oldest first. */\nexport function inboundDispositionsOf(state: CollaborationState): InboundDisposition[] {\n // Most Hosts never receive IM input. Skip building round rows when there is no inbound row at all.\n if (Object.keys(state.channel?.inbounds ?? {}).length === 0) return [];\n return inboundDispositions(inboundState(state));\n}\n/**\n * One projection id per destination transition. The id names the destination, so a projection value never changes and\n * the K4 outbox can hold every transition without an identity conflict.\n */\nexport function inboundProjection(disposition: InboundDisposition): { id: string; value: Json } {\n const id = disposition.disposition === 'filtered'\n ? `inbound:${disposition.id}:filtered:${disposition.code}`\n : `inbound:${disposition.id}:${disposition.disposition}:${disposition.turnId}`;\n return { id, value: json(disposition) };\n}\n/** Publishes the current destination of each message. `project` is idempotent for an unchanged destination. */\nexport function projectInboundDispositions(state: CollaborationState, emit: (id: string, value: Json) => void): void {\n for (const disposition of inboundDispositionsOf(state)) {\n const projection = inboundProjection(disposition);\n emit(projection.id, projection.value);\n }\n}\n","import type { RoutineCommands } from '@byok-sdk/server/execution-core';\nimport { sealDueBatches, projectInputBatches, type CoalescePolicy } from './coalesce.js';\nimport { cleanReplyTokens, withholdStaged, type IntentConclusions } from './delivery-routing.js';\nimport { projectInboundDispositions } from './inbound.js';\nimport type { Publish } from './rules/delegation.js';\nimport { expireCards } from './rules/commands.js';\nimport { dreamOf } from './dream.js';\nimport type { CollaborationState } from './model.js';\nimport type { CommandPorts } from './rules/commands.js';\nimport { createDefinition, owned, updateDefinition } from './routines.js';\n\n/**\n * A K4 terminal that K8 cannot apply (#882 Q6f): its key is neither a Bot Turn nor a Host intent, its Host handler\n * failed, or the outcome commit of its Bot Turn threw. The intent stays open at the head of its FIFO, and each pass rejects\n * with this error, until the outcome applies or the owner calls `failStuckIntent`.\n */\nexport class IntentOutcomeError extends Error {\n constructor(readonly key: string, readonly code: 'unknown_intent' | 'handler_failed' | 'outcome_failed', message: string) {\n super(message); this.name = 'IntentOutcomeError';\n }\n}\n\ntype OutcomePorts = NonNullable<CommandPorts['outcome']>;\n\n/** Routes a success terminal to a Host intent handler, a dream (closed by sync), or a Bot Turn outcome. */\nexport function routeTerminal(state: CollaborationState, key: string, handler: string | undefined):\n { kind: 'host_intent'; handler: string } | { kind: 'dream' } | { kind: 'bot_turn' } {\n if (handler !== undefined) return { kind: 'host_intent', handler };\n if (dreamOf(state, key)) return { kind: 'dream' };\n if (!Object.hasOwn(state.turns, key)) throw new IntentOutcomeError(key, 'unknown_intent', 'No Bot Turn or Host intent has this key');\n return { kind: 'bot_turn' };\n}\n\n/**\n * Runs a Host intent handler in the terminal transaction. `run` is undefined when no handler has this name.\n * L rejects missing handlers at startup; H has no startup check across every scope, so the terminal fails closed here.\n */\nexport function runHostIntentHandler(key: string, name: string, run: (() => unknown) | undefined): void {\n if (run === undefined) throw new IntentOutcomeError(key, 'handler_failed', `Unknown Host intent handler: ${name}`);\n let result: unknown;\n try { result = run(); } catch (cause) {\n throw new IntentOutcomeError(key, 'handler_failed', cause instanceof Error ? cause.message : String(cause));\n }\n // The handler shares the terminal transaction, so it must not resolve later. Its promise must not reject unhandled.\n if (result && typeof (result as { then?: unknown }).then === 'function') {\n void Promise.resolve(result).catch(() => {});\n throw new IntentOutcomeError(key, 'handler_failed', 'Host intent handler must be synchronous');\n }\n}\n\n/** The refusal of a Bot Turn whose outcome commit threw. */\nexport function outcomeFailure(key: string, cause: unknown): IntentOutcomeError {\n return new IntentOutcomeError(key, 'outcome_failed', cause instanceof Error ? cause.message : String(cause));\n}\n\n/** The outcome ports shared by L, H and their vector subjects. The caller adds `committed`. */\nexport function botOutcomePorts({ taskId, routines, manage, roomPosts }: {\n taskId: string; routines: RoutineCommands; manage: OutcomePorts['manage']; roomPosts: boolean;\n}): Omit<OutcomePorts, 'committed'> {\n return {\n manage,\n createRoutine: (turn, action, index) => routines.create(createDefinition(routines.list(), turn.botId, taskId, index, action, turn.authority ?? 'bot')),\n updateRoutine: (turn, action) => routines.update(updateDefinition(routines.list(), turn.botId, action)),\n cancelRoutine: (turn, action) => routines.lifecycle(owned(routines.list(), turn.botId, action.routineId).definition.id, 'completed'),\n roomPosts,\n };\n}\n\n/** Seals due batches and expires cards before the sync freezes any new ContextPack. */\nexport function syncHead(state: CollaborationState, coalesce: CoalescePolicy | undefined, now: number): void {\n sealDueBatches(state, coalesce, now);\n expireCards(state, now);\n}\n\n/**\n * Withholds the staged replies of concluded intents, cleans reply tokens and projects every input batch and inbound destination after the sync's Turn steps.\n * H's finishDelivery also cleans reply tokens, corresponding to L's cleanup in each flush pass.\n * #1229 item 3: one projection per destination; an unchanged destination keeps the same projection id and value.\n */\nexport function syncTail(state: CollaborationState, conclusions: IntentConclusions | undefined, now: number, emit: Publish): void {\n if (conclusions !== undefined) {\n withholdStaged(conclusions, state);\n cleanReplyTokens(conclusions, state, now);\n }\n projectInputBatches(state, emit);\n projectInboundDispositions(state, emit);\n}\n","import { hash, taskId as taskIdOf, type LedgerState } from '@byok-sdk/server/execution-core';\nimport type { CollaborationState, Delegation, DelegationCancel } from './model.js';\nimport * as rules from './rules/delegation.js';\n\n// K8 adapter for the pure delegation rules in `rules/delegation.ts`. It reads the K4 intent facts of each Turn from the ledger.\nexport { BOT_REPLY_MAX_BYTES, BOT_REQUEST_MAX_BYTES, CONTEXT_FIXED_MAX_BYTES, DEFAULT_CANCEL_GRACE_MS, DEFAULT_INSTRUCTION_MAX_BYTES,\n FRAME_MAX_BYTES, HOP_LIMIT, OPEN_DELEGATION_ENTRY_MAX_BYTES, OPEN_DELEGATIONS_MAX_BYTES, OPEN_DELEGATIONS_MAX_ITEMS,\n REPLY_REQUEST_MAX_BYTES, REPLY_RETRY_MAX_MS, REPLY_UNCERTAIN_AFTER_MS, ROOT_BOT_BUDGET, ROSTER_ENTRY_MAX_BYTES,\n applyDelegate, cancellable, claimUnit, crossBotRequest, delegationBlock, delegationDue, endChain, instructionOverhead, isCrossBot,\n minimumInstructionBytes, observeStart, openDelegations, openDelegationsContext, reconcileReply, releaseUnit, reserveUnits,\n resolveDelegation, retryReply, type DelegationTimers } from './rules/delegation.js';\n\n/** The K4 facts of each Turn, read by Turn id when a rule asks for them. */\nexport function intentFacts(s: Pick<LedgerState, 'intents' | 'executions'>): rules.IntentFacts {\n const intent = (key: string) => s.intents[hash(key)];\n return {\n intent: key => {\n const row = intent(key);\n return row && { taskId: row.taskId, ...(row.conclusion ? { conclusion: row.conclusion } : {}), ...(row.cancelReason ? { cancelReason: row.cancelReason } : {}) };\n },\n started: key => {\n const row = intent(key);\n return !!row && Array.from({ length: row.generation + 1 }, (_, g) => s.executions[taskIdOf(key, g)]).some(execution =>\n execution?.started || execution?.terminal !== undefined && execution.terminal.envelope.type !== 'task.decline');\n },\n declineCode: key => {\n const row = intent(key), envelope = row && s.executions[row.taskId]?.terminal?.envelope;\n return envelope?.type === 'task.decline' ? envelope.payload.code : undefined;\n },\n offeredTo: key => {\n const row = intent(key), execution = row && s.executions[row.taskId];\n return row?.phase === 'inflight' && execution?.submission === 'delivered' && !execution.started && execution.attempt?.status === 'offered'\n ? row.execution.deviceId : undefined;\n },\n };\n}\n/** Only the intent rows: cancel arbitration reads no execution. */\nexport function intentRows(s: Pick<LedgerState, 'intents'>): Pick<rules.IntentFacts, 'intent'> {\n return { intent: key => intentFacts({ intents: s.intents, executions: {} }).intent(key) };\n}\nexport function observeDevices(s: LedgerState, state: CollaborationState, devices: ReadonlyMap<string, boolean>, emit: rules.Publish): void {\n rules.observeDevices(state, intentFacts(s), devices, emit);\n}\nexport function arbitrateCancel(s: Pick<LedgerState, 'intents'>, state: CollaborationState, d: Delegation, now: number, emit: rules.Publish,\n reason?: DelegationCancel['reason']): boolean {\n return rules.arbitrateCancel(state, intentRows(s), d, now, emit, reason);\n}\nexport function settleDelegations(s: LedgerState, state: CollaborationState, now: number, emit: rules.Publish, timers?: rules.DelegationTimers): void {\n rules.settleDelegations(state, intentFacts(s), now, emit, timers);\n}\nexport function abandonDelegation(s: LedgerState, state: CollaborationState, d: Delegation, now: number, emit: rules.Publish): boolean {\n return rules.abandonDelegation(state, intentRows(s), d, now, emit);\n}\n","import { hash, type CompactVeto, type HostLedger, type LedgerState } from '@byok-sdk/server/execution-core';\nimport type { CollaborationState, Turn } from './model.js';\nimport { routineOccurrence } from './routines.js';\nimport { compactVeto } from './rules/commands.js';\n\n/**\n * K4 compacted the intent of this Turn, so its identity can never run again (#816). The intent tombstone proves it.\n * A routine Turn's tombstone expires with its slot, but K4 removes its occurrence with the intent, and a routine Turn is\n * written with its occurrence. So a routine Turn without its occurrence was compacted too.\n */\nexport function turnIntentRetired(ledger: HostLedger, s: Pick<LedgerState, 'occurrences'>, turn: Turn, now: number): boolean {\n return ledger.hasTombstone('intent', turn.id, now) || turn.source === 'routine' && !s.occurrences[routineOccurrence(turn)];\n}\n\n/**\n * The K8 compact veto (#816). Open every Bot ledger with it: `new HostLedger(file, tenant, { compactVeto: botCompactVeto })`.\n * It runs the K8 rule `compactVeto` (rules/compaction.ts) on the ledger's K4 intents and execution receipts.\n */\nexport const botCompactVeto: CompactVeto = (ledger, key) => {\n // Read only: `stateOf` would create the collaboration row inside the compaction.\n const state = ledger.application.collaboration as unknown as CollaborationState | undefined;\n if (state === undefined) return undefined;\n if (state.version !== 3) return 'Unsupported Bot collaboration state version';\n // #975: an exported domain keeps what it exported, so nothing of it is compacted.\n if (state.switchExport) return 'switch_exported';\n return compactVeto(state, key, { hasIntent: turnId => !!ledger.intents[hash(turnId)],\n receipt: taskId => ledger.executions[taskId]?.messageReceipt });\n};\n","import { canonical, hash } from '@byok-sdk/server/execution-core/canonical';\nimport { isOccurrenceIntentKey, occurrenceIntentKey, routineWakeKey, taskId as taskIdOf, validateJson, validateRetry, type Conclusion, type Intent, type Json, type Occurrence, type RetryPolicy, type Routine,\n type RoutineDefinition } from '@byok-sdk/server/execution-core';\nimport type { CollaborationState } from './model.js';\nimport { DEVICE_SWITCHING } from './rules/sync.js';\n\n/**\n * The state that an L/H owner switch moves (#975, design §8): one coordination domain, an L ledger tenant or an H scope,\n * exported by the old owner after every device of the domain is frozen and drained, and imported by the new owner into an\n * empty domain. Both Hosts read and write this one neutral form, so neither Host's storage is the format. The old owner\n * seals it; the new owner verifies it, writes it, reads its own rows back into this form, and compares the digest.\n *\n * A record holds what a target needs to rebuild the row. Each value is one the source stores, never a default. H stores\n * only part of it today: the K4-only fields (#975 D1 to D5) get H columns in the H slice that imports them, and until then\n * H cannot import a record that has them. Every object has an exact set of keys, so nothing an importer would drop can\n * ride along.\n *\n * A value that a Host derives from others is not in the record, and the target derives its own. The format never sees\n * the source's stored copies, so each Host's export builder checks its copies against these rules and refuses to build an\n * export where one differs:\n * - an intent's `agent`, K4 `agentKey(domain, execution)` (`transitions.ts`, H `intents.ts` with its scope). It names the\n * source's tenant or scope, and K4 `loadForSwitch` refuses another tenant's, so each target derives it with its domain;\n * - the K4 execution input of an earlier generation, and K4 `intent.execution`: `input` with that generation's task id, and\n * `input` without `taskId`. That holds while K4 runs without its memory option, which rewrites the frozen instruction\n * (`core.ts` begin); K8 passes none;\n * - K4 `applied`: the current task id exactly when `conclusion` is `succeeded`, which K4 sets only with that settle\n * (`core.ts` terminal);\n * - a K4 occurrence's wake key and slot, K4 `routineWakeKey(routineId, definitionVersion, trigger.plannedAt)` and its hash. K4 records\n * and compacts one slot with each occurrence (`routines.ts` recordOccurrence, `ledger.ts` compact), and H's slot is the\n * occurrence's unique `(routine_id, definition_version, planned_at)`, so the format has no slot section;\n * - an occurrence's intent id, the hash of K4 `occurrenceIntentKey(key)`, and K4 `attempts` (`switchAttempts`).\n * An occurrence key is checked here as well: K4 `hash([routineId, definitionVersion, trigger])`.\n *\n * The digest covers the header too: `domain` is the source's tenant or scope id, never the target's (a switch back to L\n * opens a new tenant). So the target's read-back copies the document's header as it is and rebuilds only the sections\n * from its own rows. Devices are in JS string order of `deviceId`, and each section in JS string order of\n * `canonical(identity)`, so a read-back sorts that way in JS or reseals; a database `ORDER BY` may give `unsorted`.\n *\n * A channel delivery moves under its id, `hash([taskId, messageId, routeKey, nonce?])` (`delivery.ts` deliveryId), which\n * names no domain, so the target's readback or resend of a `sending` or `unknown` delivery uses the source's idempotency\n * key. Whether a platform honors that key is its adapter's concern (`docs/host-im-adapter.md`), and the switch does not\n * change it. A projection does not move: H's receiver deduplicates by `(scope, id)` (H `sender.ts` ProjectionPort), and L\n * does not record whether a pending projection was sent (H does: it raises `tries` before the send), so the source\n * flushes its projections before the export.\n */\nexport const SWITCH_EXPORT_VERSION = 1;\nexport const SWITCH_SECTIONS = ['collaboration', 'archived', 'intents', 'routines', 'occurrences', 'outbox', 'tombstones'] as const;\nexport type SwitchSection = typeof SWITCH_SECTIONS[number];\n\n/** A device of the domain and its revision on the source Host, frozen by the source's open switch. */\nexport interface SwitchDevice { deviceId: string; frozenRevision: number }\n/** A K8 retention row (#798), `commands` included, with its absolute expiry. The importer keeps the expiry. */\nexport interface ArchivedRecord { namespace: string; id: string; body: Json; expiresAt?: number }\n/** An accepted Agent message of one task: the K4 execution's `messageReceipt`. */\nexport interface MessageReceipt { messageId: string; contentHash: string }\n/** The K4 execution facts of one earlier generation of an intent. K4 begins each generation before it opens the next. */\nexport interface ExecutionRecord {\n submission: 'uncertain' | 'delivered'; started: boolean; attempt: Json; terminal: Json; messageReceipt?: MessageReceipt;\n}\n/**\n * A concluded intent, moved as a row: L K4 `intents` and `executions[taskId]` with K8 `hostIntents`, H `intent`. `input` is\n * the frozen execution input that was submitted, a sealed one still sealed. A late terminal or message for it is refused\n * by its conclusion; one for a compacted intent, by its `intent` tombstone.\n *\n * `earlierExecutions` holds generations 0 to `generation - 1`, in order, each with the execution facts K4 stores\n * (#975 D1). Its task id is `hash([key, generation])` and its input is `input` with that task id, so neither is stored.\n * K4 compacts an intent only with the execution of every generation (`ledger.ts` compact: `Missing execution evidence`).\n * A message for an earlier task is answered from its execution, by its receipt or else `stale_generation`, never\n * `unknown_task` (`core.ts` consumeMessage); H stores the same generations in its H slice. Nothing here relies on a\n * replay after the switch getting `accepted`: the target's SDK passes an Agent message to the Host only when its own\n * stores hold the device's task and offer binding (`packages/cloud` `inbound.ts`), which this export does not carry and\n * no code moves.\n *\n * Each receipt, current or earlier, is the same fact as the K8 accepted reply of its task id, so the two must agree. A\n * `reserved` intent is in generation 0 and was never submitted: K4 begins a new generation in the transaction that\n * opens it. So K4 `attempts` is not carried: it is `generation + 1` once the intent began, and 0 while `reserved`.\n *\n * The scheduler cursors of a concluded row are not carried either (#975 D6, the one exception to \"no defaults\"): K4\n * `phase` and `notBefore`, H `tries`, `next_at`, `reconcile_at` and `last_error`. Nothing reads them on a concluded row,\n * so a target writes its own initial values of a new row.\n */\nexport interface IntentRecord {\n key: string; source: 'user' | 'bot' | 'routine'; handler?: string; ordinal: number;\n taskId: string; generation: number; input: Json; waitUntil: number; retry: RetryPolicy;\n submission: 'reserved' | 'uncertain' | 'delivered'; started: boolean; attempt?: Json; terminal?: Json;\n messageReceipt?: MessageReceipt; earlierExecutions: ExecutionRecord[];\n preparationError?: string; memoryBlocked?: NonNullable<Intent['memoryBlocked']>;\n cancelReason?: 'expired' | 'cancelled'; retryUntil?: number; conclusion: Conclusion;\n}\n/**\n * A routine: L K4 `routines`, H `routine`. `ordinal` is its position in the section, exactly 0 to n - 1: K4 stores only the\n * insertion order. `nextAt` is the planned slot. The schedule retry fields and `lastError` are K4's pacing of a slot past\n * the SDK's furthest wake, and `lastError` is never cleared.\n */\nexport interface RoutineRecord {\n id: string; ordinal: number; definition: RoutineDefinition; pending?: RoutineDefinition;\n lifecycle: Routine['lifecycle']; status: Routine['status']; nextAt: number | null; calendarErrors?: NonNullable<Routine['calendarErrors']>;\n scheduleRetryAt?: number; scheduleRetryCount?: number; lastError?: NonNullable<Routine['lastError']>;\n}\n/**\n * An occurrence: L K4 `occurrences`, H `occurrence`, with `ordinal` its position as a routine's. `job` is a Host job's tries and\n * summary, `null` for an occurrence hook. `conclusion` is set only on one with no intent; a promoted one has its intent's.\n * K4 `attempts` is not carried: it is its intent's, or 0. `slotReplayCount` counts redelivered wakes of its slot.\n */\nexport interface OccurrenceRecord {\n key: string; ordinal: number; routineId: string; definitionVersion: number; trigger: Occurrence['trigger'];\n recordedAt: number; nextAt: number | null; job: { attempts: number; summary?: Json } | null; executionSuperseded: boolean;\n conclusion?: Conclusion; slotReplayCount?: number;\n}\n/** A pending Host job of an open occurrence. The target runs it again, as K4 does after a crash. */\nexport interface OutboxRecord { kind: 'host-job'; occurrenceKey: string }\n/** A permanent or expiring tombstone in the K4 scheme: the digest of the retired identity, by kind. */\nexport interface TombstoneRecord { kind: 'intent' | 'row' | 'slot' | 'application'; digest: string; expiresAt?: number }\n\nexport interface SwitchContent {\n version: typeof SWITCH_EXPORT_VERSION; source: 'L' | 'H'; domain: string; devices: SwitchDevice[]; exportedAt: number;\n /**\n * The live state. The source Host's owner records (L `topology`, L `hostIntents`, now on each intent) and L's switch\n * records (`switchExport`, `switchImport`) are not part of it.\n */\n collaboration: CollaborationState;\n archived: ArchivedRecord[]; intents: IntentRecord[]; routines: RoutineRecord[]; occurrences: OccurrenceRecord[];\n outbox: OutboxRecord[]; tombstones: TombstoneRecord[];\n}\n/** The count and digest of each section, and `digest` over them and the header: the identity of one export. */\nexport interface SwitchManifest { counts: Record<SwitchSection, number>; digests: Record<SwitchSection, string>; digest: string }\nexport interface SwitchExport extends SwitchContent { manifest: SwitchManifest }\n\n/**\n * K4 `attempts`, which the format does not carry (#975 D5): one per generation begun, so 0 while the intent is `reserved`\n * and `generation + 1` once it began. An occurrence has its intent's, and 0 without one. Both builders and both importers\n * use it.\n */\nexport function switchAttempts(intent: Pick<IntentRecord, 'submission' | 'generation'> | undefined): number {\n return intent === undefined || intent.submission === 'reserved' ? 0 : intent.generation + 1;\n}\n\nexport type SwitchExportRefusal = 'invalid' | 'unsorted' | 'duplicate' | 'reference' | 'receipt_mismatch' | 'owner_record' | 'device_missing' | 'open_work'\n | 'home_sent' | 'projection_pending' | 'card_call' | 'execution_routine' | 'manifest';\n/** An export that the format refuses. Nothing may be imported or committed from it. */\nexport class SwitchExportError extends Error {\n readonly code = 'switch_export_refused' as const;\n constructor(readonly reason: SwitchExportRefusal, message: string) { super(message); this.name = 'SwitchExportError'; }\n}\n\ntype ListSection = Exclude<SwitchSection, 'collaboration'>;\n/** The identity that orders each section and must be unique in it. */\nconst IDENTITY: { [S in ListSection]: (row: SwitchContent[S][number]) => Json } = {\n archived: row => [(row as ArchivedRecord).namespace, (row as ArchivedRecord).id],\n intents: row => (row as IntentRecord).key,\n routines: row => (row as RoutineRecord).id,\n occurrences: row => (row as OccurrenceRecord).key,\n outbox: row => [(row as OutboxRecord).kind, (row as OutboxRecord).occurrenceKey],\n tombstones: row => [(row as TombstoneRecord).kind, (row as TombstoneRecord).digest],\n};\nconst LISTS = SWITCH_SECTIONS.filter((section): section is ListSection => section !== 'collaboration');\nconst HEADER = ['version', 'source', 'domain', 'devices', 'exportedAt'] as const;\nconst compare = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;\n\n/**\n * Seals the old owner's content: checks it, orders each section by its identity and computes the manifest. Returns a new\n * document; the content is not changed. Throws `SwitchExportError` for content that no target may import.\n */\nexport function sealSwitchExport(content: SwitchContent): SwitchExport {\n // Before the clone, which would turn a class instance into a plain object that `validateJson` accepts.\n checkContent(content, [...HEADER, ...SWITCH_SECTIONS]);\n const sealed = structuredClone(content);\n sealed.devices.sort((a, b) => compare(a.deviceId, b.deviceId));\n for (const section of LISTS) {\n const key = IDENTITY[section] as (row: unknown) => Json;\n (sealed[section] as unknown[]).sort((a, b) => compare(canonical(key(a)), canonical(key(b))));\n }\n checkOrder(sealed);\n return { ...sealed, manifest: manifestOf(sealed) };\n}\n\n/**\n * Verifies a document before an import, and the new owner's read-back after it: the format checks, each section in its\n * one order with unique identities, and the manifest recomputed from the content. Returns the manifest.\n */\nexport function verifySwitchExport(document: SwitchExport): SwitchManifest {\n checkContent(document, [...HEADER, ...SWITCH_SECTIONS, 'manifest']);\n ensure(keys(document.manifest, ['counts', 'digests', 'digest']) && keys(document.manifest.counts, SWITCH_SECTIONS)\n && keys(document.manifest.digests, SWITCH_SECTIONS), 'manifest keys');\n checkOrder(document);\n const manifest = manifestOf(document);\n if (canonical(manifest) !== canonical(document.manifest)) {\n throw new SwitchExportError('manifest', `Switch export manifest does not match its content: ${document.manifest.digest} != ${manifest.digest}`);\n }\n return manifest;\n}\n\nfunction manifestOf(content: SwitchContent): SwitchManifest {\n const counts = {} as Record<SwitchSection, number>, digests = {} as Record<SwitchSection, string>;\n counts.collaboration = 1;\n // The insertion order of the state's maps is state: K8 reads Turns in that order for context (`rules/context.ts`) and\n // retention (`retention.ts`), and H keeps it as each row's `ordinal`. `canonical` sorts keys, so the digest covers the\n // JSON text, which keeps it.\n digests.collaboration = hash(JSON.stringify(content.collaboration));\n for (const section of LISTS) {\n counts[section] = content[section].length;\n digests[section] = hash(content[section]);\n }\n const header = { version: content.version, source: content.source, domain: content.domain, devices: content.devices, exportedAt: content.exportedAt };\n return { counts, digests, digest: hash({ header, counts, digests }) };\n}\n\nfunction checkOrder(content: SwitchContent): void {\n for (let i = 1; i < content.devices.length; i++) {\n if (compare(content.devices[i - 1]!.deviceId, content.devices[i]!.deviceId) > 0) {\n throw new SwitchExportError('unsorted', `Switch export devices are not in id order at ${content.devices[i]!.deviceId}`);\n }\n }\n for (const section of LISTS) {\n const key = IDENTITY[section] as (row: unknown) => Json;\n const ids = (content[section] as unknown[]).map(row => canonical(key(row)));\n for (let i = 1; i < ids.length; i++) {\n const order = compare(ids[i - 1]!, ids[i]!);\n if (order === 0) throw new SwitchExportError('duplicate', `Switch export ${section} repeats ${ids[i]}`);\n if (order > 0) throw new SwitchExportError('unsorted', `Switch export ${section} is not in identity order at ${ids[i]}`);\n }\n }\n}\n\nconst object = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);\nconst text = (value: unknown): value is string => typeof value === 'string' && value.length > 0;\nconst time = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) >= 0;\nconst digestText = (value: unknown): value is string => typeof value === 'string' && /^[0-9a-f]{64}$/.test(value);\n/** Keyed by K4's `Conclusion`, so a new K4 conclusion fails to compile here until the format names it. */\nconst CONCLUSIONS: Record<Conclusion, true> = { succeeded: true, failed: true, declined: true, cancelled: true, expired: true, superseded: true };\nconst conclusionText = (value: unknown) => typeof value === 'string' && Object.hasOwn(CONCLUSIONS, value);\nconst optional = (value: unknown, check: (value: unknown) => boolean) => value === undefined || check(value);\nconst oneOf = (values: readonly string[]) => (value: unknown) => typeof value === 'string' && values.includes(value);\n/** An object with every `required` key and no key outside `required` and `allowed`. */\nfunction keys(value: unknown, required: readonly string[], allowed: readonly string[] = []): value is Record<string, unknown> {\n return object(value) && required.every(key => Object.hasOwn(value, key))\n && Object.keys(value).every(key => required.includes(key) || allowed.includes(key));\n}\nconst receiptShape = (value: unknown) => keys(value, ['messageId', 'contentHash']) && text(value.messageId) && text(value.contentHash);\n/** K4's JSON rule: a value that serialization would change (`NaN`, `undefined`, a class instance) cannot be digested. */\nfunction json(value: unknown): boolean { try { validateJson(value); return true; } catch { return false; } }\nfunction invalid(message: string): never { throw new SwitchExportError('invalid', `Invalid switch export: ${message}`); }\nfunction ensure(ok: boolean, message: string): void { if (!ok) invalid(message); }\nfunction reference(ok: boolean, message: string): void { if (!ok) throw new SwitchExportError('reference', `Switch export ${message}`); }\n\n/** The K4 `RoutineDefinition` keys, with exactly one of its three run kinds. */\nfunction definition(value: unknown, id: string): boolean {\n const runs = ['execution', 'hostJob', 'hostOccurrence'];\n if (!keys(value, ['id', 'version', 'timeZone', 'rule', 'waitMs', 'lateAfterMs'], ['retry', 'endAt', ...runs])) return false;\n const present = runs.filter(run => value[run] !== undefined);\n if (present.length !== 1) return false;\n const run = value[present[0]!];\n return value.id === id && time(value.version) && value.version >= 1 && text(value.timeZone)\n && time(value.waitMs) && time(value.lateAfterMs) && optional(value.endAt, time)\n && optional(value.retry, retryPolicy)\n && (present[0] === 'execution' ? object(run) : keys(run, ['type', 'input']) && text(run.type));\n}\nfunction routineRecord(row: unknown): boolean {\n return keys(row, ['id', 'ordinal', 'definition', 'lifecycle', 'status', 'nextAt'],\n ['pending', 'calendarErrors', 'scheduleRetryAt', 'scheduleRetryCount', 'lastError']) && text(row.id) && time(row.ordinal)\n && definition(row.definition, row.id) && optional(row.pending, pending => definition(pending, row.id as string))\n && oneOf(['active', 'paused', 'completed'])(row.lifecycle)\n && oneOf(['ok', 'schedule_retrying', 'no_occurrence_within_horizon', 'calendar_error'])(row.status)\n && (row.nextAt === null || time(row.nextAt))\n && optional(row.calendarErrors, errors => Array.isArray(errors) && errors.length > 0\n && errors.every(error => keys(error, ['at', 'message'], ['wakeKey']) && time(error.at) && typeof error.message === 'string'\n && optional(error.wakeKey, text)))\n && optional(row.scheduleRetryAt, time) && optional(row.scheduleRetryCount, count => time(count) && count >= 1)\n && optional(row.lastError, error => keys(error, ['code', 'message']) && text(error.code) && typeof error.message === 'string');\n}\nfunction occurrenceRecord(row: unknown): boolean {\n return keys(row, ['key', 'ordinal', 'routineId', 'definitionVersion', 'trigger', 'recordedAt', 'nextAt', 'job', 'executionSuperseded'],\n ['conclusion', 'slotReplayCount'])\n && text(row.key) && time(row.ordinal) && text(row.routineId) && time(row.definitionVersion) && row.definitionVersion >= 1\n && keys(row.trigger, ['kind', 'plannedAt']) && oneOf(['scheduled', 'catch_up'])(row.trigger.kind) && time(row.trigger.plannedAt)\n && time(row.recordedAt) && (row.nextAt === null || time(row.nextAt))\n && (row.job === null || keys(row.job, ['attempts'], ['summary']) && time(row.job.attempts))\n && typeof row.executionSuperseded === 'boolean' && optional(row.conclusion, conclusionText)\n && optional(row.slotReplayCount, count => time(count) && count >= 1);\n}\n/** A policy with exactly K4's keys that K4 `validateRetry` accepts. */\nfunction retryPolicy(retry: unknown): retry is RetryPolicy {\n if (!keys(retry, ['maxAttempts', 'delaysMs', 'retryFailures']) || !Array.isArray(retry.delaysMs)) return false;\n try { validateRetry(retry as unknown as RetryPolicy); return true; } catch { return false; }\n}\nconst executionShape = (row: Record<string, unknown>) => typeof row.started === 'boolean'\n && optional(row.attempt, object) && optional(row.terminal, object) && optional(row.messageReceipt, receiptShape);\nfunction intentRecord(row: unknown): boolean {\n return keys(row, ['key', 'source', 'ordinal', 'taskId', 'generation', 'input', 'waitUntil', 'retry', 'submission', 'started',\n 'earlierExecutions', 'conclusion'], ['handler', 'attempt', 'terminal', 'messageReceipt', 'preparationError', 'memoryBlocked', 'cancelReason', 'retryUntil'])\n && text(row.key) && oneOf(['user', 'bot', 'routine'])(row.source) && optional(row.handler, text) && time(row.ordinal)\n && digestText(row.taskId) && time(row.generation) && time(row.waitUntil)\n // The target derives `agent` from the device and Agent of the frozen input, plain or sealed (K4 `agentKey`).\n && keys(row.input, ['taskId', 'deviceId', 'payload'], ['agentMessageContext']) && text(row.input.deviceId) && object(row.input.payload)\n && object(row.input.payload.agentRef) && text(row.input.payload.agentRef.agentId)\n // K4 opens a generation only for a retry within `maxAttempts` (`core.ts` reconcile and begin), and its policy is\n // bounded by `validateRetry`, so the receipt check below walks at most 100 generations.\n && retryPolicy(row.retry) && row.generation < row.retry.maxAttempts\n && oneOf(['reserved', 'uncertain', 'delivered'])(row.submission) && executionShape(row)\n // Never submitted, so nothing came back (K4 `admit`; `begin` moves it to `uncertain`).\n && (row.submission !== 'reserved' || row.generation === 0 && !row.started && row.attempt === undefined && row.terminal === undefined\n && row.messageReceipt === undefined)\n && Array.isArray(row.earlierExecutions) && row.earlierExecutions.length === row.generation\n // K4 opens the next generation only from backoff, which `finish` enters after it stores the terminal and attempt.\n && row.earlierExecutions.every(entry => keys(entry, ['submission', 'started', 'attempt', 'terminal'], ['messageReceipt'])\n && oneOf(['uncertain', 'delivered'])(entry.submission) && executionShape(entry))\n && optional(row.preparationError, text)\n && optional(row.memoryBlocked, blocked => keys(blocked, ['resume', 'reason']) && oneOf(['queued', 'backoff'])(blocked.resume)\n && typeof blocked.reason === 'string')\n && optional(row.cancelReason, oneOf(['expired', 'cancelled'])) && optional(row.retryUntil, time) && optional(row.conclusion, conclusionText);\n}\n\nfunction checkContent(content: SwitchContent, top: readonly string[]): void {\n ensure(keys(content, top), 'document keys');\n ensure(json(content), 'not JSON');\n ensure(content.version === SWITCH_EXPORT_VERSION, `version ${String(content.version)}`);\n ensure(content.source === 'L' || content.source === 'H', 'source');\n ensure(text(content.domain), 'domain');\n ensure(time(content.exportedAt), 'exportedAt');\n ensure(Array.isArray(content.devices) && content.devices.length > 0, 'devices');\n for (const device of content.devices) {\n ensure(keys(device, ['deviceId', 'frozenRevision']) && text(device.deviceId) && time(device.frozenRevision) && device.frozenRevision >= 1, 'device');\n }\n if (new Set(content.devices.map(device => device.deviceId)).size !== content.devices.length) {\n throw new SwitchExportError('duplicate', 'Switch export lists a device twice');\n }\n for (const section of LISTS) ensure(Array.isArray(content[section]), section);\n checkCollaboration(content);\n for (const row of content.archived) {\n ensure(keys(row, ['namespace', 'id', 'body'], ['expiresAt']) && text(row.namespace) && text(row.id) && optional(row.expiresAt, time), 'archived row');\n }\n for (const row of content.intents) {\n // An intent with no conclusion fails the shape too; report it as the open work it is.\n if (object(row) && row.conclusion === undefined) throw new SwitchExportError('open_work', `Switch export has an open intent: ${String(row.key)}`);\n ensure(intentRecord(row), 'intent');\n }\n for (const row of content.routines) {\n ensure(routineRecord(row), 'routine');\n // K8 holds only Turn and Host intents (#954 C): L refuses execution routines (`host.ts` executionRoutines), H at create.\n if (row.definition.execution !== undefined || row.pending?.execution !== undefined) {\n throw new SwitchExportError('execution_routine', `Switch export has an execution routine, which K8 domains do not run: ${row.id}`);\n }\n }\n for (const row of content.occurrences) ensure(occurrenceRecord(row), 'occurrence');\n for (const row of content.outbox as unknown[]) {\n if (object(row) && row.kind === 'projection') {\n throw new SwitchExportError('projection_pending', `Switch export has a pending projection; flush it first: ${String(row.id)}`);\n }\n ensure(keys(row, ['kind', 'occurrenceKey']) && row.kind === 'host-job' && text(row.occurrenceKey), 'outbox row');\n }\n for (const row of content.tombstones) {\n ensure(keys(row, ['kind', 'digest'], ['expiresAt']) && oneOf(['intent', 'row', 'slot', 'application'])(row.kind) && digestText(row.digest)\n && optional(row.expiresAt, time), 'tombstone');\n }\n checkReferences(content);\n}\n\n/** Each record that names another names one in the export, and each identity that K4 derives matches its source. */\nfunction checkReferences(content: SwitchContent): void {\n for (const section of ['intents', 'routines', 'occurrences'] as const) {\n const ordinals = content[section].map(row => row.ordinal);\n if (new Set(ordinals).size !== ordinals.length) throw new SwitchExportError('duplicate', `Switch export ${section} repeats an ordinal`);\n }\n // A routine's or occurrence's ordinal is its position: what moves is their order, which is all K4 stores (its insertion\n // order). An intent keeps its source value, K4 `sequence` or H `ordinal`, which may have gaps.\n for (const section of ['routines', 'occurrences'] as const) {\n const ordinals = content[section].map(row => row.ordinal).sort((a, b) => a - b);\n ensure(ordinals.every((ordinal, position) => ordinal === position), `${section} ordinals are not their positions 0 to ${ordinals.length - 1}`);\n }\n const occurrences = new Map(content.occurrences.map(row => [row.key, row]));\n const occurrenceOfIntent = new Map(content.occurrences.map(row => [occurrenceIntentKey(row.key), row.key]));\n const promoted = new Set<string>();\n for (const row of content.intents) {\n reference(row.taskId === taskIdOf(row.key, row.generation), `intent ${row.key} has task id ${row.taskId}, not that of generation ${row.generation}`);\n ensure((row.input as { taskId?: unknown }).taskId === row.taskId, `intent ${row.key} input is not frozen for its task id`);\n // K4's own test for an occurrence intent; any other key is a Host's.\n if (isOccurrenceIntentKey(row.key)) {\n const key = occurrenceOfIntent.get(row.key);\n reference(key !== undefined, `intent ${row.key} names no occurrence of the export`);\n promoted.add(key!);\n }\n }\n const routineById = new Map(content.routines.map(row => [row.id, row]));\n const pendingJobs = new Set(content.outbox.map(row => row.occurrenceKey));\n const slots = new Set<string>();\n for (const row of content.occurrences) {\n const routine = routineById.get(row.routineId);\n reference(routine !== undefined, `occurrence ${row.key} names no routine of the export: ${row.routineId}`);\n reference(row.key === hash([row.routineId, row.definitionVersion, row.trigger]), `occurrence ${row.key} is not the key of its routine slot and trigger`);\n // One occurrence per slot: the target derives the slot from it.\n const slot = routineWakeKey(row.routineId, row.definitionVersion, row.trigger.plannedAt);\n if (slots.has(slot)) throw new SwitchExportError('duplicate', `Switch export has two occurrences of the slot of ${row.key}`);\n slots.add(slot);\n // A promoted occurrence's conclusion is its intent's, which K4 copies and H does not store.\n ensure(!(promoted.has(row.key) && row.conclusion !== undefined), `occurrence ${row.key} has an intent and its own conclusion`);\n // By the routine's run kind, which a version cannot change (K4 `routines.ts` updateRoutine). A Host job's outbox row\n // goes in the step that concludes or promotes its occurrence (K4 `core.ts` runHostJobs, `routines.ts`; H `store.ts`).\n if (routine!.definition.hostJob) {\n // K8 never promotes one (#954): L runs K4 with `hostJobExecution: 'fail'`, and H concludes such a result `failed`\n // (`store.ts` settleHostJob), so a job result with an execution concludes the occurrence `failed` on both Hosts.\n ensure(row.job !== null && !promoted.has(row.key) && pendingJobs.has(row.key) === (row.conclusion === undefined),\n `Host job occurrence ${row.key} is not promoted, and has a pending job exactly when it is open`);\n } else ensure(row.job === null, `occurrence ${row.key} has a Host job, but its routine runs a hook`);\n }\n // The K8 accepted reply of a task, live or retained (#798), is the same fact as the K4 message receipt of that task.\n const archivedReplies = new Map(content.archived.filter(row => row.namespace === 'replies').map(row => [row.id, row.body]));\n const replyOf = (taskId: string) => (content.collaboration.replies as Record<string, unknown>)[taskId] ?? archivedReplies.get(taskId);\n for (const row of content.intents) {\n // Every generation of the intent, current and earlier: a receipt and a K8 reply of its task id come together or not at all.\n const receipts = [...row.earlierExecutions.map(entry => entry.messageReceipt), row.messageReceipt];\n for (let generation = 0; generation <= row.generation; generation++) {\n const reply = replyOf(taskIdOf(row.key, generation)), receipt = receipts[generation];\n const same = receipt === undefined ? reply === undefined\n : object(reply) && reply.messageId === receipt.messageId && reply.contentHash === receipt.contentHash;\n if (!same) {\n throw new SwitchExportError('receipt_mismatch', `Switch export intent ${row.key} generation ${generation} has a message receipt that differs from its K8 reply`);\n }\n }\n }\n for (const row of content.outbox) {\n reference(occurrences.get(row.occurrenceKey)?.job != null, `Host job ${row.occurrenceKey} names no Host job occurrence`);\n }\n}\n\n/**\n * The K8 state keys (`model.ts`). The source's owner records (`topology`, `hostIntents`) and L's switch records\n * (`switchExport`, `switchImport`) are refused as `owner_record`.\n */\nconst COLLABORATION_KEYS = ['version', 'team', 'turns', 'budgets', 'delegations', 'batches', 'units', 'replies', 'schemas', 'questions', 'cards',\n 'rejected', 'audit', 'sequence'];\nconst COLLABORATION_OPTIONAL = ['inputs', 'inputBatches', 'channel', 'revision', 'commands', 'cardCalls', 'wouldDo', 'dreams'];\n\n/**\n * The live state of a drained domain: no owner record of the source, each routine Turn keyed by its occurrence's intent\n * key, every live Bot on a device of the export, no Turn or input batch left open, no Agent home write that may have\n * reached a device, and no card call in flight.\n */\nfunction checkCollaboration(content: SwitchContent): void {\n const state = content.collaboration;\n ensure(object(state), 'collaboration state');\n if (state.topology !== undefined) throw new SwitchExportError('owner_record', 'Switch export carries the source owner records (topology)');\n if (state.hostIntents !== undefined) throw new SwitchExportError('owner_record', 'Switch export carries L hostIntents; each intent carries its handler');\n if (state.switchExport !== undefined || state.switchImport !== undefined) {\n throw new SwitchExportError('owner_record', 'Switch export carries an L switch record (switchExport or switchImport)');\n }\n ensure(keys(state, COLLABORATION_KEYS, COLLABORATION_OPTIONAL) && state.version === 3 && object(state.team) && object(state.team.bots)\n && Array.isArray(state.team.homeOperations) && object(state.turns) && optional(state.inputBatches, object) && optional(state.cardCalls, object)\n && optional(state.wouldDo, object),\n 'collaboration state');\n for (const bot of Object.values(state.team.bots)) ensure(object(bot) && object(bot.execution) && text(bot.execution.deviceId), 'bot');\n for (const turn of Object.values(state.turns)) {\n ensure(object(turn), 'turn');\n // A routine Turn's id is its occurrence's intent key, which K8 reads the occurrence from (`routineOccurrence`).\n if (turn.source === 'routine') ensure(typeof turn.id === 'string' && isOccurrenceIntentKey(turn.id), `routine Turn ${String(turn.id)} names no occurrence`);\n }\n for (const batch of Object.values(state.inputBatches ?? {})) ensure(object(batch), 'input batch');\n // A row without its Turn is the shape before #1756: migrate the source first (`migrateWouldDo`, H `migrate()`).\n for (const row of Object.values(state.wouldDo ?? {})) ensure(object(row) && text(row.turnId), 'would-do row without turnId');\n for (const op of state.team.homeOperations) ensure(object(op), 'home operation');\n const devices = new Set(content.devices.map(device => device.deviceId));\n for (const bot of Object.values(state.team.bots)) {\n if (!bot.archived && !devices.has(bot.execution.deviceId)) {\n throw new SwitchExportError('device_missing', `Bot ${bot.id} runs on device ${bot.execution.deviceId}, which the export does not move`);\n }\n }\n for (const turn of Object.values(state.turns)) {\n if (!turn.conclusion) throw new SwitchExportError('open_work', `Switch export has an open Turn: ${turn.id}`);\n }\n for (const batch of Object.values(state.inputBatches ?? {})) {\n if (batch.state === 'open') throw new SwitchExportError('open_work', `Switch export has an open input batch: ${batch.id}`);\n }\n for (const op of state.team.homeOperations) {\n // A write that may have reached a device is the old owner's to settle before the export (#957); only an unsent one moves.\n if (op.status === 'pending' && op.sent === true) {\n throw new SwitchExportError('home_sent', `Switch export has a pending Agent home write that may have been sent: ${op.sequence}`);\n }\n }\n if (Object.keys(state.cardCalls ?? {}).length) throw new SwitchExportError('card_call', 'Switch export has a card call in flight');\n}\n\n/** The header fields of a document: the source's, also on the target's read-back. */\nexport type SwitchHeader = Pick<SwitchContent, 'source' | 'domain' | 'devices' | 'exportedAt'>;\n/** What a new owner returns after its read-back: the digest the old owner commits away on. */\nexport interface SwitchReceipt { digest: string; devices: string[] }\n/**\n * The export record of an old owner (an L ledger or `scope.switch_export` of H): from the export on, also after the\n * commit, so the domain keeps the exported state. `devices` and `exportedAt` are the document's header.\n */\nexport interface SwitchExportMark { digest: string; exportedAt: number; devices: SwitchDevice[] }\n\n/** The domain was exported for a switch, so its owner writes nothing to it. Abort the switch to resume it. Nothing was written. */\nexport class SwitchExportedError extends Error {\n readonly code = 'switch_exported' as const;\n constructor(readonly digest: string) {\n super(`The domain was exported for a switch (${digest}); it writes nothing until the switch is aborted`);\n this.name = 'SwitchExportedError';\n }\n}\n/** The domain holds a switch import that is not committed yet, so no work runs on it. Nothing was written. */\nexport class SwitchImportedError extends Error {\n readonly code = 'switch_imported' as const;\n constructor(readonly digest: string) {\n super(`The domain holds the switch import ${digest}; commit it or discard it first`);\n this.name = 'SwitchImportedError';\n }\n}\n/** The device is frozen for an owner switch. A retry after the switch may succeed. */\nexport class DeviceSwitchingError extends Error {\n readonly code = DEVICE_SWITCHING;\n constructor(readonly deviceId: string, readonly target: 'L' | 'H', readonly revision: number) {\n super(`Device ${deviceId} is switching to ${target}`);\n this.name = 'DeviceSwitchingError';\n }\n}\n\n/** A stored export mark, checked field by field: a malformed one fails closed. */\nexport function exportMarkOf(value: unknown): SwitchExportMark {\n const mark = value as SwitchExportMark;\n const valid = typeof value === 'object' && value !== null && Object.keys(value).sort().join(',') === 'devices,digest,exportedAt'\n && typeof mark.digest === 'string' && Number.isSafeInteger(mark.exportedAt) && Array.isArray(mark.devices) && mark.devices.length > 0\n && mark.devices.every(device => !!device && Object.keys(device).sort().join(',') === 'deviceId,frozenRevision'\n && typeof device.deviceId === 'string' && Number.isSafeInteger(device.frozenRevision) && device.frozenRevision > 0);\n if (!valid) throw new Error('Invalid switch export record');\n return mark;\n}\n","import { hash, type LedgerState } from '@byok-sdk/server/execution-core';\nimport { stateOf, type CollaborationState } from './model.js';\nimport type { HomeOperation } from './team-model.js';\nimport { CommitConflict } from './rules/commit.js';\nimport { DEVICE_NOT_BOUND, type SyncRefusal } from './rules/commands.js';\nimport { DeviceSwitchingError } from './migration.js';\n\n// The L side of the §4.1 owner switch (#957). L is the old owner: it freezes one device, drains it, and then either hands it\n// to H or resumes it. The record is per device, as §4.1 records the mode, and one L Host can own Bots on two devices.\n\n/** The L owner record of one device. A device with no row is `{ mode: 'L', revision: 0 }`: a device defaults to L. */\nexport interface DeviceTopology { mode: 'L' | 'H'; revision: number; switching?: 'H' }\n/** The device's open work that a switch must drain before it commits. */\nexport interface SwitchWork {\n /** Open K4 intents whose execution names the device: Bot Turns, routine occurrences and Host intents. */\n intents: string[];\n /** Turns of the device's Bots with no conclusion and no intent. */\n turns: string[];\n /** Open input batches of the device's Bots. Each becomes a Turn when it seals. */\n batches: string[];\n /** Agent home writes of the device's Bots that were sent and have no terminal readback yet. */\n homeOperations: number[];\n}\n\n/** The device's owner is now H. L never creates work on it again. Same code and reason as H's `DeviceBindingError`. */\nexport class DeviceModeError extends Error {\n readonly code = DEVICE_NOT_BOUND;\n readonly reason = 'mode' as const;\n constructor(readonly deviceId: string, readonly mode: 'H', readonly revision: number) {\n super(`Device ${deviceId} is owned by ${mode}`);\n this.name = 'DeviceModeError';\n }\n}\n\n/** A device id is the Host's string, so the table is read and written through own properties only, never `__proto__`. */\nfunction recordOf(state: CollaborationState, deviceId: string): DeviceTopology | undefined {\n return state.topology && Object.hasOwn(state.topology, deviceId) ? state.topology[deviceId] : undefined;\n}\nexport function deviceTopology(state: CollaborationState, deviceId: string): DeviceTopology {\n const row = recordOf(state, deviceId);\n return row ? { ...row } : { mode: 'L', revision: 0 };\n}\n/** The sync refusal of the device (#956 `deviceRefusal`), or undefined when L may create work on it. */\nexport function deviceRefusal(state: CollaborationState, deviceId: string): Extract<SyncRefusal, 'mode' | 'switching'> | undefined {\n const row = recordOf(state, deviceId);\n return row?.mode === 'H' ? 'mode' : row?.switching ? 'switching' : undefined;\n}\nexport function botDeviceRefusal(state: CollaborationState, botId: string): ReturnType<typeof deviceRefusal> {\n const bot = state.team.bots[botId];\n return bot && deviceRefusal(state, bot.execution.deviceId);\n}\n/** Throws the typed refusal when L must not create work on the device. */\nexport function admitDevice(state: CollaborationState, deviceId: string): void {\n const row = recordOf(state, deviceId);\n if (row?.mode === 'H') throw new DeviceModeError(deviceId, row.mode, row.revision);\n if (row?.switching) throw new DeviceSwitchingError(deviceId, row.switching, row.revision);\n}\n/** An unknown Bot or room is left to the command, which refuses it. */\nexport function admitBot(state: CollaborationState, botId: string): void {\n const bot = state.team.bots[botId];\n if (bot) admitDevice(state, bot.execution.deviceId);\n}\n\nexport function switchWork(s: LedgerState, deviceId: string): SwitchWork {\n const state = stateOf(s.application), onDevice = (botId: string) => state.team.bots[botId]?.execution.deviceId === deviceId;\n return {\n intents: Object.values(s.intents).filter(intent => !intent.conclusion && intent.execution.deviceId === deviceId).map(intent => intent.key),\n turns: Object.values(state.turns).filter(turn => !turn.conclusion && !s.intents[hash(turn.id)] && onDevice(turn.botId)).map(turn => turn.id),\n batches: Object.values(state.inputBatches ?? {}).filter(batch => batch.state === 'open' && onDevice(batch.botId)).map(batch => batch.id),\n // A write that was never sent moves with the exported state.\n homeOperations: state.team.homeOperations.filter(op => op.status === 'pending' && homeSent(op) && op.request.deviceId === deviceId)\n .map(op => op.sequence),\n };\n}\n/** A home write that may have reached the server: marked before its first send. */\nexport function homeSent(op: HomeOperation): boolean {\n return op.sent === true;\n}\nexport function switchDrained(work: SwitchWork): boolean {\n return !work.intents.length && !work.turns.length && !work.batches.length && !work.homeOperations.length;\n}\n\n/**\n * One switch step on the expected revision. Each step raises the revision, so every later step names the one it expects.\n * `freeze`: an L device that is not switching. `commit` and `abort`: a frozen device. A stale revision is a `CommitConflict`.\n */\nexport function switchStep(s: LedgerState, deviceId: string, expectedRevision: number, step: 'freeze' | 'commit' | 'abort'): DeviceTopology {\n const state = stateOf(s.application), row = deviceTopology(state, deviceId);\n if (row.revision !== expectedRevision) {\n throw new CommitConflict('stale_revision', `Device ${deviceId} is at topology revision ${row.revision}, not ${expectedRevision}`);\n }\n if (row.mode !== 'L') throw new DeviceModeError(deviceId, row.mode, row.revision);\n if (step === 'freeze' ? row.switching : !row.switching) throw new Error(`Device ${deviceId} is ${row.switching ? 'already' : 'not'} switching`);\n if (step === 'commit' && !switchDrained(switchWork(s, deviceId))) throw new Error(`Device ${deviceId} still has open work`);\n const next: DeviceTopology = step === 'freeze' ? { mode: 'L', revision: row.revision + 1, switching: 'H' }\n : { mode: step === 'commit' ? 'H' : 'L', revision: row.revision + 1 };\n Object.defineProperty(state.topology ??= {}, deviceId, { value: next, enumerable: true, writable: true, configurable: true });\n return { ...next };\n}\n\n/** A restart reads every row before any pass. A malformed row fails closed. */\nexport function checkTopology(state: CollaborationState): void {\n for (const [deviceId, row] of Object.entries(state.topology ?? {})) {\n const keys = Object.keys(row ?? {}).sort().join(',');\n const valid = !!row && (row.mode === 'L' || row.mode === 'H') && Number.isSafeInteger(row.revision) && row.revision > 0\n && (row.switching === undefined ? keys === 'mode,revision' : row.switching === 'H' && row.mode === 'L' && keys === 'mode,revision,switching');\n if (!valid) throw new Error(`Invalid topology record for device ${deviceId}`);\n }\n}\n","import { agentKey, canonical, frozenInput, hash, isOccurrenceIntentKey, occurrenceIntentKey, parseRoutineWakeKey, routineWakeKey, taskId,\n type HostLedger, type Intent, type Json, type LedgerDump, type LedgerState, type Occurrence, type Routine } from '@byok-sdk/server/execution-core';\nimport { stateOf, type CollaborationState } from './model.js';\nimport { exportMarkOf, sealSwitchExport, switchAttempts, SwitchExportedError, SwitchExportError, SwitchImportedError, verifySwitchExport, type ExecutionRecord, type IntentRecord, type OccurrenceRecord, type OutboxRecord,\n type RoutineRecord, type SwitchContent, type SwitchDevice, type SwitchExport, type SwitchExportRefusal, type SwitchHeader, type SwitchReceipt } from './migration.js';\n\n// The L side of the #975 state move. `switchContent` reads an L ledger into the neutral form, both for the old owner's export\n// and for the new owner's read-back, so one function states what an L ledger holds. `switchDump` writes the neutral form\n// into a K4 dump for one tenant. Each value either moves, is derived from values that move (the checks below), or is a\n// named scheduler value of a concluded row or of the SDK's wakes, which a target writes for itself.\n\n/** The import record of a new L owner: from the load until the commit toward L. */\nexport interface SwitchImport { digest: string; devices: string[]; discarding?: true }\n/** Throws while the domain has an export mark. Each L write calls it after its own refusals, so those come first. */\nexport function refuseExported(state: CollaborationState): void {\n if (state.switchExport) throw new SwitchExportedError(state.switchExport.digest);\n}\n/**\n * Throws while the ledger holds a switch import, which is not committed toward L yet: no K8 work runs on it. The switch\n * steps `commitImport` and `discardImport` write it themselves.\n */\nexport function refuseImported(state: CollaborationState): void {\n if (state.switchImport) throw new SwitchImportedError(state.switchImport.digest);\n}\n/**\n * A restart reads the switch records before any write. A ledger with an import is not committed toward L yet, so no\n * `BotCollaboration` may run on it; a malformed export mark fails closed.\n */\nexport function checkSwitchRecords(state: CollaborationState): void {\n refuseImported(state);\n if (state.switchExport !== undefined) exportMarkOf(state.switchExport);\n}\n\n\nconst INTENT_KEYS = ['id', 'key', 'source', 'execution', 'waitUntil', 'retry', 'agent', 'sequence', 'phase', 'generation', 'taskId', 'notBefore', 'attempts'];\nconst INTENT_OPTIONAL = ['memoryBlocked', 'preparationError', 'occurrence', 'retryUntil', 'cancelReason', 'conclusion'];\nconst EXECUTION_KEYS = ['input', 'submission', 'started'], EXECUTION_OPTIONAL = ['messageReceipt', 'attempt', 'terminal'];\nconst ROUTINE_KEYS = ['definition', 'lifecycle', 'status', 'next'];\nconst ROUTINE_OPTIONAL = ['pending', 'scheduleRetryAt', 'scheduleRetryCount', 'lastError', 'calendarErrors'];\nconst OCCURRENCE_KEYS = ['key', 'routineId', 'definitionVersion', 'trigger', 'wakeKey', 'recordedAt', 'nextAt', 'attempts'];\nconst OCCURRENCE_OPTIONAL = ['intentId', 'job', 'hook', 'conclusion', 'slotReplayCount'];\nconst LEDGER_KEYS = ['version', 'sequence', 'scanSequence', 'intents', 'executions', 'routines', 'occurrences', 'slots', 'outbox', 'applied',\n 'application', 'scanWake'];\nconst LEDGER_OPTIONAL = ['memory', 'ignoredWakes'];\n\nfunction refuse(reason: SwitchExportRefusal, message: string): never { throw new SwitchExportError(reason, `Switch export source: ${message}`); }\n/** A stored copy that differs from the value it is derived from. */\nfunction derived(ok: boolean, message: string): void { if (!ok) refuse('reference', message); }\n/** Exact keys: a field that the neutral form does not name would be dropped, so it is refused. */\nfunction exact(value: object, required: readonly string[], optional: readonly string[], what: string): void {\n const own = Object.keys(value);\n if (!required.every(key => own.includes(key)) || !own.every(key => required.includes(key) || optional.includes(key))) {\n refuse('invalid', `${what} has keys ${own.join(', ')}`);\n }\n}\nconst same = (a: unknown, b: unknown) => canonical(a as Json) === canonical(b as Json);\n/** The fields of `source` whose value is not undefined. */\nfunction defined<T extends object>(source: T): Partial<T> {\n return Object.fromEntries(Object.entries(source).filter(([, value]) => value !== undefined)) as Partial<T>;\n}\n\n/** The K8 state of a ledger without the source Host's owner records, which a target writes for itself. */\nfunction liveState(state: CollaborationState): CollaborationState {\n const live = structuredClone(state);\n delete live.topology; delete live.hostIntents; delete live.switchExport; delete live.switchImport;\n return live;\n}\n\n/**\n * Reads an L ledger dump into the neutral form, and refuses a stored copy that differs from the value it is derived from\n * (#975 \"Export builder must check\"). `tenant` names the ledger (its `agent` keys); `header` is the document's.\n */\nexport function switchContent(dump: LedgerDump, tenant: string, header: SwitchHeader): SwitchContent {\n const s = dump.body;\n exact(s, LEDGER_KEYS, LEDGER_OPTIONAL, 'The K4 ledger');\n // D4: memory binds the tenant inside its digests, and K4 cannot load it into another tenant.\n if (s.memory && Object.values(s.memory).some(rows => rows && Object.keys(rows).length) || dump.memoryTombstones.length) {\n refuse('invalid', 'the domain has Agent memory state, which a switch does not move');\n }\n exact(s.application, ['collaboration'], [], 'The K4 application state');\n const state = stateOf(s.application);\n const handlers = state.hostIntents ?? {};\n\n const intents: IntentRecord[] = [], tasks = new Set<string>(), succeeded = new Set<string>();\n for (const [id, intent] of Object.entries(s.intents)) {\n exact(intent, INTENT_KEYS, INTENT_OPTIONAL, `Intent ${intent.key}`);\n if (!intent.conclusion || intent.phase !== 'settled') refuse('open_work', `intent ${intent.key} is open`);\n derived(id === hash(intent.key), `intent ${intent.key} is stored under ${id}`);\n derived(intent.agent === agentKey(tenant, intent.execution), `intent ${intent.key} queues under another tenant`);\n derived(intent.taskId === taskId(intent.key, intent.generation), `intent ${intent.key} task id is not that of its generation`);\n derived(isOccurrenceIntentKey(intent.key) ? intent.occurrence !== undefined && intent.key === occurrenceIntentKey(intent.occurrence)\n : intent.occurrence === undefined,\n `intent ${intent.key} names occurrence ${String(intent.occurrence)}`);\n const current = s.executions[intent.taskId];\n if (!current) refuse('reference', `intent ${intent.key} has no execution`);\n exact(current, EXECUTION_KEYS, EXECUTION_OPTIONAL, `Execution ${intent.taskId}`);\n derived(same(current.input, frozenInput(intent.execution, intent.taskId)), `intent ${intent.key} execution differs from its frozen input`);\n derived(intent.attempts === switchAttempts({ submission: current.submission, generation: intent.generation }), `intent ${intent.key} attempts`);\n tasks.add(intent.taskId);\n const earlierExecutions: ExecutionRecord[] = [];\n for (let generation = 0; generation < intent.generation; generation++) {\n const task = taskId(intent.key, generation), earlier = s.executions[task];\n if (!earlier) refuse('reference', `intent ${intent.key} has no execution of generation ${generation}`);\n exact(earlier, EXECUTION_KEYS, EXECUTION_OPTIONAL, `Execution ${task}`);\n derived(same(earlier.input, frozenInput(intent.execution, task)), `intent ${intent.key} generation ${generation} input differs`);\n if (earlier.submission === 'reserved') refuse('invalid', `intent ${intent.key} generation ${generation} was never begun`);\n // A missing attempt or terminal stays missing, and the format refuses it.\n earlierExecutions.push(defined({ submission: earlier.submission, started: earlier.started, attempt: earlier.attempt as unknown as Json,\n terminal: earlier.terminal as unknown as Json, messageReceipt: earlier.messageReceipt }) as ExecutionRecord);\n tasks.add(task);\n }\n if (intent.conclusion === 'succeeded') succeeded.add(intent.taskId);\n const handler = Object.hasOwn(handlers, intent.key) ? handlers[intent.key]!.handler : undefined;\n intents.push(defined({\n key: intent.key, source: intent.source, handler, ordinal: intent.sequence, taskId: intent.taskId, generation: intent.generation,\n input: current.input as unknown as Json, waitUntil: intent.waitUntil, retry: intent.retry, submission: current.submission, started: current.started,\n attempt: current.attempt as unknown as Json | undefined, terminal: current.terminal as unknown as Json | undefined, messageReceipt: current.messageReceipt,\n earlierExecutions, preparationError: intent.preparationError, memoryBlocked: intent.memoryBlocked, cancelReason: intent.cancelReason,\n retryUntil: intent.retryUntil, conclusion: intent.conclusion,\n }) as IntentRecord);\n }\n // An execution that no intent names, a handler of no intent, or an `applied` entry other than a succeeded current task\n // would be dropped; K4 sets `applied` only with the success settle (`core.ts` terminal).\n for (const task of Object.keys(s.executions)) derived(tasks.has(task), `execution ${task} belongs to no intent`);\n for (const key of Object.keys(handlers)) derived(!!s.intents[hash(key)], `Host intent ${key} has no K4 intent`);\n derived(same(Object.keys(s.applied).sort(), [...succeeded].sort()), 'K4 applied is not the succeeded current tasks');\n\n const routines: RoutineRecord[] = Object.entries(s.routines).map(([id, routine], ordinal) => {\n exact(routine, ROUTINE_KEYS, ROUTINE_OPTIONAL, `Routine ${routine.definition.id}`);\n const { definition } = routine;\n derived(id === hash(definition.id), `routine ${definition.id} is stored under ${id}`);\n if (routine.next) {\n exact(routine.next, ['dedupKey', 'availableAt'], [], `Routine ${definition.id} next wake`);\n const parsed = parseRoutineWakeKey(routine.next.dedupKey);\n derived(parsed?.id === definition.id && parsed.version === definition.version && parsed.at === routine.next.availableAt\n && routine.next.dedupKey === routineWakeKey(definition.id, definition.version, routine.next.availableAt), `routine ${definition.id} next wake key`);\n }\n return defined({\n id: definition.id, ordinal, definition, pending: routine.pending, lifecycle: routine.lifecycle, status: routine.status,\n nextAt: routine.next?.availableAt ?? null, calendarErrors: routine.calendarErrors?.length ? routine.calendarErrors : undefined,\n scheduleRetryAt: routine.scheduleRetryAt, scheduleRetryCount: routine.scheduleRetryCount, lastError: routine.lastError,\n }) as RoutineRecord;\n });\n\n // The format pairs each Host job row with its open occurrence (`migration.ts` checkReferences).\n const slots = new Map<string, string>(), outbox: OutboxRecord[] = [];\n for (const [key, row] of Object.entries(s.outbox)) {\n if (row.kind === 'projection') refuse('projection_pending', `projection ${row.id} is not sent; flush it first`);\n if (row.kind === 'intent') refuse('open_work', `intent ${row.intentId} has a pending submit`);\n if (row.kind !== 'host-job') continue; // `schedule` and `cancel-wake` are this SDK's wakes; a target schedules its own.\n exact(row, ['kind', 'occurrenceKey'], [], `Host job ${row.occurrenceKey}`);\n derived(key === `host-job:${row.occurrenceKey}`, `Host job row ${key}`);\n outbox.push({ kind: 'host-job', occurrenceKey: row.occurrenceKey });\n }\n const occurrences: OccurrenceRecord[] = Object.entries(s.occurrences).map(([key, row], ordinal) => {\n exact(row, OCCURRENCE_KEYS, OCCURRENCE_OPTIONAL, `Occurrence ${key}`);\n derived(row.key === key, `occurrence ${row.key} is stored under ${key}`);\n const parsed = parseRoutineWakeKey(row.wakeKey);\n derived(parsed?.id === row.routineId && parsed.version === row.definitionVersion && parsed.at === row.trigger.plannedAt\n && row.wakeKey === routineWakeKey(row.routineId, row.definitionVersion, row.trigger.plannedAt), `occurrence ${key} wake key`);\n slots.set(hash(row.wakeKey), key);\n const intent = s.intents[hash(occurrenceIntentKey(key))];\n derived(intent ? row.intentId === intent.id : row.intentId === undefined, `occurrence ${key} intent id`);\n derived(row.attempts === switchAttempts(intent && { submission: s.executions[intent.taskId]!.submission, generation: intent.generation }),\n `occurrence ${key} attempts`);\n // A promoted occurrence's conclusion is its intent's (K4 `settle`), so it is not carried.\n derived(intent ? row.conclusion === intent.conclusion : true, `occurrence ${key} conclusion differs from its intent's`);\n if ((row.job === undefined) === (row.hook === undefined)) refuse('invalid', `occurrence ${key} is not exactly one of a Host job and a hook`);\n if (row.job) exact(row.job, ['attempts'], ['summary', 'executionSuperseded'], `Occurrence ${key} job`);\n if (row.hook) exact(row.hook, [], ['executionSuperseded'], `Occurrence ${key} hook`);\n return defined({\n key, ordinal, routineId: row.routineId, definitionVersion: row.definitionVersion, trigger: row.trigger, recordedAt: row.recordedAt,\n nextAt: row.nextAt, job: row.job ? defined({ attempts: row.job.attempts, summary: row.job.summary }) as OccurrenceRecord['job'] : null,\n executionSuperseded: !!(row.job ?? row.hook)!.executionSuperseded, conclusion: intent ? undefined : row.conclusion,\n slotReplayCount: row.slotReplayCount,\n }) as OccurrenceRecord;\n });\n derived(same(Object.entries(s.slots).sort(), [...slots].sort()), 'K4 slots are not one per occurrence');\n\n return {\n version: 1, ...header, collaboration: liveState(state),\n archived: dump.rows.map(row => defined({ namespace: row.namespace, id: row.id, body: row.value, expiresAt: row.expiresAt ?? undefined }) as SwitchContent['archived'][number]),\n intents, routines, occurrences, outbox,\n tombstones: dump.tombstones.map(row => defined({ kind: row.kind, digest: row.identity, expiresAt: row.expiresAt ?? undefined }) as SwitchContent['tombstones'][number]),\n };\n}\n\n/**\n * Writes the neutral form into a K4 dump bound to `tenant`. The K8 owner records the target needs are passed in `owner`.\n * A concluded row gets K4's values of a new row for its scheduler cursors (#975 D6): `phase: 'settled'`, `notBefore: 0`.\n */\nexport function switchDump(content: SwitchContent, tenant: string, owner: Pick<CollaborationState, 'topology' | 'switchImport'>): LedgerDump {\n // K4 keeps routines and occurrences in insertion order, and the format makes their ordinals their positions.\n const byOrdinal = <T extends { ordinal: number }>(rows: readonly T[]) => [...rows].sort((a, b) => a.ordinal - b.ordinal);\n const records = new Map(content.intents.map(row => [row.key, row]));\n const s: LedgerState = { version: 1, sequence: Math.max(0, ...content.intents.map(row => row.ordinal)), scanSequence: 0, intents: {}, executions: {},\n routines: {}, occurrences: {}, slots: {}, outbox: {}, applied: {}, application: {}, scanWake: null };\n const hostIntents: Record<string, { handler: string }> = {};\n for (const row of byOrdinal(content.intents)) {\n const { taskId: _task, ...execution } = row.input as unknown as Intent['execution'] & { taskId: string };\n const intent: Intent = defined({\n key: row.key, source: row.source, execution, waitUntil: row.waitUntil, retry: row.retry, id: hash(row.key), agent: agentKey(tenant, execution),\n sequence: row.ordinal, phase: 'settled', generation: row.generation, taskId: row.taskId, notBefore: 0,\n attempts: switchAttempts(row), memoryBlocked: row.memoryBlocked, preparationError: row.preparationError,\n retryUntil: row.retryUntil,\n cancelReason: row.cancelReason, conclusion: row.conclusion,\n }) as Intent;\n s.intents[intent.id] = intent;\n s.executions[row.taskId] = defined({ input: row.input, submission: row.submission, started: row.started, attempt: row.attempt,\n terminal: row.terminal, messageReceipt: row.messageReceipt }) as unknown as LedgerState['executions'][string];\n row.earlierExecutions.forEach((earlier, generation) => {\n const task = taskId(row.key, generation);\n s.executions[task] = defined({ input: frozenInput(execution, task), ...earlier }) as unknown as LedgerState['executions'][string];\n });\n if (row.conclusion === 'succeeded') s.applied[row.taskId] = true;\n if (row.handler !== undefined) Object.defineProperty(hostIntents, row.key, { value: { handler: row.handler }, enumerable: true, writable: true, configurable: true });\n }\n for (const row of byOrdinal(content.routines)) {\n s.routines[hash(row.id)] = defined({\n definition: row.definition, pending: row.pending, lifecycle: row.lifecycle, status: row.status,\n next: row.nextAt === null ? null : { dedupKey: routineWakeKey(row.id, row.definition.version, row.nextAt), availableAt: row.nextAt },\n calendarErrors: row.calendarErrors, scheduleRetryAt: row.scheduleRetryAt, scheduleRetryCount: row.scheduleRetryCount, lastError: row.lastError,\n }) as Routine;\n }\n for (const row of byOrdinal(content.occurrences)) {\n const wakeKey = routineWakeKey(row.routineId, row.definitionVersion, row.trigger.plannedAt);\n // The occurrence names its intent (K4 `promote`): the format checks that each occurrence intent names one.\n const intent = s.intents[hash(occurrenceIntentKey(row.key))];\n if (intent) intent.occurrence = row.key;\n const superseded = row.executionSuperseded ? { executionSuperseded: true as const } : {};\n s.occurrences[row.key] = defined({\n key: row.key, routineId: row.routineId, definitionVersion: row.definitionVersion, trigger: row.trigger, wakeKey, recordedAt: row.recordedAt,\n nextAt: row.nextAt, intentId: intent?.id, job: row.job ? { ...row.job, ...superseded } : undefined, hook: row.job ? undefined : superseded,\n attempts: switchAttempts(records.get(occurrenceIntentKey(row.key))), conclusion: intent ? intent.conclusion : row.conclusion, slotReplayCount: row.slotReplayCount,\n }) as Occurrence;\n s.slots[hash(wakeKey)] = row.key;\n }\n for (const row of content.outbox) s.outbox[`host-job:${row.occurrenceKey}`] = { kind: 'host-job', occurrenceKey: row.occurrenceKey };\n s.application.collaboration = { ...structuredClone(content.collaboration), ...(Object.keys(hostIntents).length ? { hostIntents } : {}),\n ...defined(owner) } as unknown as Json;\n return {\n version: 1, body: s, memoryTombstones: [],\n tombstones: content.tombstones.map(row => ({ kind: row.kind, identity: row.digest, expiresAt: row.expiresAt ?? null })),\n rows: content.archived.map(row => ({ namespace: row.namespace, id: row.id, value: row.body, expiresAt: row.expiresAt ?? null })),\n };\n}\n\n/** The header of a document, which a read-back copies as it is. */\nconst headerOf = (document: SwitchContent): SwitchHeader =>\n ({ source: document.source, domain: document.domain, devices: document.devices, exportedAt: document.exportedAt });\n/** Seals the content that a ledger holds now, under a given header. */\nexport function sealLedger(ledger: HostLedger, header: SwitchHeader): SwitchExport {\n return sealSwitchExport(switchContent(ledger.dumpForSwitch(), ledger.tenant, header));\n}\n\nconst importOf = (state: CollaborationState): SwitchImport => {\n if (!state.switchImport) throw new Error('This ledger holds no switch import record');\n return state.switchImport;\n};\n\n/**\n * Step 2 of a switch to L (#975): writes an H export into an empty L ledger tenant and verifies it in the same transaction.\n * The document must verify. Each of its devices is recorded as owned by H, with the import record, until `commitImport`.\n * Before the load commits, K4 reads the tenant's rows back, and they must give the document's digest under its header;\n * otherwise nothing is written. Returns the receipt the old owner commits away on. A `BotCollaboration` refuses a ledger\n * with an import, so no work runs on it before the commit.\n */\nexport function importForSwitch(ledger: HostLedger, document: SwitchExport): SwitchReceipt {\n const manifest = verifySwitchExport(document);\n if (document.source !== 'H') throw new SwitchExportError('invalid', `An L owner imports only an H export, not one from ${document.source}`);\n const devices = document.devices.map((device: SwitchDevice) => device.deviceId);\n const topology = {};\n for (const id of devices) Object.defineProperty(topology, id, { value: { mode: 'H', revision: 1 }, enumerable: true, writable: true, configurable: true });\n ledger.loadForSwitch(switchDump(document, ledger.tenant, { topology, switchImport: { digest: manifest.digest, devices } }), readBack => {\n const back = sealSwitchExport(switchContent(readBack, ledger.tenant, headerOf(document))).manifest.digest;\n if (back !== manifest.digest) throw new SwitchExportError('manifest', `The imported ledger reads back as ${back}, not ${manifest.digest}`);\n });\n return { digest: manifest.digest, devices };\n}\n\n/**\n * Step 4 of a switch to L, after the old owner committed away on the receipt: L owns each device of the import. Only the\n * import of this digest that is not being discarded commits. Then a `BotCollaboration` can open the ledger.\n */\nexport function commitImport(ledger: HostLedger, digest: string): void {\n ledger.transaction(s => {\n const state = stateOf(s.application), record = importOf(state);\n if (record.discarding) throw new Error('The switch import is being discarded');\n if (record.digest !== digest) throw new Error(`The switch import is ${record.digest}, not ${digest}`);\n for (const id of record.devices) {\n const row = state.topology && Object.hasOwn(state.topology, id) ? state.topology[id] : undefined;\n if (row?.mode !== 'H' || row.revision !== 1 || row.switching) throw new Error(`Device ${id} is not an imported device`);\n state.topology![id] = { mode: 'L', revision: 2 };\n }\n delete state.switchImport;\n });\n}\n\n/**\n * Deletes an import that was not committed, when the switch does not go ahead: the old owner aborts, or the product\n * decides against it. It first records\n * that the import is being discarded, so `commitImport` refuses it from then on, then deletes the tenant (K4 `discard`).\n * A committed tenant has no import record, so it is refused; no `BotCollaboration` ran work on an uncommitted one.\n */\nexport function discardImport(ledger: HostLedger): void {\n ledger.transaction(s => { importOf(stateOf(s.application)).discarding = true; });\n ledger.discard();\n}\n","import { enqueue, hash, project, promoteOccurrence, taskId, type ApplicationRows, type HostLedger, type Intent, type LedgerState } from '@byok-sdk/server/execution-core';\nimport { stateOf, type Card, type CollaborationState, type Turn } from './model.js';\nimport type { Json } from './rules/turn.js';\nimport { intentFacts } from './delegation.js';\nimport { turnIntentRetired } from './compaction.js';\nimport { concludeRoutineTurn, routineOccurrence, type BotRoutine } from './routines.js';\nimport { dreamIntentIds } from './dream.js';\nimport { syncTurn, type SyncFacts, type SyncOptions } from './rules/sync.js';\nimport { autonomousIntentIds, userFirst } from './rules/priority.js';\nimport { cardCallDue, commitCommand, CONNECTOR_OUTCOME_UNKNOWN, refuseRetired, retiredIdentity, settleCardCall, type AdmittedIds, type Command,\n type CommandPorts } from './rules/commands.js';\nimport type { CommandRecord, CommitRequest, CommitResult } from './rules/commit.js';\nimport { botDeviceRefusal } from './topology.js';\nimport { retainRoots, type RetentionInput, type RetentionLimits, type RetentionResult } from './retention.js';\nimport { refuseExported, refuseImported } from './switch.js';\n\n// The L store of the commit contract (#739 D1): one K4 ledger transaction holds the state change,\n// the command record and the outbox rows. K4 deduplicates terminals and messages, so L records no callback.\n// Retention (#798) moves settled rows into K4 application rows of the same transaction.\n// A sync step (#793 D2b) writes in the transaction of the Host sync. It records no command and keeps the revision.\nexport { CommitConflict, revisionOf, type CommitRequest, type CommitResult, type Disposition, type OutboxIntent } from './rules/commit.js';\nexport type { Command, CommandPorts } from './rules/commands.js';\n\n/**\n * One K8 write to an L ledger in one ledger transaction (#975). It refuses a ledger that holds an uncommitted switch import\n * before the work runs. It refuses while the domain is exported after the work, so a new command on a frozen or H-owned\n * device still gets its device refusal. A refusal the work raises first (a replayed command id, an id conflict,\n * `stale_revision`, `RetentionRefused`) also comes before the export's; each refusal rolls the transaction back.\n */\nexport function writeLedger<T>(ledger: Pick<HostLedger, 'transaction'>, apply: (state: LedgerState, rows: ApplicationRows) => T): T {\n return ledger.transaction((s, rows) => {\n refuseImported(stateOf(s.application));\n const result = apply(s, rows);\n refuseExported(stateOf(s.application));\n return result;\n });\n}\n/**\n * The scope of an L ledger is its tenant. `ports` gets the transaction state, so outbox writes join the commit.\n * Moved command records and tombstones come from K4 application rows of the same transaction (#798).\n */\nexport function commitInLedger(ledger: HostLedger, request: CommitRequest<Command>, ports: (s: LedgerState) => CommandPorts): CommitResult {\n return writeLedger(ledger, (s, rows) => commitInRows(stateOf(s.application), ledger.tenant, request, rows, ports(s)));\n}\n/**\n * One command in a K4 transaction of the ledger with tenant `scope`, which holds `rows`: an owner command, or a K4 outcome,\n * message or occurrence callback.\n */\nexport function commitInRows(state: CollaborationState, scope: string, request: CommitRequest<Command>, rows: ApplicationRows,\n ports: CommandPorts): CommitResult {\n let admitted: AdmittedIds | undefined;\n const result = commitCommand(state, request, { scope, recordCallbacks: false,\n archived: id => rows.get('commands', id) as CommandRecord | undefined, admitted: ids => { admitted = ids; } }, ports);\n refuseRetired(admitted, (namespace, id) => rows.isRetired(namespace, id));\n return result;\n}\n/** One retention call in one ledger transaction. K4 facts come from the same state. */\nexport function retainInLedger(ledger: HostLedger, input: RetentionInput, limits: RetentionLimits): RetentionResult {\n return writeLedger(ledger, (s, rows) => retainRoots(stateOf(s.application), input, limits, {\n hasIntent: turnId => !!s.intents[hash(turnId)],\n occurrenceOpen: turnId => { const occurrence = s.occurrences[routineOccurrence({ id: turnId })]; return !!occurrence && !occurrence.conclusion; },\n }, rows));\n}\nconst wouldDoRowNeedsMigration = (row: { turnId?: string }): boolean => row.turnId === undefined;\nexport function wouldDoNeedsMigration(state: CollaborationState): boolean {\n return Object.values(state.wouldDo ?? {}).some(wouldDoRowNeedsMigration);\n}\n/** The result of `migrateWouldDo`: rows that got their `turnId`, and rows archived because no live Turn owns them. */\nexport interface WouldDoMigration { backfilled: number; archived: number }\n/**\n * The one-shot migration of would-do rows written before #1756, which have no `turnId`. The operator runs it once before\n * the new code serves. Each Turn intent of K4 has the task id `taskId(turnId, generation)` for each of its generations, so\n * the row's task id names its Turn exactly. A row whose intent was compacted, or whose Turn left the state, has no live\n * owner: it moves to the `wouldDo` application rows, as retention would move it, and is counted.\n */\nexport function migrateWouldDo(ledger: HostLedger): WouldDoMigration {\n return writeLedger(ledger, (s, rows) => {\n const state = stateOf(s.application), owners = new Map<string, string>(), result: WouldDoMigration = { backfilled: 0, archived: 0 };\n for (const intent of Object.values(s.intents)) {\n if (!Object.hasOwn(state.turns, intent.key)) continue;\n for (let generation = 0; generation <= intent.generation; generation++) owners.set(taskId(intent.key, generation), intent.key);\n }\n for (const row of Object.values(state.wouldDo ?? {})) {\n if (!wouldDoRowNeedsMigration(row)) continue;\n const turnId = owners.get(row.taskId);\n if (turnId !== undefined) { row.turnId = turnId; result.backfilled++; continue; }\n // SAFETY: The persisted would-do row consists of JSON fields and can be stored as an application row.\n rows.put('wouldDo', row.id, row as unknown as Json);\n delete state.wouldDo![row.id];\n result.archived++;\n }\n return result;\n });\n}\n/**\n * The intents that user input goes ahead of (#1229): a Bot Turn whose source is a routine occurrence or another Bot's\n * request, and a dream (#1475). A self continuation, an answer result or a Bot reply keeps its FIFO position.\n */\nfunction prioritiseUser(s: LedgerState, state: ReturnType<typeof stateOf>, user: Intent): void {\n // K4 keys an intent by `hash(turn.id)`, so the priority rule compares intent ids, not Turn ids.\n const autonomous = autonomousIntentIds(Object.values(state.turns), dreamIntentIds(state));\n const plan = userFirst(Object.values(s.intents), user.id, autonomous, s.sequence);\n if (!plan) return;\n for (const { id, sequence } of plan.assignments) s.intents[id]!.sequence = sequence;\n s.sequence = plan.sequence;\n}\n/**\n * One sync step of one Turn in the L ledger, inside the caller's transaction. The Host sync loop calls it for each Turn.\n * The K4 writes stay here: `enqueue`, `promoteOccurrence`, the intent cancel and the occurrence conclusion.\n * Returns true when the step queued work or concluded an occurrence, so that K4 drains again.\n */\nexport function syncTurnInLedger(ledger: HostLedger, s: LedgerState, rows: ApplicationRows, turn: Turn, options: SyncOptions<BotRoutine>): boolean {\n const facts: SyncFacts = {\n intent: intentFacts(s).intent,\n executionStarted: id => { const row = s.intents[hash(id)]; return !!row && !!s.executions[row.taskId]?.started; },\n retired: id => turnIntentRetired(ledger, s, turn, options.now) ? 'result_retired' : retiredIdentity('turn', id, (namespace, row) => rows.isRetired(namespace, row)) ? 'turn_retired' : undefined,\n // #957: a Turn whose Bot's device is frozen for a switch, or owned by H, is held and never frozen into an intent.\n deviceRefusal: botId => botDeviceRefusal(stateOf(s.application), botId),\n };\n refuseImported(stateOf(s.application));\n const step = syncTurn(stateOf(s.application), turn, facts, options, (key, value) => project(s, key, value));\n const more = applyStep();\n // The caller's transaction rolls the step back on an uncommitted import or an exported domain (#975).\n refuseExported(stateOf(s.application));\n return more;\n function applyStep(): boolean {\n switch (step?.kind) {\n case 'freeze': {\n const intent = enqueue(s, ledger.tenant, step.input);\n // #1229 item 1: a user-source intent goes ahead of the queued, never-submitted routine and bot_request intents\n // of the same Agent FIFO. Submitted work keeps its order and its taskId generation; the order lives in the ledger.\n if (step.input.source === 'user') prioritiseUser(s, stateOf(s.application), intent);\n return true;\n }\n case 'routine': promoteOccurrence(s, ledger.tenant, routineOccurrence(turn), step.execution); return true;\n case 'cancel': s.intents[hash(turn.id)]!.cancelReason = 'cancelled'; return false;\n // A concluded occurrence can make a staged version due, so the next pass drains K4 again.\n case 'ended': return turn.source === 'routine' && concludeRoutineTurn(s, turn);\n default: return false;\n }\n }\n}\n/**\n * L's card call step (#958): at most one connector call per card, as H. For each due card, one transaction claims the call\n * before it runs, and one transaction settles it and drops the claim. A claim that a later pass finds with no settle (a crash\n * or a failed settle after the call) ends the card with `CONNECTOR_OUTCOME_UNKNOWN`, with no second call.\n */\nexport async function callCardsInLedger(ledger: HostLedger, call: (card: Card) => Promise<unknown>): Promise<void> {\n for (const old of Object.values(stateOf(ledger.snapshot().application).cards)) {\n if (!cardCallDue(old)) continue;\n const claimed = writeLedger(ledger, s => {\n const state = stateOf(s.application), card = state.cards[old.id];\n if (!card || !cardCallDue(card)) return false;\n const calls = state.cardCalls ??= {};\n if (!calls[card.id]) return calls[card.id] = true;\n delete calls[card.id];\n settleCardCall(card, { error: new Error(CONNECTOR_OUTCOME_UNKNOWN) });\n return false;\n });\n if (!claimed) continue;\n let outcome: Parameters<typeof settleCardCall>[1];\n try { outcome = { result: await call(old) }; } catch (error) { outcome = { error }; }\n writeLedger(ledger, s => {\n const state = stateOf(s.application);\n delete state.cardCalls![old.id];\n settleCardCall(state.cards[old.id]!, outcome);\n });\n }\n}\n","import type { BotTurnOutcome } from '@byok-sdk/protocol';\nimport { hash, type LedgerState } from '@byok-sdk/server/execution-core';\nimport type { Publish } from './rules/delegation.js';\nimport { addTurn, type CollaborationState, type Turn } from './model.js';\nimport * as rules from './rules/rooms.js';\nimport type { AutonomyGate } from './rules/autonomy.js';\n\n// K8 adapter for the pure room rules in `rules/rooms.ts`.\nexport { DEFAULT_MEMBER_MENTIONS, ROOM_GRACE_MS, memberMentions, memberPresent, roomContext, roomMessageProjection, roomMessages, roomVisibility,\n type MemberMentions, type Mentions, type RoomMessage } from './rules/rooms.js';\nexport { ROOM_CONTEXT_BYTES, ROOM_CONTEXT_MESSAGES } from './rules/rooms.js';\nexport function roomInput(state: CollaborationState, key: string, roomId: string, text: string, mentions: rules.Mentions, publish: Publish,\n from?: string): string {\n return rules.roomInput(state.team, key, roomId, text, mentions, publish, from);\n}\nexport function applySpeech(state: CollaborationState, turn: Turn, document: BotTurnOutcome, taskId: string, now: number, publish: Publish,\n accept: (action: string, work: () => void) => void, gate: AutonomyGate): void {\n rules.applySpeech(state.team, turn.id, document, taskId, now, publish, accept, gate);\n}\n/**\n * Seat facts come from the K4 intent and execution of each seat Turn. A cancel of admitted work sets\n * the K4 `cancelReason`; a seat Turn without an intent fails at once. Then the new seat Turns are added.\n */\nexport function advanceRooms(s: LedgerState, state: CollaborationState, now: number,\n add: (id: string, botId: string, request: string) => void, publish: Publish): void {\n const facts: Record<string, rules.SeatFacts> = {};\n for (const id of Object.keys(state.team.seats)) {\n const intent = s.intents[hash(id)], execution = intent && s.executions[intent.taskId];\n facts[id] = { admitted: !!intent, started: !!execution?.started, conclusion: intent?.conclusion };\n }\n for (const seatId of rules.advanceRoomSeats(state, facts, now, add, publish)) s.intents[hash(seatId)]!.cancelReason = 'cancelled';\n}\n/**\n * The room step and the Turn steps of L's sync (K8 host.ts `sync`). A Turn step can release a seat (a blocked or retired seat\n * Turn), so the room step then runs again and the next seat gets its Turn in this sync, as H's sync does (#876). Only\n * `reserve` sets `released = false`, and a sync never reserves, so each seat adds at most one more round. Returns whether any\n * Turn step returned true.\n */\nexport function advanceRoomsAndTurns(s: LedgerState, state: CollaborationState, now: number, step: (turn: Turn) => boolean,\n publish: Publish): boolean {\n const released = () => Object.values(state.team.seats).filter(seat => seat.released).length;\n let changed = false, before: number;\n do {\n advanceRooms(s, state, now, (id, botId, request) => addTurn(state, rules.seatTurn(id, botId, request)), publish);\n before = released();\n for (const turn of Object.values(state.turns)) changed = step(turn) || changed;\n } while (released() > before);\n return changed;\n}\n"]}