@ixo/editor 6.34.0 → 6.35.1

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 (48) hide show
  1. package/dist/{BidFlowDetail-TJCJBJZZ.js → BidFlowDetail-U2SX5M7F.js} +3 -3
  2. package/dist/{ClaimFlowDetail-UVEQMEI5.js → ClaimFlowDetail-I4OQSHAB.js} +3 -3
  3. package/dist/{CollectionLifecycleFlowDetail-WFCSVIIG.js → CollectionLifecycleFlowDetail-LQHKB227.js} +3 -3
  4. package/dist/{CollectionUsersFlowDetail-ZLCJBWHG.js → CollectionUsersFlowDetail-HELGXFYN.js} +5 -5
  5. package/dist/{EvaluateBidFlowDetail-2S2N4YTW.js → EvaluateBidFlowDetail-YR7PK7EG.js} +5 -5
  6. package/dist/{EvaluateClaimFlowDetail-QYR7PJRD.js → EvaluateClaimFlowDetail-FEUMB37M.js} +4 -4
  7. package/dist/{IdentityCreateFlowDetail-WGKO43IH.js → IdentityCreateFlowDetail-4TE6UCEB.js} +2 -2
  8. package/dist/{IidCreateFlowDetail-6M32S6XS.js → IidCreateFlowDetail-HPVZAHVY.js} +2 -2
  9. package/dist/{KycVerifyFlowDetail-EWOMXSD3.js → KycVerifyFlowDetail-FEU43HML.js} +2 -2
  10. package/dist/{OracleConfigureOracleFlowDetail-73BHAN76.js → OracleConfigureOracleFlowDetail-MIBXUEKC.js} +2 -2
  11. package/dist/{OracleStoreSecretsAndConfigFlowDetail-BFV2EHLT.js → OracleStoreSecretsAndConfigFlowDetail-HQU3UKEB.js} +2 -2
  12. package/dist/{OracleStoreSecretsFlowDetail-DNNOPHVA.js → OracleStoreSecretsFlowDetail-5RXWQ3KA.js} +2 -2
  13. package/dist/{ProposalCreateFlowDetail-4VZZPAWH.js → ProposalCreateFlowDetail-2FCRCNYV.js} +2 -2
  14. package/dist/{chunk-HRRI4BLF.js → chunk-5E6Z6JJN.js} +1 -1
  15. package/dist/chunk-5E6Z6JJN.js.map +1 -0
  16. package/dist/{chunk-JBBFSORW.js → chunk-BLFBVFHV.js} +2 -2
  17. package/dist/{chunk-JBBFSORW.js.map → chunk-BLFBVFHV.js.map} +1 -1
  18. package/dist/{chunk-3O42FYT3.js → chunk-F5GTFCYV.js} +2 -2
  19. package/dist/chunk-F5GTFCYV.js.map +1 -0
  20. package/dist/{chunk-2WPEATI7.js → chunk-JB6ASLUJ.js} +2 -2
  21. package/dist/{chunk-3XSLBJYI.js → chunk-MZIBZ5FY.js} +2 -2
  22. package/dist/{chunk-6ESTNTSH.js → chunk-WZW2WDJM.js} +2 -2
  23. package/dist/{chunk-D2CQPNQG.js → chunk-YAY3ZF3O.js} +16 -16
  24. package/dist/chunk-YAY3ZF3O.js.map +1 -0
  25. package/dist/core/index.cjs.map +1 -1
  26. package/dist/core/index.js +3 -3
  27. package/dist/index.js +4 -4
  28. package/dist/mantine/index.js +3 -3
  29. package/package.json +1 -1
  30. package/dist/chunk-3O42FYT3.js.map +0 -1
  31. package/dist/chunk-D2CQPNQG.js.map +0 -1
  32. package/dist/chunk-HRRI4BLF.js.map +0 -1
  33. /package/dist/{BidFlowDetail-TJCJBJZZ.js.map → BidFlowDetail-U2SX5M7F.js.map} +0 -0
  34. /package/dist/{ClaimFlowDetail-UVEQMEI5.js.map → ClaimFlowDetail-I4OQSHAB.js.map} +0 -0
  35. /package/dist/{CollectionLifecycleFlowDetail-WFCSVIIG.js.map → CollectionLifecycleFlowDetail-LQHKB227.js.map} +0 -0
  36. /package/dist/{CollectionUsersFlowDetail-ZLCJBWHG.js.map → CollectionUsersFlowDetail-HELGXFYN.js.map} +0 -0
  37. /package/dist/{EvaluateBidFlowDetail-2S2N4YTW.js.map → EvaluateBidFlowDetail-YR7PK7EG.js.map} +0 -0
  38. /package/dist/{EvaluateClaimFlowDetail-QYR7PJRD.js.map → EvaluateClaimFlowDetail-FEUMB37M.js.map} +0 -0
  39. /package/dist/{IdentityCreateFlowDetail-WGKO43IH.js.map → IdentityCreateFlowDetail-4TE6UCEB.js.map} +0 -0
  40. /package/dist/{IidCreateFlowDetail-6M32S6XS.js.map → IidCreateFlowDetail-HPVZAHVY.js.map} +0 -0
  41. /package/dist/{KycVerifyFlowDetail-EWOMXSD3.js.map → KycVerifyFlowDetail-FEU43HML.js.map} +0 -0
  42. /package/dist/{OracleConfigureOracleFlowDetail-73BHAN76.js.map → OracleConfigureOracleFlowDetail-MIBXUEKC.js.map} +0 -0
  43. /package/dist/{OracleStoreSecretsAndConfigFlowDetail-BFV2EHLT.js.map → OracleStoreSecretsAndConfigFlowDetail-HQU3UKEB.js.map} +0 -0
  44. /package/dist/{OracleStoreSecretsFlowDetail-DNNOPHVA.js.map → OracleStoreSecretsFlowDetail-5RXWQ3KA.js.map} +0 -0
  45. /package/dist/{ProposalCreateFlowDetail-4VZZPAWH.js.map → ProposalCreateFlowDetail-2FCRCNYV.js.map} +0 -0
  46. /package/dist/{chunk-2WPEATI7.js.map → chunk-JB6ASLUJ.js.map} +0 -0
  47. /package/dist/{chunk-3XSLBJYI.js.map → chunk-MZIBZ5FY.js.map} +0 -0
  48. /package/dist/{chunk-6ESTNTSH.js.map → chunk-WZW2WDJM.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/lib/sharedFlowDocument.ts","../src/core/lib/flowDocumentCache.ts","../src/core/lib/flowCompiler/conditions.ts","../src/core/lib/flowCompiler/blockMapping.ts","../src/core/lib/flowCompiler/compiler.ts","../src/core/lib/flowCompiler/hydrate.ts","../src/core/lib/flowCompiler/documentFragment.ts","../src/core/lib/flowCompiler/readFlow.ts","../src/core/lib/flowCompiler/mergeFlows.ts","../src/core/lib/flowCompiler/decompile.ts","../src/core/lib/flowCompiler/setup.ts","../src/core/lib/flowCompiler/authoring.ts","../src/core/lib/flowAgent/policy.ts","../src/core/lib/flowAgent/commands.ts","../src/core/lib/flowAgent/context.ts","../src/core/lib/flowAgent/lease.ts","../src/core/lib/flowAgent/state.ts","../src/core/lib/flowAgent/actionExecutionPolicy.ts","../src/core/lib/flowAgent/orchestrator.ts","../src/core/lib/flowAgent/execution.ts","../src/core/lib/flowAgent/service.ts"],"sourcesContent":["import { MatrixCRDTEventTranslator, MatrixProvider, MatrixReader } from '@ixo/matrix-crdt';\nimport { Direction, Filter, type MatrixClient } from 'matrix-js-sdk';\nimport * as Y from 'yjs';\nimport { readFlowCheckpoint, writeFlowCheckpoint, type FlowDocumentCheckpoint } from './flowDocumentCache';\n\nexport type SharedFlowDocumentStatus = 'disconnected' | 'connecting' | 'connected' | 'error';\ntype Messages = Awaited<ReturnType<MatrixClient['createMessagesRequest']>>;\nconst sessions = new WeakMap<MatrixClient, Map<string, SharedFlowDocument>>();\nconst RETAIN_MS = 5 * 60 * 1000;\nlet activeLoads = 0;\nconst loadQueue: { visible: boolean; start: () => void }[] = [];\n\nfunction withLoadSlot<T>(read: () => Promise<T>, visible: boolean): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const start = () => {\n activeLoads++;\n void read()\n .then(resolve, reject)\n .finally(() => {\n activeLoads--;\n loadQueue.sort((a, b) => Number(b.visible) - Number(a.visible));\n loadQueue.shift()?.start();\n });\n };\n if (activeLoads < 4) start();\n else loadQueue.push({ visible, start });\n });\n}\n\nfunction syntheticSnapshot(update: Uint8Array) {\n let binary = '';\n for (const byte of update) binary += String.fromCharCode(byte);\n return { type: 'matrix-crdt.doc_snapshot', event_id: '$local-checkpoint', sender: '@local:cache', origin_server_ts: 0, content: { update: btoa(binary) } };\n}\n\nfunction clientWithHistory(client: MatrixClient, history: () => Promise<Messages | undefined>): MatrixClient {\n let first = true;\n return new Proxy(client, {\n get(target, property) {\n if (property === 'createMessagesRequest') {\n return async (...args: Parameters<MatrixClient['createMessagesRequest']>) => {\n if (first && !args[1] && args[3] === Direction.Backward) {\n first = false;\n const response = await history();\n if (response) return response;\n }\n return target.createMessagesRequest(args[0], args[1], 200, args[3], args[4]);\n };\n }\n const value = Reflect.get(target, property);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n}\n\nexport async function readFlowDocumentHistory(client: MatrixClient, roomId: string, checkpoint?: FlowDocumentCheckpoint) {\n const room = client.getRoom(roomId);\n if (checkpoint && Date.now() - checkpoint.savedAt > 30 * 60 * 1000 && room && !room.currentState.getStateEvents('m.room.encryption', '')) checkpoint = undefined;\n if (checkpoint) {\n try {\n Y.decodeUpdate(checkpoint.update);\n } catch {\n checkpoint = undefined;\n }\n }\n const translator = new MatrixCRDTEventTranslator();\n const filter = new Filter(client.getUserId() ?? undefined);\n filter.setDefinition({ room: { timeline: { types: [...translator.readEventTypes, 'm.room.encrypted'] } } });\n const readerClient = clientWithHistory(client, async () => {\n let token = checkpoint?.token;\n let initial: Messages['chunk'] = checkpoint ? [syntheticSnapshot(checkpoint.update)] : [];\n let recent: Messages | undefined;\n if (!token) {\n const room = client.getRoom(roomId);\n if (!room || room.currentState.getStateEvents('m.room.encryption', '')) return;\n recent = await client.createMessagesRequest(roomId, '', 200, Direction.Backward, filter);\n if (!recent.end || recent.end === recent.start || recent.chunk.some((event) => translator.isAnySnapshotEvent(event))) return recent;\n const snapshots = new Filter(client.getUserId() ?? undefined);\n snapshots.setDefinition({ room: { timeline: { types: ['matrix-crdt.doc_snapshot', 'matrix-crdt.doc_snapshot_v2'] } } });\n try {\n const page = await client.createMessagesRequest(roomId, '', 1, Direction.Backward, snapshots);\n if (!page.chunk.length || !page.end) return recent;\n token = page.end;\n } catch {\n return recent;\n }\n }\n try {\n for (;;) {\n const page = await client.createMessagesRequest(roomId, token, 200, Direction.Forward, filter);\n initial.push(...page.chunk);\n if (!page.end || page.end === token || page.chunk.length === 0) {\n return { chunk: initial.reverse(), start: page.end || token, end: undefined } as Messages;\n }\n token = page.end;\n }\n } catch {\n return recent;\n }\n });\n let reader = new MatrixReader(readerClient, roomId, translator);\n try {\n let events;\n try {\n events = await reader.getInitialDocumentUpdateEvents();\n } catch {\n reader.dispose();\n reader = new MatrixReader(\n clientWithHistory(client, async () => undefined),\n roomId,\n translator\n );\n events = await reader.getInitialDocumentUpdateEvents();\n }\n if (reader.snapshotDegradations.length) {\n reader.dispose();\n reader = new MatrixReader(\n clientWithHistory(client, async () => undefined),\n roomId,\n translator\n );\n events = await reader.getInitialDocumentUpdateEvents();\n }\n const updates = events.map((event) => translator.getUpdateBytes(event)).filter((update): update is Uint8Array => !!update);\n return { update: updates.length ? Y.mergeUpdates(updates) : Y.encodeStateAsUpdate(new Y.Doc()), token: reader.latestToken };\n } finally {\n reader.dispose();\n }\n}\n\nexport class SharedFlowDocument {\n readonly doc = new Y.Doc();\n lastAccess = Date.now();\n status: SharedFlowDocumentStatus = 'disconnected';\n ready = false;\n error?: string;\n provider: MatrixProvider | null = null;\n private listeners = new Set<() => void>();\n private live = new Set<() => void>();\n private pending?: Promise<void>;\n private checkpoint?: FlowDocumentCheckpoint;\n private idle?: ReturnType<typeof setTimeout>;\n private retry?: ReturnType<typeof setTimeout>;\n private stopTimer?: ReturnType<typeof setTimeout>;\n private stopping?: Promise<void>;\n private attempt = 0;\n private generation = 0;\n\n constructor(\n readonly client: MatrixClient,\n readonly roomId: string\n ) {}\n\n private notify = () => {\n for (const listener of this.listeners) listener();\n };\n private flush = () => {\n void this.provider?.waitForFlush().catch(() => undefined);\n };\n\n private watchPageExit(enabled: boolean) {\n if (typeof window === 'undefined') return;\n if (enabled) {\n window.addEventListener('pagehide', this.flush);\n window.addEventListener('beforeunload', this.flush);\n } else {\n window.removeEventListener('pagehide', this.flush);\n window.removeEventListener('beforeunload', this.flush);\n }\n }\n\n evictIfIdle(): boolean {\n if (this.listeners.size || this.pending) return false;\n this.generation++;\n clearTimeout(this.idle);\n clearTimeout(this.retry);\n clearTimeout(this.stopTimer);\n if (sessions.get(this.client)?.get(this.roomId) === this) sessions.get(this.client)?.delete(this.roomId);\n void this.stopProvider().finally(() => this.doc.destroy());\n return true;\n }\n\n subscribe(listener: () => void, live = true): () => void {\n this.lastAccess = Date.now();\n clearTimeout(this.idle);\n clearTimeout(this.stopTimer);\n this.listeners.add(listener);\n if (live) this.live.add(listener);\n void this.connect();\n return () => {\n this.listeners.delete(listener);\n this.live.delete(listener);\n if (!this.live.size && this.provider)\n this.stopTimer = setTimeout(() => {\n if (!this.live.size) void this.stopProvider();\n }, 1000);\n if (!this.listeners.size) {\n clearTimeout(this.retry);\n this.idle = setTimeout(() => {\n this.evictIfIdle();\n }, RETAIN_MS);\n this.idle.unref?.();\n }\n };\n }\n\n connect(): Promise<void> {\n if (this.pending) return this.pending;\n if (this.provider || (this.ready && !this.live.size && this.checkpoint && Date.now() - this.checkpoint.savedAt < 30_000)) return Promise.resolve();\n const generation = this.generation;\n this.status = 'connecting';\n this.notify();\n this.pending = (async () => {\n await this.stopping;\n if (!this.checkpoint) {\n const membership = this.client.getRoom(this.roomId)?.getMyMembership?.();\n if (!membership || membership === 'join') this.checkpoint = await readFlowCheckpoint(this.client, this.roomId);\n if (generation !== this.generation) return;\n if (this.checkpoint) {\n try {\n Y.decodeUpdate(this.checkpoint.update);\n Y.applyUpdate(this.doc, this.checkpoint.update, this);\n this.ready = true;\n this.notify();\n } catch {\n this.checkpoint = undefined;\n }\n }\n }\n const result = await withLoadSlot(() => readFlowDocumentHistory(this.client, this.roomId, this.checkpoint), this.live.size > 0);\n if (generation !== this.generation) return;\n Y.applyUpdate(this.doc, result.update, this);\n this.ready = true;\n this.error = undefined;\n this.attempt = 0;\n if (result.token) this.checkpoint = { update: result.update, token: result.token, savedAt: Date.now() };\n this.status = this.live.size ? 'connecting' : 'connected';\n if (this.live.size) {\n const providerClient = clientWithHistory(\n this.client,\n async () =>\n ({\n chunk: [syntheticSnapshot(result.update)],\n start: result.token,\n end: undefined,\n }) as Messages\n );\n const provider = new MatrixProvider(\n this.doc,\n providerClient,\n { type: 'id', id: this.roomId },\n {\n translator: { enableMediaSnapshots: true },\n reader: { snapshotInterval: 10 },\n writer: { flushInterval: 300, retryIfForbiddenInterval: 30000 },\n enableAwareness: true,\n enableExperimentalWebrtcSync: true,\n }\n );\n this.provider = provider;\n this.watchPageExit(true);\n provider.onDocumentUnavailable(() => {\n if (this.provider !== provider) return;\n this.status = 'error';\n this.error = 'Flow document is unavailable';\n this.notify();\n });\n provider.onDocumentAvailable(() => {\n if (this.provider !== provider) return;\n this.status = 'connected';\n this.error = undefined;\n this.notify();\n });\n void provider.initialize().catch((error) => {\n if (this.provider !== provider) return;\n provider.dispose();\n this.watchPageExit(false);\n this.provider = null;\n this.fail(error);\n });\n }\n this.save();\n this.notify();\n })()\n .catch((error) => {\n if (generation === this.generation) this.fail(error);\n })\n .finally(() => {\n this.pending = undefined;\n });\n return this.pending;\n }\n\n private fail(error: unknown) {\n const code = (error as { errcode?: string })?.errcode;\n if (code === 'M_FORBIDDEN' || code === 'M_UNKNOWN_TOKEN') {\n this.ready = false;\n this.checkpoint = undefined;\n }\n this.status = 'error';\n this.error = error instanceof Error ? error.message : String(error);\n this.notify();\n clearTimeout(this.retry);\n if (this.listeners.size) this.retry = setTimeout(() => void this.connect(), Math.min(5000 * 2 ** this.attempt++, 30000));\n }\n\n private save() {\n if (this.checkpoint && this.ready) void writeFlowCheckpoint(this.client, this.roomId, this.checkpoint);\n }\n\n private async stopProvider() {\n const provider = this.provider;\n if (!provider) return;\n this.save();\n this.watchPageExit(false);\n this.provider = null;\n this.stopping = (async () => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n provider.waitForFlush(),\n new Promise((resolve) => {\n timer = setTimeout(resolve, 3000);\n }),\n ]);\n } catch {\n return;\n } finally {\n clearTimeout(timer);\n provider.dispose();\n }\n })();\n await this.stopping;\n this.stopping = undefined;\n }\n\n reconnect = async () => {\n clearTimeout(this.retry);\n this.attempt = 0;\n await this.stopProvider();\n await this.connect();\n };\n}\n\nexport function getSharedFlowDocument(client: MatrixClient, roomId: string): SharedFlowDocument {\n let rooms = sessions.get(client);\n if (!rooms) {\n rooms = new Map();\n sessions.set(client, rooms);\n }\n let session = rooms.get(roomId);\n if (!session) {\n session = new SharedFlowDocument(client, roomId);\n rooms.set(roomId, session);\n }\n session.lastAccess = Date.now();\n if (rooms.size > 32) {\n for (const candidate of [...rooms.values()].sort((a, b) => a.lastAccess - b.lastAccess)) {\n if (rooms.size <= 32) break;\n if (candidate !== session && Date.now() - candidate.lastAccess > 1000) candidate.evictIfIdle();\n }\n }\n return session;\n}\n","import type { MatrixClient } from 'matrix-js-sdk';\n\nexport interface FlowDocumentCheckpoint {\n update: Uint8Array;\n token: string;\n savedAt: number;\n}\n\nconst DATABASE = 'ixo-flow-checkpoints-v1';\nconst MAX_AGE = 7 * 24 * 60 * 60 * 1000;\n\nasync function identity(client: MatrixClient, roomId: string) {\n const token = client.getAccessToken?.();\n if (!token || !globalThis.crypto?.subtle || typeof indexedDB === 'undefined') return;\n const scope = JSON.stringify([client.getHomeserverUrl(), client.getUserId(), roomId]);\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(`${scope}\\u0000${token}`));\n const key = await crypto.subtle.importKey('raw', digest, 'AES-GCM', false, ['encrypt', 'decrypt']);\n return { scope, key };\n}\n\nasync function database(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(DATABASE, 1);\n request.onupgradeneeded = () => request.result.createObjectStore('documents');\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n request.onblocked = () => reject(new Error('Flow cache is blocked'));\n });\n}\n\nexport async function readFlowCheckpoint(client: MatrixClient, roomId: string): Promise<FlowDocumentCheckpoint | undefined> {\n try {\n const auth = await identity(client, roomId);\n if (!auth) return;\n const db = await database();\n const record = await new Promise<{ iv: Uint8Array; data: ArrayBuffer; savedAt: number } | undefined>((resolve, reject) => {\n const transaction = db.transaction('documents', 'readonly');\n const request = transaction.objectStore('documents').get(auth.scope);\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n transaction.oncomplete = () => db.close();\n transaction.onabort = () => db.close();\n });\n if (!record || Date.now() - record.savedAt > MAX_AGE) return;\n const clear = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: new Uint8Array(record.iv), additionalData: new TextEncoder().encode(auth.scope) }, auth.key, record.data);\n const value = JSON.parse(new TextDecoder().decode(clear)) as { update: number[]; token: string };\n if (!Array.isArray(value.update) || !value.token) return;\n return { update: new Uint8Array(value.update), token: value.token, savedAt: record.savedAt };\n } catch {\n return;\n }\n}\n\nexport async function writeFlowCheckpoint(client: MatrixClient, roomId: string, checkpoint: FlowDocumentCheckpoint): Promise<void> {\n try {\n if (checkpoint.update.byteLength > 8 * 1024 * 1024) return;\n const auth = await identity(client, roomId);\n if (!auth) return;\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const data = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv, additionalData: new TextEncoder().encode(auth.scope) },\n auth.key,\n new TextEncoder().encode(JSON.stringify({ update: Array.from(checkpoint.update), token: checkpoint.token }))\n );\n const db = await database();\n await new Promise<void>((resolve, reject) => {\n const transaction = db.transaction('documents', 'readwrite');\n const store = transaction.objectStore('documents');\n store.put({ iv, data, savedAt: checkpoint.savedAt }, auth.scope);\n const request = store.openCursor();\n const records: { key: IDBValidKey; savedAt: number }[] = [];\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) {\n records.sort((a, b) => b.savedAt - a.savedAt);\n for (const record of records.slice(32)) store.delete(record.key);\n return;\n }\n if (Date.now() - cursor.value.savedAt > MAX_AGE) cursor.delete();\n else records.push({ key: cursor.key, savedAt: cursor.value.savedAt });\n cursor.continue();\n };\n transaction.oncomplete = () => {\n db.close();\n resolve();\n };\n transaction.onerror = () => {\n db.close();\n reject(transaction.error);\n };\n transaction.onabort = () => {\n db.close();\n reject(transaction.error);\n };\n });\n } catch {\n return;\n }\n}\n","/**\n * The operator vocabulary the FE condition evaluator actually understands\n * (`src/mantine/blocks/utils/conditionEvaluator.ts`). The compiler historically wrote the\n * BaseUcan `ConditionRef` vocabulary (`eq`/`neq`/…) verbatim, which the evaluator does NOT\n * recognise (and no normalizer bridged them) — so those conditions silently never fired.\n * This module is the single source of truth that maps every supported spelling onto the\n * evaluator's vocabulary, and assembles the `props.conditions` JSON.\n */\nexport type EvaluatorOperator = 'equals' | 'not_equals' | 'greater_than' | 'less_than' | 'contains' | 'not_contains' | 'is_empty' | 'is_not_empty';\n\nconst OPERATOR_MAP: Record<string, EvaluatorOperator> = {\n // BaseUcan ConditionRef vocabulary\n eq: 'equals',\n neq: 'not_equals',\n gt: 'greater_than',\n lt: 'less_than',\n in: 'contains',\n exists: 'is_not_empty',\n // Friendly camelCase (plugin FlowSpec `is`)\n equals: 'equals',\n notEquals: 'not_equals',\n greaterThan: 'greater_than',\n lessThan: 'less_than',\n isEmpty: 'is_empty',\n isNotEmpty: 'is_not_empty',\n // Evaluator vocabulary passthrough\n not_equals: 'not_equals',\n greater_than: 'greater_than',\n less_than: 'less_than',\n contains: 'contains',\n not_contains: 'not_contains',\n notContains: 'not_contains',\n is_empty: 'is_empty',\n is_not_empty: 'is_not_empty',\n};\n\n/** Normalize any supported operator spelling to the evaluator's vocabulary. Unknown → `equals`. */\nexport function toEvaluatorOperator(operator: string): EvaluatorOperator {\n return OPERATOR_MAP[operator] ?? 'equals';\n}\n\nexport interface BlockConditionInput {\n /** The BLOCK id of the source step (note: the stored shape keys on blockId, not nodeId). */\n sourceBlockId: string;\n /** Property on the source block to test. */\n property: string;\n /** Any supported operator spelling — normalized to the evaluator's vocabulary on write. */\n operator: string;\n value?: unknown;\n effect?: { action: 'enable' | 'disable' | 'show' | 'hide'; message?: string };\n /** Source block type label; defaults to the compiled action type (`'action'`). */\n sourceBlockType?: string;\n name?: string;\n}\n\n/**\n * Build the `props.conditions` JSON string in the exact shape the FE evaluator reads, with\n * operators normalized to its vocabulary. Single source of truth for the conditions prop —\n * used by both the flow compiler (`compileCondition`) and direct authoring writes\n * (`setBlockProps('conditions', buildBlockConditionsProp(...))`), so a condition authored\n * either way actually evaluates.\n */\nexport function buildBlockConditionsProp(conditions: BlockConditionInput[], opts?: { mode?: 'all_must_pass' | 'any_can_pass'; enabled?: boolean }): string {\n return JSON.stringify({\n enabled: opts?.enabled ?? true,\n mode: opts?.mode ?? 'all_must_pass',\n conditions: conditions.map((c, i) => ({\n id: `cond_${c.sourceBlockId}_${c.property}_${i}`,\n name: c.name ?? `Condition from ${c.sourceBlockId}`,\n sourceBlockId: c.sourceBlockId,\n sourceBlockType: c.sourceBlockType ?? 'action',\n rule: {\n type: 'property_value',\n property: c.property,\n operator: toEvaluatorOperator(c.operator),\n value: c.value,\n },\n effect: c.effect ?? { action: 'enable' },\n })),\n });\n}\n","import type { FlowCapability } from '../../types/baseUcan';\n\n/** Default icon per `can` statement. */\nconst ICON_DEFAULTS: Record<string, string> = {\n 'bid/submit': 'gavel',\n 'bid/evaluate': 'check-circle',\n 'claim/submit': 'file-check',\n 'claim/evaluate': 'clipboard-check',\n 'email/send': 'mail',\n 'notification/push': 'bell',\n 'matrix/dm': 'message-circle',\n 'proposal/create': 'scroll',\n 'proposal/vote': 'vote',\n 'domain/card-preview': 'id',\n 'domain/sign': 'feather',\n 'credential/store': 'shield',\n 'http/request': 'cloud',\n 'protocol/select': 'git-branch',\n 'human/checkbox': 'check-square',\n 'human/form': 'file-text',\n 'form/submit': 'file-text',\n 'oracle/query': 'cpu',\n};\n\n/**\n * Compile a FlowCapability into block props for the `action` block type.\n *\n * All capabilities map to the `action` block type — the `actionType` prop\n * routes to the correct registry action at runtime. This is consistent with\n * how the slash menu creates action blocks today.\n *\n * All returned values are strings per BlockNote convention.\n */\nexport function compileBlockProps(cap: FlowCapability, registryType: string): Record<string, string> {\n return {\n title: cap.title || cap.can,\n description: cap.description || '',\n icon: cap.icon || ICON_DEFAULTS[cap.can] || 'bolt',\n actionType: registryType,\n inputs: JSON.stringify(cap.nb || {}),\n requiresConfirmation: '',\n conditions: '', // compiled separately by the compiler\n // Authorization props\n parentCapability: cap.actor?.parentCapability || '',\n authorisedActors: cap.actor?.authorisedActors ? JSON.stringify(cap.actor.authorisedActors) : '',\n // TTL props\n ttlAbsoluteDueDate: cap.ttl?.absoluteDueDate || '',\n ttlFromEnablement: cap.ttl?.fromEnablement || '',\n ttlFromCommitment: cap.ttl?.fromCommitment || '',\n // Trigger props (slice D — events and triggers feature). Stored as a\n // JSON string mirroring how `inputs` serializes `nb`. Default empty\n // string means \"manual\" — the runtime treats absent or empty as manual.\n trigger: cap.trigger ? JSON.stringify(cap.trigger) : '',\n };\n}\n\n/** The BlockNote block type that all capabilities compile to. */\nexport const COMPILED_BLOCK_TYPE = 'action' as const;\n\n/** Get the default icon for a `can` statement. */\nexport function getDefaultIcon(can: string): string {\n return ICON_DEFAULTS[can] || 'bolt';\n}\n","import type { BaseUcanFlow, FlowCapability, CompiledFlow, CompiledBlock, CompiledEdge, CompiledFlowNode, ConditionRef, RuntimeRef, TriggerSpec } from '../../types/baseUcan';\nimport { isRuntimeRef } from '../../types/baseUcan';\nimport type { ActionDefinition } from '../actionRegistry/types';\nimport { getEventsForBlock } from '../actionRegistry/registry';\nimport { compileBlockProps, COMPILED_BLOCK_TYPE } from './blockMapping';\nimport { toEvaluatorOperator } from './conditions';\n\n// ─── Public API ─────────────────────────────────────────────────────────────\n\n/** Registry interface expected by the compiler (keeps it pure / testable). */\nexport interface CompilerRegistry {\n getActionByCan(can: string): ActionDefinition | undefined;\n}\n\n/**\n * Compile a Base UCAN flow plan into blocks, graph state, and metadata.\n *\n * This is a **pure function** — no React, no Yjs, no side effects.\n * The output is consumed by `hydrateFlowFromPlan()`.\n */\n/**\n * Strip active schedule bindings from a plan — the clone rule (IXO-4429):\n * templates and instantiated copies keep the INTENT that a block runs on a\n * schedule, but never the activated schedule ID or its pinned revision. An\n * active scheduleRef names one authorized binding — one signed activation,\n * one revision guard, one provider timer — not a reusable default; carrying\n * it into a copy would point two flows at one authorization.\n *\n * Pure: returns a new plan, and returns the SAME plan object when nothing\n * needed stripping.\n */\nexport function stripActiveScheduleBindings(plan: BaseUcanFlow): BaseUcanFlow {\n let changed = false;\n const capabilities = plan.capabilities.map((cap) => {\n if (cap.trigger?.type !== 'schedule') return cap;\n if (cap.trigger.scheduleRef === undefined && cap.trigger.scheduleRevision === undefined) return cap;\n changed = true;\n const { scheduleRef: _ref, scheduleRevision: _rev, ...inactive } = cap.trigger;\n return { ...cap, trigger: inactive as TriggerSpec };\n });\n return changed ? { ...plan, capabilities } : plan;\n}\n\nexport function compileBaseUcanFlow(plan: BaseUcanFlow, registry: CompilerRegistry): CompiledFlow {\n if (!Array.isArray(plan.capabilities)) {\n throw new Error('BaseUcanFlow.capabilities must be an array');\n }\n\n const capabilities = plan.capabilities;\n if (capabilities.length === 0) {\n throw new Error('BaseUcanFlow has no capabilities to compile');\n }\n\n // 1. Validate every `can` against the registry\n const actionMap = new Map<string, { action: ActionDefinition; nodeId: string; cap: FlowCapability }>();\n for (const cap of capabilities) {\n const nodeId = cap.id?.trim();\n if (!nodeId) {\n throw new Error('Every capability in BaseUcanFlow.capabilities must include a non-empty id.');\n }\n if (actionMap.has(nodeId)) {\n throw new Error(`Duplicate capability id \"${nodeId}\" in BaseUcanFlow.capabilities.`);\n }\n\n const action = registry.getActionByCan(cap.can);\n if (!action) {\n throw new Error(`Unknown capability \"${cap.can}\" for node \"${nodeId}\". Not found in action registry.`);\n }\n actionMap.set(nodeId, { action, nodeId, cap });\n }\n\n // 2. Pre-generate deterministic block IDs (stable for testing)\n const blockIndex: Record<string, string> = {};\n for (const nodeId of actionMap.keys()) {\n blockIndex[nodeId] = generateBlockId(nodeId);\n }\n\n // 3. Validate triggers (slice D — events and triggers feature).\n // For every block.event-triggered listener:\n // a) source block must exist in the plan\n // b) source action must declare an `events` array\n // c) eventName must match a declared event\n // d) every nodeId.output.* ref in the listener's nb must be reachable\n // (the referenced block must exist; the field shape is enforced\n // loosely because output schemas are optional today)\n // Also: synthesize \"trigger\" edges from each block.event trigger so the\n // visual graph and the cycle detector see the dependency.\n const triggerEdges: CompiledEdge[] = [];\n for (const [nodeId, { cap, action }] of actionMap) {\n const trigger = cap.trigger;\n if (!trigger) continue;\n\n // ── block.event (single source) ──────────────────────────────────\n if (trigger.type === 'block.event') {\n if (action.eligibleForEventTrigger !== true) {\n throw new Error(\n `Block \"${nodeId}\" is configured with a block.event trigger, but its action type \"${action.type}\" is not marked eligibleForEventTrigger. Set eligibleForEventTrigger: true on the action definition or change the trigger to manual.`\n );\n }\n\n const sourceId = trigger.sourceBlockId?.trim();\n const eventName = trigger.eventName?.trim();\n if (!sourceId || !eventName) {\n throw new Error(`Block \"${nodeId}\" has a block.event trigger but is missing sourceBlockId or eventName.`);\n }\n\n const source = actionMap.get(sourceId);\n if (!source) {\n throw new Error(`Trigger on block \"${nodeId}\" references unknown source block \"${sourceId}\".`);\n }\n\n // Resolve events per the source block's current inputs; some actions\n // (e.g. claim.submit) derive the event list from configured state.\n const declaredEvents = getEventsForBlock(source.action, source.cap.nb);\n if (declaredEvents.length === 0) {\n throw new Error(`Trigger on block \"${nodeId}\" references event \"${eventName}\" but source action \"${source.action.type}\" declares no events.`);\n }\n\n const found = declaredEvents.find((e) => e.name === eventName);\n if (!found) {\n const declared = declaredEvents.map((e) => e.name).join(', ');\n throw new Error(`Trigger on block \"${nodeId}\" references unknown event \"${eventName}\" on action type \"${source.action.type}\". Declared events: [${declared}]`);\n }\n\n triggerEdges.push({\n id: `${sourceId}~event:${eventName}~>${nodeId}`,\n source: sourceId,\n target: nodeId,\n kind: 'trigger',\n });\n }\n\n if (trigger.type === 'block.event.all') {\n if (action.eligibleForEventTrigger !== true) {\n throw new Error(`Block \"${nodeId}\" is configured with a block.event.all trigger, but its action type \"${action.type}\" is not marked eligibleForEventTrigger.`);\n }\n\n const sources = trigger.sources || [];\n if (sources.length === 0) {\n throw new Error(`Block \"${nodeId}\" has a block.event.all trigger but no sources configured.`);\n }\n\n for (const src of sources) {\n const srcId = src.sourceBlockId?.trim();\n const evtName = src.eventName?.trim();\n if (!srcId || !evtName) {\n throw new Error(`Block \"${nodeId}\" has a block.event.all source with missing sourceBlockId or eventName.`);\n }\n\n const sourceEntry = actionMap.get(srcId);\n if (!sourceEntry) {\n throw new Error(`Barrier trigger on block \"${nodeId}\" references unknown source block \"${srcId}\".`);\n }\n\n const declaredEvents = getEventsForBlock(sourceEntry.action, sourceEntry.cap.nb);\n const found = declaredEvents.find((e) => e.name === evtName);\n if (!found) {\n const declared = declaredEvents.map((e) => e.name).join(', ');\n throw new Error(`Barrier trigger on block \"${nodeId}\" references unknown event \"${evtName}\" on action type \"${sourceEntry.action.type}\". Declared events: [${declared}]`);\n }\n\n if (!src.alias?.trim()) {\n throw new Error(`Barrier trigger on block \"${nodeId}\" has a source (${srcId}/${evtName}) with no alias.`);\n }\n\n triggerEdges.push({\n id: `${srcId}~event:${evtName}~>${nodeId}`,\n source: srcId,\n target: nodeId,\n kind: 'trigger',\n });\n }\n }\n\n // ── schedule (Sovereign Scheduling, IXO-4429/IXO-4433) ────────────\n if (trigger.type === 'schedule') {\n if (action.eligibleForTimeTrigger !== true) {\n // The eligibility gate: an ineligible Action fails at compilation\n // (and again at activation). Being fireable on a timer is a\n // deliberate per-action opt-in, distinct from event eligibility.\n throw new Error(\n `Block \"${nodeId}\" is configured with a schedule trigger, but its action type \"${action.type}\" is not marked eligibleForTimeTrigger. Set eligibleForTimeTrigger: true on the action definition or change the trigger.`\n );\n }\n // A schedule trigger WITHOUT a scheduleRef is valid: it is inactive\n // intent — \"this block runs on a schedule, not yet bound to one\".\n // Templates clone exactly this shape (IXO-4429): the intent survives,\n // the activated schedule ID never does. Binding a real scheduleRef\n // happens at activation through the schedule control module, which\n // requires an existing, authorized schedule record.\n if (trigger.sourceBlockId || trigger.sources || trigger.eventName) {\n throw new Error(\n `Block \"${nodeId}\" has a schedule trigger carrying event-trigger fields (sourceBlockId/eventName/sources). A schedule trigger holds only scheduleRef and scheduleRevision — timing lives in the referenced ScheduleSpec, never in the block.`\n );\n }\n if (trigger.scheduleRevision !== undefined && (!Number.isInteger(trigger.scheduleRevision) || trigger.scheduleRevision < 1)) {\n throw new Error(`Block \"${nodeId}\" has a schedule trigger with an invalid scheduleRevision (must be an integer >= 1).`);\n }\n }\n\n // Validate that every nodeId.output.* ref the listener uses points at a\n // block that exists.\n if (trigger.type === 'block.event' || trigger.type === 'block.event.all') {\n const refs = collectOutputRefs(cap.nb || {});\n for (const ref of refs) {\n const parsed = parseOutputRef(ref);\n if (!parsed) continue;\n if (!actionMap.has(parsed.nodeId)) {\n throw new Error(`Listener \"${nodeId}\" references output of unknown block \"${parsed.nodeId}\" via ref \"${ref}\".`);\n }\n }\n }\n }\n\n // 4. Edges = trigger edges only. Synthesized in step 3 from `block.event`\n // triggers. Each one represents a real runtime relationship: source\n // emits an event, listener queues a pending invocation. There are no\n // other edge kinds — sequential ordering is implicit in the\n // capabilities[] array order, not derived from a separate field.\n const edges: CompiledEdge[] = [...triggerEdges];\n\n // 4b. Trigger graph cycle check. A cycle would cause the reconciliation\n // loop to oscillate (A's emission queues B, B's emission queues A,\n // forever). Hard error at compile time.\n detectTriggerCycles(triggerEdges);\n\n // 5. Order = the order capabilities appeared in the input plan.\n // No topological sort. The author is responsible for the order they\n // want; the compiler does not infer it.\n const order = Array.from(actionMap.keys());\n\n // 6. Compile each block in order\n const blocks: CompiledBlock[] = [];\n const nodes: Record<string, CompiledFlowNode> = {};\n\n for (const nodeId of order) {\n const { action, cap } = actionMap.get(nodeId)!;\n const blockId = blockIndex[nodeId];\n\n // Compile base props from the capability\n const props = compileBlockProps(cap, action.type);\n\n // Compile conditions into the block's conditions prop\n if (cap.condition) {\n props.conditions = compileCondition(cap.condition, blockIndex);\n }\n\n // Rewrite trigger source references from the node-id namespace (what\n // plan authors write, validated in step 3) into the block-id namespace\n // before serialization. The runtime reconciler matches props.trigger\n // against real document block ids (`flow_block_<nodeId>`) — a trigger\n // serialized with node ids validates fine but never fires.\n if (cap.trigger) {\n props.trigger = compileTrigger(cap.trigger, blockIndex);\n }\n\n // Stamp the trigger mode prop so the runtime UI knows whether this\n // block is event-driven or manually invoked. Event-driven blocks\n // suppress all manual run affordances and only fire via pending\n // invocations queued by the reconciliation loop. Default 'manual'.\n props.triggerMode = cap.trigger?.type || 'manual';\n\n blocks.push({\n id: blockId,\n type: COMPILED_BLOCK_TYPE,\n props,\n });\n\n nodes[nodeId] = {\n id: nodeId,\n blockId,\n can: cap.can,\n with: cap.with,\n registryType: action.type,\n title: cap.title || cap.can,\n description: cap.description || '',\n props,\n phase: cap.phase,\n parallelGroup: cap.parallelGroup,\n actor: cap.actor,\n };\n }\n\n return {\n meta: {\n flowId: plan.flowId,\n title: plan.title,\n goal: plan.goal,\n version: plan.version,\n flowOwnerDid: plan.meta?.rootIssuer || '',\n flowUri: plan.meta?.flowUri,\n compiledAt: new Date().toISOString(),\n compiledFrom: 'BaseUcanFlow',\n },\n blocks,\n nodes,\n edges,\n order,\n blockIndex,\n };\n}\n\n// ─── Internal Helpers ───────────────────────────────────────────────────────\n\n/** Generate a deterministic block ID from a node ID. */\nfunction generateBlockId(nodeId: string): string {\n // Use a prefix to clearly identify compiler-generated blocks\n return `flow_block_${nodeId}`;\n}\n\n/**\n * Compile a ConditionRef into the JSON string format expected by block conditions.\n * Matches the shape used by the existing block conditions system.\n */\nfunction compileCondition(condition: ConditionRef, blockIndex: Record<string, string>): string {\n const sourceBlockId = blockIndex[condition.sourceId];\n if (!sourceBlockId) {\n throw new Error(`Condition references unknown source \"${condition.sourceId}\".`);\n }\n\n const conditionConfig = {\n enabled: true,\n mode: 'all_must_pass',\n conditions: [\n {\n id: `cond_${condition.sourceId}_${condition.field}`,\n name: `Condition from ${condition.sourceId}`,\n sourceBlockId,\n sourceBlockType: COMPILED_BLOCK_TYPE,\n rule: {\n type: 'property_value',\n property: condition.field,\n // Map the BaseUcan ConditionRef operator (eq/neq/…) onto the FE evaluator's\n // vocabulary (equals/not_equals/…). Writing it verbatim is the historical bug\n // that made compiler-authored conditions silently never evaluate.\n operator: toEvaluatorOperator(condition.operator),\n value: condition.value,\n },\n effect: condition.effect || { action: 'enable' },\n },\n ],\n };\n\n return JSON.stringify(conditionConfig);\n}\n\n/**\n * Compile a TriggerSpec into the JSON string stored in props.trigger,\n * remapping every source reference from node id to compiled block id —\n * the same namespace translation compileCondition performs. Trigger\n * validation (step 3) has already guaranteed every source id resolves\n * in blockIndex.\n */\nfunction compileTrigger(trigger: TriggerSpec, blockIndex: Record<string, string>): string {\n if (trigger.type === 'block.event' && trigger.sourceBlockId) {\n return JSON.stringify({ ...trigger, sourceBlockId: blockIndex[trigger.sourceBlockId.trim()] });\n }\n if (trigger.type === 'block.event.all' && trigger.sources) {\n return JSON.stringify({\n ...trigger,\n sources: trigger.sources.map((src) => ({ ...src, sourceBlockId: blockIndex[src.sourceBlockId.trim()] })),\n });\n }\n return JSON.stringify(trigger);\n}\n\n// ─── Trigger validation helpers (slice D — events and triggers) ─────────────\n\n/**\n * Recursively walk an inputs/nb object and collect every RuntimeRef string\n * that targets a node output (i.e. matches `nodeId.output.fieldPath`).\n * Skips `trigger.payload.*` refs which resolve from a different namespace.\n */\nfunction collectOutputRefs(value: unknown): string[] {\n const refs: string[] = [];\n walk(value);\n return refs;\n\n function walk(v: unknown): void {\n if (isRuntimeRef(v)) {\n const r = (v as RuntimeRef).$ref;\n if (!r.startsWith('trigger.')) refs.push(r);\n return;\n }\n if (Array.isArray(v)) {\n for (const item of v) walk(item);\n return;\n }\n if (v !== null && typeof v === 'object') {\n for (const inner of Object.values(v as Record<string, unknown>)) walk(inner);\n }\n }\n}\n\n/** Parse `\"nodeId.output.fieldPath\"` into its parts; returns null if not a node-output ref. */\nfunction parseOutputRef(ref: string): { nodeId: string; fieldPath: string } | null {\n const outputIndex = ref.indexOf('.output.');\n if (outputIndex === -1) return null;\n return {\n nodeId: ref.slice(0, outputIndex),\n fieldPath: ref.slice(outputIndex + '.output.'.length),\n };\n}\n\n/**\n * Detect cycles in the trigger graph.\n *\n * A trigger cycle would mean: block A's event triggers block B, whose event\n * triggers block C, whose event triggers block A. The reconciliation loop\n * would oscillate forever queueing pending invocations. Hard error.\n *\n * Implementation: standard DFS with three-color marking (white/gray/black).\n * If we hit a gray node during DFS, we're inside its own subtree — that's\n * the cycle. ~30 lines and runs in O(V + E) which is sub-millisecond at any\n * realistic block count.\n */\nfunction detectTriggerCycles(triggerEdges: CompiledEdge[]): void {\n if (triggerEdges.length === 0) return;\n\n const adjacency = new Map<string, string[]>();\n const allNodes = new Set<string>();\n for (const edge of triggerEdges) {\n if (!adjacency.has(edge.source)) adjacency.set(edge.source, []);\n adjacency.get(edge.source)!.push(edge.target);\n allNodes.add(edge.source);\n allNodes.add(edge.target);\n }\n\n const WHITE = 0;\n const GRAY = 1;\n const BLACK = 2;\n const color = new Map<string, number>();\n for (const id of allNodes) color.set(id, WHITE);\n\n const path: string[] = [];\n\n const visit = (node: string): void => {\n color.set(node, GRAY);\n path.push(node);\n for (const next of adjacency.get(node) || []) {\n if (color.get(next) === GRAY) {\n // Found the back-edge. Build a readable cycle path.\n const start = path.indexOf(next);\n const cycle = path.slice(start).concat(next).join(' → ');\n throw new Error(`Trigger cycle detected: ${cycle}. Block.event triggers must form a DAG; remove one of the trigger declarations to break the cycle.`);\n }\n if (color.get(next) === WHITE) {\n visit(next);\n }\n }\n path.pop();\n color.set(node, BLACK);\n };\n\n for (const id of allNodes) {\n if (color.get(id) === WHITE) visit(id);\n }\n}\n","import type { Doc as YDoc } from 'yjs';\nimport * as Y from 'yjs';\nimport type { CompiledFlow, CompiledFlowNode } from '../../types/baseUcan';\nimport type { MergeResult } from './mergeFlows';\nimport { resetActionState, resolveActiveRunId } from '../flowEngine/runs';\nimport { generateActionManifest, getAction } from '../actionRegistry';\nimport { sha256Digest } from '../actionRegistry/digest';\nimport type { ActionContractV1, ActionSafety, Sha256Digest } from '../flowEngine/vnext/contracts';\n\nconst DRAFT_CONTROL_MAP = 'qi.flow.draftControl';\nconst LEGACY_COMMAND_REVISION_KEY = 'legacyCommandRevision';\n\nfunction nextDraftRevision(yDoc: YDoc, current: unknown): number {\n const currentRevision = Number(current ?? 0);\n const legacyRevision = Number(yDoc.getMap(DRAFT_CONTROL_MAP).get(LEGACY_COMMAND_REVISION_KEY) ?? 0);\n return Math.max(0, Number.isFinite(currentRevision) ? currentRevision : 0, Number.isFinite(legacyRevision) ? legacyRevision : 0) + 1;\n}\n\nfunction jsonOutputSchema(fields: ReadonlyArray<{ path: string; type: string }>): Record<string, unknown> {\n if (fields.length === 0) return { type: 'object', additionalProperties: true };\n const properties: Record<string, unknown> = {};\n for (const field of fields) {\n const [root] = field.path.split('.');\n if (!root) continue;\n properties[root] = field.path.includes('.') ? { type: 'object' } : { type: field.type };\n }\n return { type: 'object', properties, additionalProperties: true };\n}\n\n/**\n * How each action runs, by action type. The runner reads the `safety` this\n * pins onto the node and chooses a path from it:\n *\n * - `pure` run in-process, no service and no grant beyond the flow's own.\n * - `provider_idempotent` run in-process against a provider (an HTTP endpoint, an API).\n * - `fenced` hand to a helper oracle over the flow-work protocol.\n * - `approval_only` a person runs it; the runner never does.\n *\n * Only types listed here are taken off the `fenced` default. `fenced` is the\n * safe outcome: with no helper the runner leaves the step for a person instead\n * of running something it cannot fence. `qi/noop` and `qi/data.constant` are\n * not registry actions — the runner's own pure-flow path uses them — but they\n * are named here so both sides read one table.\n *\n * A human-owned action is `approval_only` whatever this table says.\n */\nexport const ACTION_SAFETY_BY_TYPE: Readonly<Record<string, ActionSafety>> = {\n 'qi/noop': 'pure',\n 'qi/data.constant': 'pure',\n // Reads a public endpoint and returns the body. No effect to fence.\n 'qi/http.fetch': 'pure',\n // Calls out and may change the far side, so it is not pure — but the runner\n // makes the call itself, so it is a provider action, not a fenced one. That\n // keeps the `flow/block/execute` grant every flow already holds sufficient.\n 'qi/http.request': 'provider_idempotent',\n};\n\n/** The safety an action of this type runs under. */\nexport function resolveActionSafety(type: string, executionOwner: 'agent' | 'human' | undefined): ActionSafety {\n if (executionOwner === 'human') return 'approval_only';\n return ACTION_SAFETY_BY_TYPE[type] ?? 'fenced';\n}\n\n/** Build the conservative execution contract which the Yjs document pins. */\nfunction executionContract(node: CompiledFlowNode): ActionContractV1 | undefined {\n const action = getAction(node.registryType);\n const manifest = generateActionManifest();\n const entry = manifest.actions.find((candidate) => candidate.type === node.registryType);\n if (!action || !entry || !entry.can) return undefined;\n const safety = resolveActionSafety(action.type, action.executionOwner);\n const contract: ActionContractV1 = {\n kind: 'qi.action.contract',\n schemaVersion: '1.0',\n type: action.type,\n can: entry.can,\n contractVersion: action.contractVersion,\n manifestDigest: manifest.manifestDigest as Sha256Digest,\n inputSchema: (action.inputSchema ?? { type: 'object', additionalProperties: true }) as ActionContractV1['inputSchema'],\n outputSchema: jsonOutputSchema(entry.outputSchema) as ActionContractV1['outputSchema'],\n safety,\n handlerVersion: `${action.type}@${action.contractVersion}`,\n dataClassification: action.sensitiveInputPaths?.length || action.sensitiveOutputPaths?.length ? 'confidential' : 'shared',\n requiredServices: [...(action.requiredServices ?? [])],\n idempotency: {\n providerKey: false,\n readback: safety === 'fenced' ? 'required' : 'unavailable',\n compensation: 'unavailable',\n },\n contractDigest: entry.contractDigest as Sha256Digest,\n };\n return contract;\n}\n\nfunction writeExecutionMeta(yDoc: YDoc): void {\n const meta = yDoc.getMap('qi.flow.meta');\n meta.set(\n 'definitionDigest',\n sha256Digest({\n nodes: yDoc.getMap('qi.flow.nodes').toJSON(),\n edges: yDoc.getMap('qi.flow.edges').toJSON(),\n order: yDoc.getArray<string>('qi.flow.order').toArray(),\n })\n );\n meta.set('executionSchemaVersion', 3);\n}\n\n/**\n * The flow segment of a step resource, re-based on the flow that holds it —\n * or `undefined` when the resource already names it, or cannot be identified.\n *\n * A step is addressed `ixo:flow:<flow id>:<step>`, and every grant over it is\n * minted from the document's own `doc_id`. Installing a template left those\n * two out of step: `createTemplateCloneSource` stamps each node with a\n * `crypto.randomUUID()` it invents, while `doc_id` is assigned separately, by\n * the editor, when someone first opens the new room. The nodes then named a\n * flow that does not exist. No grant covered them, so every run died at its\n * first step with \"The oracle has no flow delegation\" — for a flow whose\n * delegation was sitting right there, correctly signed and correctly pinned.\n *\n * Only the flow segment moves. The step segment is whatever the document\n * already said, recognised by matching the node's own ids rather than parsed\n * out of the string: a flow id may itself contain colons (a Matrix room id\n * does), so splitting on them would corrupt the very resources this repairs.\n * A resource ending in neither id is left alone — re-addressing something we\n * cannot identify would invent authority rather than repair it.\n */\nfunction rebaseStepResource(authored: string, flowPrefix: string, stepIds: readonly string[]): string | undefined {\n if (authored === flowPrefix || authored.startsWith(`${flowPrefix}:`)) return undefined;\n for (const stepId of stepIds) {\n if (stepId && authored.endsWith(`:${stepId}`)) return `${flowPrefix}:${stepId}`;\n }\n return undefined;\n}\n\n/** Add missing execution contracts to an existing typed flow document. */\nexport function ensureFlowExecutionMetadata(yDoc: YDoc): boolean {\n if (yDoc.getMap('qi.flow.meta').get('draftSchemaVersion') !== 1) return false;\n let changed = false;\n yDoc.transact(() => {\n // Absent until the editor assigns it on first open. Until then there is no\n // flow to re-base onto, and the next pass does it.\n const docId = yDoc.getMap('root').get('doc_id');\n const flowPrefix = typeof docId === 'string' && docId ? `ixo:flow:${docId}` : undefined;\n for (const [nodeId, value] of yDoc.getMap('qi.flow.nodes').entries()) {\n if (!(value instanceof Y.Map)) continue;\n const registryType = value.get('registryType');\n if (typeof registryType !== 'string' || !registryType) continue;\n const authoredResource = value.get('with');\n const rebased =\n flowPrefix && typeof authoredResource === 'string'\n ? rebaseStepResource(authoredResource, flowPrefix, [String(value.get('id') ?? nodeId), String(value.get('blockId') ?? '')])\n : undefined;\n if (rebased) {\n value.set('with', rebased);\n // `props` is the canonical copy the runner and the authoring surfaces\n // read; it carries the same string and has to move with it.\n const props = asRecord(value.get('props'));\n if (props && props.with === authoredResource) value.set('props', { ...props, with: rebased });\n changed = true;\n }\n const executionOwner = getAction(registryType)?.executionOwner ?? 'agent';\n if (value.get('executionOwner') !== executionOwner) {\n value.set('executionOwner', executionOwner);\n changed = true;\n }\n const contract = executionContract({\n id: String(value.get('id') ?? nodeId),\n blockId: String(value.get('blockId') ?? ''),\n can: String(value.get('can') ?? ''),\n with: String(value.get('with') ?? ''),\n registryType,\n title: String(value.get('title') ?? ''),\n description: String(value.get('description') ?? ''),\n props: (value.get('props') as Record<string, string> | undefined) ?? {},\n });\n if (contract && JSON.stringify(value.get('actionContract')) !== JSON.stringify(contract)) {\n value.set('actionContract', contract);\n changed = true;\n }\n }\n const meta = yDoc.getMap('qi.flow.meta');\n if (changed || typeof meta.get('definitionDigest') !== 'string' || meta.get('executionSchemaVersion') !== 3) {\n meta.set('draftRevision', nextDraftRevision(yDoc, meta.get('draftRevision')));\n writeExecutionMeta(yDoc);\n meta.set('draftUpdatedAt', new Date().toISOString());\n changed = true;\n }\n });\n return changed;\n}\n\n/**\n * Move a pre-vNext flow document onto the typed draft shape, in place.\n *\n * A document authored before the vNext draft shape keeps its per-block props\n * only in the BlockNote `document` fragment; `qi.flow.nodes` carries the graph\n * with empty `props`. The runner cannot read such a document: it has no action\n * contract, no execution owner and no definition digest, and `readFlowDocument`\n * treats the fragment as the authority (`nodePropsAreAuthoritative`).\n *\n * Adoption copies the fragment props onto the nodes that have none, marks the\n * document `draftSchemaVersion` 1, and then stamps the execution metadata. At\n * the moment of adoption the node props equal the fragment props, so every\n * reader sees exactly what it saw before.\n *\n * Every write is additive: a node that already has props keeps them, and a\n * document that is already vNext is only re-stamped if something is missing.\n * Calling this twice on the same document writes nothing the second time.\n *\n * Returns `true` when the document changed.\n */\nexport function adoptLegacyFlowDocument(yDoc: YDoc): boolean {\n const adopted = adoptDraftShape(yDoc);\n const stamped = ensureFlowExecutionMetadata(yDoc);\n return adopted || stamped;\n}\n\n/**\n * Per-block props recovered from the BlockNote `document` fragment.\n *\n * A legacy document stores them in one of two shapes, and a document synced\n * from a live browser editor carries both: as plain attributes on the block's\n * content element, and as a structured ProseMirror `attrs` record on the\n * `blockContainer`. `readBlocksFromFragment` reads only the first, and skips a\n * container whose id lives in `attrs.id`, so adoption reads both and merges\n * them — content attributes win, because that is the shape every other reader\n * already trusts.\n */\nfunction legacyPropsByBlockId(yDoc: YDoc): Map<string, Record<string, string>> {\n const byBlockId = new Map<string, Record<string, string>>();\n collectLegacyBlockProps(yDoc.getXmlFragment('document'), byBlockId);\n return byBlockId;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction collectLegacyBlockProps(parent: Y.XmlFragment | Y.XmlElement, out: Map<string, Record<string, string>>): void {\n for (let index = 0; index < parent.length; index += 1) {\n const child = parent.get(index);\n if (!(child instanceof Y.XmlElement)) continue;\n if (child.nodeName === 'blockContainer') readContainerProps(child, out);\n collectLegacyBlockProps(child, out);\n }\n}\n\nfunction readContainerProps(container: Y.XmlElement, out: Map<string, Record<string, string>>): void {\n const attrs = asRecord(container.getAttribute('attrs') as unknown);\n const directId = container.getAttribute('id');\n const blockId = typeof directId === 'string' && directId ? directId : typeof attrs?.id === 'string' ? attrs.id : '';\n if (!blockId) return;\n\n const props: Record<string, string> = {};\n const addAll = (source: Record<string, unknown> | undefined): void => {\n for (const [key, value] of Object.entries(source ?? {})) {\n if (typeof value === 'string' && value !== '') props[key] = value;\n }\n };\n addAll(asRecord(attrs?.props));\n const content = container.get(0);\n if (content instanceof Y.XmlElement && content.nodeName !== 'blockGroup') addAll(content.getAttributes() as Record<string, unknown>);\n\n // `createBlockContainer` hoists the colours onto the container and defaults\n // them, so fold them back only when they were actually chosen.\n const textColor = container.getAttribute('textColor');\n if (typeof textColor === 'string' && textColor !== 'default') props.textColor = textColor;\n const backgroundColor = container.getAttribute('backgroundColor');\n if (typeof backgroundColor === 'string' && backgroundColor !== 'default') props.backgroundColor = backgroundColor;\n\n if (Object.keys(props).length > 0) out.set(blockId, props);\n}\n\n/** Copy fragment props onto prop-less nodes and mark the doc as a vNext draft. */\nfunction adoptDraftShape(yDoc: YDoc): boolean {\n const meta = yDoc.getMap('qi.flow.meta');\n if (meta.get('draftSchemaVersion') === 1) return false;\n const nodes = yDoc.getMap('qi.flow.nodes');\n if (nodes.size === 0) return false;\n\n const propsByBlockId = legacyPropsByBlockId(yDoc);\n\n yDoc.transact(() => {\n for (const value of nodes.values()) {\n if (!(value instanceof Y.Map)) continue;\n const existing = value.get('props');\n if (existing && typeof existing === 'object' && Object.keys(existing).length > 0) continue;\n const blockId = value.get('blockId');\n const props = typeof blockId === 'string' ? propsByBlockId.get(blockId) : undefined;\n if (props && Object.keys(props).length > 0) value.set('props', { ...props });\n }\n meta.set('draftSchemaVersion', 1);\n });\n return true;\n}\n\n/**\n * Insert compiled flow artifacts into a live collaborative editor's Y.Doc.\n *\n * This function:\n * 1. Populates qi.flow.* Yjs maps with graph state\n * 2. Returns the compiled blocks for insertion into BlockNote\n *\n * Should be called ONCE when the editor connects to an empty document.\n *\n * Note: Block insertion into BlockNote must be done by the caller via\n * `editor.insertBlocks()` because BlockNote's API is not accessible here\n * without pulling in React dependencies.\n */\nexport function hydrateYDocFromCompiledFlow(yDoc: YDoc, compiled: CompiledFlow): void {\n yDoc.transact(() => {\n // ── qi.flow.meta ──\n const flowMeta = yDoc.getMap('qi.flow.meta');\n for (const [key, value] of Object.entries(compiled.meta)) {\n if (value !== undefined) {\n flowMeta.set(key, value);\n }\n }\n const draftRevision = nextDraftRevision(yDoc, flowMeta.get('draftRevision'));\n flowMeta.set('draftSchemaVersion', 1);\n flowMeta.set('draftRevision', draftRevision);\n\n // ── qi.flow.nodes ──\n const flowNodes = yDoc.getMap('qi.flow.nodes');\n for (const [nodeId, node] of Object.entries(compiled.nodes)) {\n flowNodes.set(nodeId, createYMapFromNode(node));\n }\n\n // ── qi.flow.edges ──\n const flowEdges = yDoc.getMap('qi.flow.edges');\n for (const edge of compiled.edges) {\n const yEdge = new Y.Map();\n yEdge.set('id', edge.id);\n yEdge.set('source', edge.source);\n yEdge.set('target', edge.target);\n yEdge.set('kind', edge.kind);\n if (edge.condition) yEdge.set('condition', edge.condition);\n flowEdges.set(edge.id, yEdge);\n }\n\n // ── qi.flow.order ──\n const flowOrder = yDoc.getArray('qi.flow.order');\n for (const nodeId of compiled.order) {\n flowOrder.push([nodeId]);\n }\n\n // ── qi.flow.blockIndex ──\n const flowBlockIndex = yDoc.getMap('qi.flow.blockIndex');\n for (const [nodeId, blockId] of Object.entries(compiled.blockIndex)) {\n flowBlockIndex.set(nodeId, blockId);\n }\n writeExecutionMeta(yDoc);\n });\n}\n\n/**\n * Clear all flow graph state from a Y.Doc.\n * Used by the `full` strategy before rebuilding.\n */\nexport function clearFlowState(yDoc: YDoc): void {\n yDoc.transact(() => {\n const flowMeta = yDoc.getMap('qi.flow.meta');\n flowMeta.forEach((_, key) => flowMeta.delete(key));\n\n const flowNodes = yDoc.getMap('qi.flow.nodes');\n flowNodes.forEach((_, key) => flowNodes.delete(key));\n\n const flowEdges = yDoc.getMap('qi.flow.edges');\n flowEdges.forEach((_, key) => flowEdges.delete(key));\n\n const flowOrder = yDoc.getArray('qi.flow.order');\n if (flowOrder.length > 0) {\n flowOrder.delete(0, flowOrder.length);\n }\n\n const flowBlockIndex = yDoc.getMap('qi.flow.blockIndex');\n flowBlockIndex.forEach((_, key) => flowBlockIndex.delete(key));\n });\n}\n\n/**\n * Apply a MergeResult to the Y.Doc's flow graph state.\n *\n * - Added nodes: create new Y.Map entries\n * - Replaced nodes: delete + recreate with new data\n * - Kept nodes: untouched\n * - Edges: cleared entirely and rewritten from the merged trigger edges\n * - Order: cleared and rewritten as the merged node insertion order\n */\nexport function hydrateYDocFromMergeResult(yDoc: YDoc, mergeResult: MergeResult): void {\n const { merged, added, replaced } = mergeResult;\n\n yDoc.transact(() => {\n // ── Update meta ──\n const flowMeta = yDoc.getMap('qi.flow.meta');\n for (const [key, value] of Object.entries(merged.meta)) {\n if (value !== undefined) {\n flowMeta.set(key, value);\n }\n }\n const draftRevision = nextDraftRevision(yDoc, flowMeta.get('draftRevision'));\n flowMeta.set('draftSchemaVersion', 1);\n flowMeta.set('draftRevision', draftRevision);\n\n // ── Add / replace nodes ──\n const flowNodes = yDoc.getMap('qi.flow.nodes');\n for (const nodeId of replaced) {\n flowNodes.delete(nodeId);\n flowNodes.set(nodeId, createYMapFromNode(merged.nodes[nodeId]));\n }\n for (const nodeId of added) {\n flowNodes.set(nodeId, createYMapFromNode(merged.nodes[nodeId]));\n }\n\n // ── Rewrite edges (derived state — always recompute) ──\n const flowEdges = yDoc.getMap('qi.flow.edges');\n flowEdges.forEach((_, key) => flowEdges.delete(key));\n for (const edge of merged.edges) {\n const yEdge = new Y.Map();\n yEdge.set('id', edge.id);\n yEdge.set('source', edge.source);\n yEdge.set('target', edge.target);\n yEdge.set('kind', edge.kind);\n if (edge.condition) yEdge.set('condition', edge.condition);\n flowEdges.set(edge.id, yEdge);\n }\n\n // ── Rewrite order (derived state — always recompute) ──\n const flowOrder = yDoc.getArray('qi.flow.order');\n if (flowOrder.length > 0) {\n flowOrder.delete(0, flowOrder.length);\n }\n for (const nodeId of merged.order) {\n flowOrder.push([nodeId]);\n }\n\n // ── Update blockIndex ──\n const flowBlockIndex = yDoc.getMap('qi.flow.blockIndex');\n for (const nodeId of [...added, ...replaced]) {\n flowBlockIndex.set(nodeId, merged.blockIndex[nodeId]);\n }\n writeExecutionMeta(yDoc);\n });\n}\n\n/**\n * Initialize action state for all compiled nodes: every node reset to `idle`.\n *\n * **Takes the `Y.Doc`, not the flat `runtime` map.** This is a *reset* path, and\n * Phase A resets must land on both the run entry and the flat mirror or they\n * desynchronise permanently — see {@link resetActionState}. Seeding only the\n * flat map leaves a pre-rebuild `completed` run entry in place, and\n * `resolveActionState` rule (a) then makes the freshly-rebuilt block read as\n * already executed.\n */\nexport function initializeRuntime(yDoc: YDoc, compiled: CompiledFlow, runId?: string): void {\n // No session, nothing to seed. Authoring a flow must not create a run — and\n // `startRun` seeds its own manifest blocks the moment one is started.\n const resolvedRunId = runId ?? resolveActiveRunId(yDoc);\n if (!resolvedRunId) return;\n yDoc.transact(() => {\n for (const nodeId of compiled.order) {\n const blockId = compiled.blockIndex[nodeId];\n if (blockId) resetActionState(yDoc, resolvedRunId, blockId);\n }\n });\n}\n\n/**\n * Initialize action state for specific nodes only.\n * Used by merge/patch strategies to only initialize new or replaced nodes.\n *\n * Same dual-target reset contract as {@link initializeRuntime}.\n */\nexport function initializeRuntimeForNodes(yDoc: YDoc, compiled: CompiledFlow, nodeIds: string[], runId?: string): void {\n // Same rule as {@link initializeRuntime}: no session, no seed.\n const resolvedRunId = runId ?? resolveActiveRunId(yDoc);\n if (!resolvedRunId) return;\n yDoc.transact(() => {\n for (const nodeId of nodeIds) {\n const blockId = compiled.blockIndex[nodeId];\n if (blockId) resetActionState(yDoc, resolvedRunId, blockId);\n }\n });\n}\n\n// ─── Internal Helpers ───────────────────────────────────────────────────────\n\n/** Create a Y.Map from a CompiledFlowNode. */\nexport function createYMapFromNode(node: CompiledFlowNode): Y.Map<unknown> {\n const yNode = new Y.Map();\n yNode.set('id', node.id);\n yNode.set('blockId', node.blockId);\n yNode.set('can', node.can);\n yNode.set('with', node.with);\n yNode.set('registryType', node.registryType);\n yNode.set('executionOwner', getAction(node.registryType)?.executionOwner ?? 'agent');\n yNode.set('title', node.title);\n yNode.set('description', node.description);\n yNode.set('props', { ...node.props });\n const contract = executionContract(node);\n if (contract) yNode.set('actionContract', contract);\n if (node.phase) yNode.set('phase', node.phase);\n if (node.parallelGroup) yNode.set('parallelGroup', node.parallelGroup);\n if (node.actor) yNode.set('actor', node.actor);\n return yNode;\n}\n","import * as Y from 'yjs';\nimport type { CompiledBlock } from '../../types/baseUcan';\nimport { isYXmlElementLike } from '../yjsTypes';\nimport type { MergeResult } from './mergeFlows';\n\n/**\n * Writes compiled blocks into BlockNote's collaborative XmlFragment using the\n * ProseMirror/Yjs structure that BlockNote reads from collaboration.\n */\nexport function writeCompiledBlocksToFragment(fragment: Y.XmlFragment, blocks: CompiledBlock[]): void {\n const documentBlockGroup = getOrCreateDocumentBlockGroup(fragment);\n\n for (const block of blocks) {\n appendBlockToGroup(documentBlockGroup, block);\n }\n}\n\n/** Insert a compiled block before a known block, or append it when no anchor exists. */\nexport function insertCompiledBlockIntoFragment(fragment: Y.XmlFragment, block: CompiledBlock, beforeBlockId?: string): void {\n const blockGroup = getOrCreateDocumentBlockGroup(fragment);\n if (beforeBlockId) {\n for (let index = 0; index < blockGroup.length; index += 1) {\n const candidate = blockGroup.get(index);\n if (isYXmlElementLike(candidate) && candidate.getAttribute('id') === beforeBlockId) {\n blockGroup.insert(index, [createBlockContainer(block)]);\n return;\n }\n }\n }\n appendBlockToGroup(blockGroup, block);\n}\n\n/**\n * Remove all block containers from the document fragment.\n * Used by the `full` strategy to clear existing blocks before rebuilding.\n */\nexport function removeAllFlowBlocks(fragment: Y.XmlFragment): void {\n const blockGroup = getExistingBlockGroup(fragment);\n if (!blockGroup) return;\n\n // Delete all children from the blockGroup\n while (blockGroup.length > 0) {\n blockGroup.delete(0, 1);\n }\n}\n\n/**\n * Remove a single block container by its block ID.\n * Returns `true` if the block was found and removed.\n */\nexport function removeBlockFromFragment(fragment: Y.XmlFragment, blockId: string): boolean {\n const blockGroup = getExistingBlockGroup(fragment);\n if (!blockGroup) return false;\n\n for (let i = 0; i < blockGroup.length; i++) {\n const container = blockGroup.get(i);\n if (isYXmlElementLike(container) && container.getAttribute('id') === blockId) {\n blockGroup.delete(i, 1);\n return true;\n }\n }\n return false;\n}\n\n/**\n * Replace a block container in-place (same position) by its block ID.\n * Returns `true` if the block was found and replaced.\n */\nexport function replaceBlockInFragment(fragment: Y.XmlFragment, block: CompiledBlock): boolean {\n const blockGroup = getExistingBlockGroup(fragment);\n if (!blockGroup) return false;\n\n for (let i = 0; i < blockGroup.length; i++) {\n const container = blockGroup.get(i);\n if (isYXmlElementLike(container) && container.getAttribute('id') === block.id) {\n blockGroup.delete(i, 1);\n const newContainer = createBlockContainer(block);\n blockGroup.insert(i, [newContainer]);\n return true;\n }\n }\n return false;\n}\n\n/**\n * Swap the document positions of two block containers, identified by block id.\n * Uses `clone()` so each block — including any inline/prose content — moves\n * intact (its `id` attribute is preserved, so runtime/graph linkage keyed on the\n * block id survives). Non-target blocks between them keep their positions.\n *\n * Returns `false` if either id is missing or they resolve to the same container.\n */\nexport function swapBlocksInFragment(fragment: Y.XmlFragment, idA: string, idB: string): boolean {\n const blockGroup = getExistingBlockGroup(fragment);\n if (!blockGroup) return false;\n\n let ia = -1;\n let ib = -1;\n for (let i = 0; i < blockGroup.length; i++) {\n const container = blockGroup.get(i);\n if (isYXmlElementLike(container)) {\n const id = container.getAttribute('id');\n if (id === idA) ia = i;\n else if (id === idB) ib = i;\n }\n }\n if (ia < 0 || ib < 0 || ia === ib) return false;\n\n const lo = Math.min(ia, ib);\n const hi = Math.max(ia, ib);\n const loClone = (blockGroup.get(lo) as Y.XmlElement).clone();\n const hiClone = (blockGroup.get(hi) as Y.XmlElement).clone();\n\n // Rewrite the higher index first so the lower index stays valid.\n blockGroup.delete(hi, 1);\n blockGroup.insert(hi, [loClone]);\n blockGroup.delete(lo, 1);\n blockGroup.insert(lo, [hiClone]);\n return true;\n}\n\n/**\n * Apply a MergeResult to the document fragment.\n * Replaces changed blocks in-place and appends new blocks.\n */\nexport function applyMergeResultToFragment(fragment: Y.XmlFragment, mergeResult: MergeResult): void {\n const documentBlockGroup = getOrCreateDocumentBlockGroup(fragment);\n\n // Build a lookup from nodeId → block for the merged output\n const blockByNodeId = new Map<string, CompiledBlock>();\n for (const block of mergeResult.merged.blocks) {\n // blockId is `flow_block_{nodeId}`, reverse-map to nodeId\n for (const [nodeId, blockId] of Object.entries(mergeResult.merged.blockIndex)) {\n if (blockId === block.id) {\n blockByNodeId.set(nodeId, block);\n break;\n }\n }\n }\n\n // Replace existing blocks that were patched\n for (const nodeId of mergeResult.replaced) {\n const block = blockByNodeId.get(nodeId);\n if (block) {\n replaceBlockInFragment(fragment, block);\n }\n }\n\n // Append new blocks\n for (const nodeId of mergeResult.added) {\n const block = blockByNodeId.get(nodeId);\n if (block) {\n appendBlockToGroup(documentBlockGroup, block);\n }\n }\n}\n\n/**\n * Read all blocks (with their props) back out of the document fragment.\n *\n * The inverse of `writeCompiledBlocksToFragment` / `createBlockContainer`: walks the single\n * `blockGroup` and, for each `blockContainer`, returns `{ id, type, props }` where `props` is\n * the inner `blockContent` element's attributes — the **authoritative per-block prop store**\n * (the `qi.flow.nodes` map omits props, so this is the only place to recover them headlessly).\n *\n * `textColor`/`backgroundColor` are folded back into `props` only when non-`'default'`, so a\n * default-styled block round-trips to exactly its content props. Note: props written as `''`\n * are not persisted by `createBlockContainer`, so they do not reappear here.\n *\n * Returns `[]` when the fragment has no `blockGroup`.\n */\nexport function readBlocksFromFragment(fragment: Y.XmlFragment): CompiledBlock[] {\n const blockGroup = getExistingBlockGroup(fragment);\n if (!blockGroup) return [];\n\n const blocks: CompiledBlock[] = [];\n for (let i = 0; i < blockGroup.length; i++) {\n const container = blockGroup.get(i);\n if (!isYXmlElementLike(container) || container.nodeName !== 'blockContainer') continue;\n\n const id = container.getAttribute('id');\n if (typeof id !== 'string' || id.length === 0) continue;\n\n const content = container.get(0);\n if (!isYXmlElementLike(content)) continue;\n\n const props: Record<string, string> = { ...(content.getAttributes() as Record<string, string>) };\n\n // createBlockContainer hoists the color attrs onto the container and defaults them to\n // 'default'. Fold them back only when explicitly set, so a default block's props match\n // exactly what was written (no color noise).\n const textColor = container.getAttribute('textColor');\n if (typeof textColor === 'string' && textColor !== 'default') props.textColor = textColor;\n const backgroundColor = container.getAttribute('backgroundColor');\n if (typeof backgroundColor === 'string' && backgroundColor !== 'default') props.backgroundColor = backgroundColor;\n\n blocks.push({ id, type: content.nodeName, props });\n }\n\n return blocks;\n}\n\n// ─── Internal Helpers ───────────────────────────────────────────────────────\n\n/** Create a blockContainer XmlElement from a CompiledBlock. */\nfunction createBlockContainer(block: CompiledBlock): Y.XmlElement {\n const blockContainer = new Y.XmlElement('blockContainer');\n const { backgroundColor: rawBackgroundColor, textColor: rawTextColor, ...contentProps } = block.props;\n\n blockContainer.setAttribute('id', block.id);\n blockContainer.setAttribute('textColor', rawTextColor || 'default');\n blockContainer.setAttribute('backgroundColor', rawBackgroundColor || 'default');\n\n const blockContent = new Y.XmlElement(block.type);\n for (const [key, value] of Object.entries(contentProps)) {\n if (value !== '') {\n blockContent.setAttribute(key, value);\n }\n }\n\n blockContainer.insert(0, [blockContent]);\n return blockContainer;\n}\n\n/** Append a single block to a blockGroup. */\nfunction appendBlockToGroup(blockGroup: Y.XmlElement, block: CompiledBlock): void {\n const container = createBlockContainer(block);\n blockGroup.insert(blockGroup.length, [container]);\n}\n\nfunction getOrCreateDocumentBlockGroup(fragment: Y.XmlFragment): Y.XmlElement {\n if (fragment.length === 0) {\n const blockGroup = new Y.XmlElement('blockGroup');\n fragment.insert(0, [blockGroup]);\n return blockGroup;\n }\n\n if (fragment.length === 1) {\n const rootNode = fragment.get(0);\n if (isYXmlElementLike(rootNode) && rootNode.nodeName === 'blockGroup') {\n return rootNode;\n }\n }\n\n throw new Error('Unexpected BlockNote document shape in XmlFragment. ' + 'Expected a single top-level blockGroup node.');\n}\n\n/** Get the existing blockGroup or null if the fragment is empty. */\nfunction getExistingBlockGroup(fragment: Y.XmlFragment): Y.XmlElement | null {\n if (fragment.length === 0) return null;\n\n if (fragment.length === 1) {\n const rootNode = fragment.get(0);\n if (isYXmlElementLike(rootNode) && rootNode.nodeName === 'blockGroup') {\n return rootNode;\n }\n }\n\n return null;\n}\n","import type { Doc as YDoc, Map as YMap } from 'yjs';\nimport type { CompiledFlow, CompiledFlowNode, CompiledEdge, CompiledBlock } from '../../types/baseUcan';\nimport { COMPILED_BLOCK_TYPE } from './blockMapping';\nimport { isYMapLike } from '../yjsTypes';\n\n/**\n * Read the current compiled flow state from a live Y.Doc.\n *\n * This is the inverse of `hydrateYDocFromCompiledFlow`. It extracts the flow\n * graph state from Yjs maps so that the pure merge/patch logic can operate\n * on plain objects.\n *\n * Returns `null` if the document has no flow state.\n */\nexport function readCompiledFlowFromYDoc(yDoc: YDoc): CompiledFlow | null {\n // ── qi.flow.meta ──\n const flowMeta = yDoc.getMap('qi.flow.meta');\n\n // ── qi.flow.nodes ──\n // Read this BEFORE deciding null. Old behavior returned null on empty\n // flowId, which broke the read for any flow whose plan was authored\n // with `flowId: \"\"` (the documented agent convention). The right\n // signal that the room has no flow is \"no nodes AND no meta,\" not\n // \"flowId is falsy.\"\n const flowNodes = yDoc.getMap('qi.flow.nodes');\n const nodes: Record<string, CompiledFlowNode> = {};\n flowNodes.forEach((value, nodeId) => {\n if (isYMapLike<unknown>(value)) {\n nodes[nodeId] = yMapToFlowNode(value);\n }\n });\n\n if (flowNodes.size === 0 && flowMeta.size === 0) {\n return null;\n }\n\n const meta = {\n flowId: (flowMeta.get('flowId') as string) || '',\n title: (flowMeta.get('title') as string) || '',\n goal: flowMeta.get('goal') as string | undefined,\n version: (flowMeta.get('version') as string) || '',\n flowOwnerDid: (flowMeta.get('flowOwnerDid') as string) || '',\n flowUri: flowMeta.get('flowUri') as string | undefined,\n compiledAt: (flowMeta.get('compiledAt') as string) || '',\n compiledFrom: 'BaseUcanFlow' as const,\n };\n\n // ── qi.flow.edges ──\n const flowEdges = yDoc.getMap('qi.flow.edges');\n const edges: CompiledEdge[] = [];\n flowEdges.forEach((value) => {\n if (isYMapLike<unknown>(value)) {\n edges.push(yMapToEdge(value));\n }\n });\n\n // ── qi.flow.order ──\n const flowOrder = yDoc.getArray<string>('qi.flow.order');\n const order = flowOrder.toArray();\n\n // ── qi.flow.blockIndex ──\n const flowBlockIndex = yDoc.getMap('qi.flow.blockIndex');\n const blockIndex: Record<string, string> = {};\n flowBlockIndex.forEach((value, key) => {\n blockIndex[key] = value as string;\n });\n\n // ── Reconstruct blocks from nodes (in topological order) ──\n const blocks: CompiledBlock[] = order\n .filter((nodeId) => nodes[nodeId])\n .map((nodeId) => {\n const node = nodes[nodeId];\n return {\n id: node.blockId,\n type: COMPILED_BLOCK_TYPE,\n props: { ...node.props },\n };\n });\n\n return { meta, blocks, nodes, edges, order, blockIndex };\n}\n\n// ─── Internal Helpers ───────────────────────────────────────────────────────\n\nfunction yMapToFlowNode(yMap: YMap<unknown>): CompiledFlowNode {\n return {\n id: (yMap.get('id') as string) || '',\n blockId: (yMap.get('blockId') as string) || '',\n can: (yMap.get('can') as string) || '',\n with: (yMap.get('with') as string) || '',\n registryType: (yMap.get('registryType') as string) || '',\n title: (yMap.get('title') as string) || '',\n description: (yMap.get('description') as string) || '',\n props: (yMap.get('props') as Record<string, string>) || {},\n phase: yMap.get('phase') as string | undefined,\n parallelGroup: yMap.get('parallelGroup') as string | undefined,\n actor: yMap.get('actor') as CompiledFlowNode['actor'],\n };\n}\n\nfunction yMapToEdge(yMap: YMap<unknown>): CompiledEdge {\n return {\n id: (yMap.get('id') as string) || '',\n source: (yMap.get('source') as string) || '',\n target: (yMap.get('target') as string) || '',\n // Only 'trigger' edges exist. Legacy 'dependency' edges from older\n // Y.Docs (before dependsOn was removed) get coerced — they'll be\n // overwritten on the next compile pass.\n kind: 'trigger',\n condition: yMap.get('condition') as CompiledEdge['condition'],\n };\n}\n","import type { CompiledFlow, CompiledFlowNode, CompiledEdge, CompiledBlock } from '../../types/baseUcan';\nimport { COMPILED_BLOCK_TYPE } from './blockMapping';\n\n// ─── Public API ─────────────────────────────────────────────────────────────\n\n/** Describes what changed when merging two compiled flows. */\nexport interface MergeResult {\n /** The merged compiled flow (full state). */\n merged: CompiledFlow;\n /** Node IDs that were added (new in incoming, not in existing). */\n added: string[];\n /** Node IDs that were replaced (patch only — existed and was overwritten). */\n replaced: string[];\n /** Node IDs that were kept unchanged from existing. */\n kept: string[];\n}\n\n/**\n * Merge an incoming compiled flow into an existing one.\n *\n * This is a **pure function** — no Yjs, no side effects.\n *\n * Strategies:\n * - `merge`: existing nodes win on ID collision. Incoming nodes with new IDs\n * are added. Existing nodes are never modified.\n * - `patch`: incoming nodes overwrite existing nodes on ID collision. Incoming\n * nodes with new IDs are added. Existing nodes not in incoming are kept.\n *\n * Edges in the merged result are the union of edges from both sides, filtered\n * to those whose source and target both exist in the merged node set, with\n * duplicates collapsed by edge id. Order is the merged node insertion order\n * (existing first, then newly added) — there is no topological sort because\n * there is no inferred dependency relationship.\n */\nexport function mergeCompiledFlows(existing: CompiledFlow, incoming: CompiledFlow, strategy: 'merge' | 'patch'): MergeResult {\n const added: string[] = [];\n const replaced: string[] = [];\n const kept: string[] = [];\n\n // Build the merged node set\n const mergedNodes: Record<string, CompiledFlowNode> = {};\n const mergedBlockIndex: Record<string, string> = {};\n\n // Start with existing nodes\n for (const [nodeId, node] of Object.entries(existing.nodes)) {\n mergedNodes[nodeId] = node;\n mergedBlockIndex[nodeId] = existing.blockIndex[nodeId];\n }\n\n // Apply incoming nodes based on strategy\n for (const [nodeId, node] of Object.entries(incoming.nodes)) {\n if (mergedNodes[nodeId]) {\n if (strategy === 'patch') {\n // Patch: incoming overwrites existing\n mergedNodes[nodeId] = node;\n mergedBlockIndex[nodeId] = incoming.blockIndex[nodeId];\n replaced.push(nodeId);\n } else {\n // Merge: existing wins, skip incoming\n kept.push(nodeId);\n }\n } else {\n // New node in both strategies\n mergedNodes[nodeId] = node;\n mergedBlockIndex[nodeId] = incoming.blockIndex[nodeId];\n added.push(nodeId);\n }\n }\n\n // Mark existing nodes that weren't replaced as kept\n for (const nodeId of Object.keys(existing.nodes)) {\n if (!replaced.includes(nodeId)) {\n kept.push(nodeId);\n }\n }\n\n // Merge edges from both sides, filter to those whose endpoints survive,\n // dedupe by id (last write wins on dupes — irrelevant since edges are\n // content-derived from trigger props and identical inputs produce identical\n // edge ids).\n const edgeMap = new Map<string, CompiledEdge>();\n for (const edge of [...existing.edges, ...incoming.edges]) {\n if (mergedNodes[edge.source] && mergedNodes[edge.target]) {\n edgeMap.set(edge.id, edge);\n }\n }\n const edges = Array.from(edgeMap.values());\n\n // Order = the natural insertion order of the merged node map\n // (existing first, then newly added). No topological sort.\n const order = Object.keys(mergedNodes);\n\n // Build blocks array in the same order\n const blocks: CompiledBlock[] = order.map((nodeId) => {\n const node = mergedNodes[nodeId];\n return {\n id: node.blockId,\n type: COMPILED_BLOCK_TYPE,\n props: { ...node.props },\n };\n });\n\n // Use incoming meta (newer timestamp) but preserve existing flowId\n const meta = {\n ...incoming.meta,\n flowId: existing.meta.flowId,\n compiledAt: new Date().toISOString(),\n };\n\n return {\n merged: { meta, blocks, nodes: mergedNodes, edges, order, blockIndex: mergedBlockIndex },\n added,\n replaced,\n kept,\n };\n}\n","import type { BaseUcanFlow, CompiledFlow, CompiledFlowNode, FlowCapability, ActorConstraint, TTLConstraint, TriggerSpec } from '../../types/baseUcan';\n\n/**\n * Reconstruct a BaseUcanFlow plan from a CompiledFlow.\n *\n * This is the inverse of `compileBaseUcanFlow`. It allows the AI agent to\n * read the current flow in the same format it writes — a plain capability\n * list it can reason about, modify, and pass back to the compiler.\n *\n * This is a **pure function** — no Yjs, no side effects.\n *\n * Note: some information is lossy (e.g. conditions are stored as a JSON\n * string in props and are not fully round-tripped back to ConditionRef).\n * The core capability data (can, with, nb, trigger, actor, ttl, metadata)\n * is fully preserved.\n */\nexport function decompileToBaseUcanFlow(compiled: CompiledFlow): BaseUcanFlow {\n // Reverse of the compiler's blockIndex (blockId → nodeId), used to map\n // trigger source references — serialized as block ids in props.trigger\n // for the runtime reconciler — back into the node-id namespace the plan\n // format uses (and the compiler validates against).\n const nodeIdByBlockId: Record<string, string> = {};\n for (const [nodeId, blockId] of Object.entries(compiled.blockIndex)) {\n nodeIdByBlockId[blockId] = nodeId;\n }\n\n const capabilities: FlowCapability[] = compiled.order.map((nodeId) => {\n const node = compiled.nodes[nodeId];\n return nodeToCapability(node, nodeIdByBlockId);\n });\n\n return {\n kind: 'qi.flow.base-ucan',\n version: '1.0',\n flowId: compiled.meta.flowId,\n title: compiled.meta.title,\n goal: compiled.meta.goal,\n meta: {\n rootIssuer: compiled.meta.flowOwnerDid || undefined,\n flowUri: compiled.meta.flowUri,\n },\n capabilities,\n };\n}\n\n// ─── Internal Helpers ───────────────────────────────────────────────────────\n\nfunction nodeToCapability(node: CompiledFlowNode, nodeIdByBlockId: Record<string, string>): FlowCapability {\n const cap: FlowCapability = {\n id: node.id,\n can: node.can,\n with: node.with,\n };\n\n // ── nb (caveats) — stored as JSON string in props.inputs ──\n if (node.props.inputs) {\n try {\n const nb = JSON.parse(node.props.inputs);\n if (nb && typeof nb === 'object' && Object.keys(nb).length > 0) {\n cap.nb = nb;\n }\n } catch {\n // props.inputs wasn't valid JSON — skip\n }\n }\n\n // ── Workflow topology ──\n if (node.parallelGroup) {\n cap.parallelGroup = node.parallelGroup;\n }\n\n if (node.phase) {\n cap.phase = node.phase;\n }\n\n // ── Authorization ──\n if (node.actor) {\n cap.actor = { ...node.actor } as ActorConstraint;\n }\n\n // ── TTL — stored in individual props ──\n const ttl: TTLConstraint = {};\n if (node.props.ttlAbsoluteDueDate) ttl.absoluteDueDate = node.props.ttlAbsoluteDueDate;\n if (node.props.ttlFromEnablement) ttl.fromEnablement = node.props.ttlFromEnablement;\n if (node.props.ttlFromCommitment) ttl.fromCommitment = node.props.ttlFromCommitment;\n if (Object.keys(ttl).length > 0) {\n cap.ttl = ttl;\n }\n\n // ── Trigger — stored as JSON string in props.trigger ──\n // Mirrors how `nb` round-trips through props.inputs. Empty / missing /\n // unparseable trigger means manual (the compiler treats absent trigger\n // as type='manual'), so we omit the field in that case to keep the\n // round-tripped plan minimal.\n if (typeof node.props.trigger === 'string' && node.props.trigger.length > 0) {\n try {\n const trigger = JSON.parse(node.props.trigger) as Partial<TriggerSpec>;\n if (trigger && typeof trigger === 'object' && typeof trigger.type === 'string') {\n cap.trigger = triggerToNodeIds(trigger as TriggerSpec, nodeIdByBlockId);\n }\n } catch {\n // props.trigger wasn't valid JSON — skip, treat as manual\n }\n }\n\n // ── Human-facing metadata ──\n // Title: only set if it differs from the `can` string (compiler falls back to can)\n if (node.title && node.title !== node.can) {\n cap.title = node.title;\n }\n\n if (node.description) {\n cap.description = node.description;\n }\n\n if (node.props.icon) {\n cap.icon = node.props.icon;\n }\n\n return cap;\n}\n\n/**\n * Map trigger source references from the block-id namespace back to node\n * ids so the round-tripped plan validates against the compiler. Ids with\n * no reverse-index entry pass through unchanged — that covers documents\n * compiled before the compiler remapped trigger sources, whose triggers\n * already carry node ids.\n */\nfunction triggerToNodeIds(trigger: TriggerSpec, nodeIdByBlockId: Record<string, string>): TriggerSpec {\n if (trigger.type === 'block.event' && trigger.sourceBlockId) {\n return { ...trigger, sourceBlockId: nodeIdByBlockId[trigger.sourceBlockId] ?? trigger.sourceBlockId };\n }\n if (trigger.type === 'block.event.all' && trigger.sources) {\n return {\n ...trigger,\n sources: trigger.sources.map((src) => ({ ...src, sourceBlockId: nodeIdByBlockId[src.sourceBlockId] ?? src.sourceBlockId })),\n };\n }\n return trigger;\n}\n","import * as Y from 'yjs';\nimport { MatrixProvider } from '@ixo/matrix-crdt';\nimport type { MatrixClient } from 'matrix-js-sdk';\nimport type { BaseUcanFlow, CompiledFlow, FlowStrategy } from '../../types/baseUcan';\nimport { compileBaseUcanFlow, stripActiveScheduleBindings } from './compiler';\nimport { hydrateYDocFromCompiledFlow, initializeRuntime, clearFlowState, hydrateYDocFromMergeResult, initializeRuntimeForNodes } from './hydrate';\nimport { getActionByCan } from '../actionRegistry';\nimport { writeCompiledBlocksToFragment, removeAllFlowBlocks, applyMergeResultToFragment } from './documentFragment';\nimport { readCompiledFlowFromYDoc } from './readFlow';\nimport { mergeCompiledFlows } from './mergeFlows';\nimport { decompileToBaseUcanFlow } from './decompile';\nimport { collectPhantomLegacyRun, hasLegacyRuntimeHistory, setMultiRunStorage } from '../flowEngine/runs';\nimport { createDesignPodPortalJourneyPlan } from '../designPod/template';\nimport { seedDesignPodMethodDefinition } from '../designPod/state';\nimport type { DesignPodMethodId } from '../designPod/contracts';\n\n// ─── Public Types ───────────────────────────────────────────────────────────\n\nexport interface SetupFlowOptions {\n /** The Base UCAN flow plan to compile. */\n plan: BaseUcanFlow;\n /** Matrix room ID to hydrate the flow into. */\n roomId: string;\n /** Authenticated Matrix client. */\n matrixClient: MatrixClient;\n /** DID of the user setting up the flow. */\n creatorDid: string;\n /** Optional doc ID override (defaults to plan.flowId). */\n docId?: string;\n /**\n * Room ID of the template this flow was instantiated from, if any.\n * Recorded into the root map as `source_template_id` for lineage tracking.\n */\n templateId?: string;\n /**\n * How to apply the plan to the existing document.\n * - `full` (default): wipe existing flow state and rebuild entirely.\n * - `merge`: keep existing blocks, add new capabilities from the plan.\n * - `patch`: replace matching nodes, add new ones, keep the rest.\n */\n strategy?: FlowStrategy;\n}\n\nexport interface SetupFlowResult {\n /** The compiled flow artifacts. */\n compiled: CompiledFlow;\n /** The room ID (same as input, for convenience). */\n roomId: string;\n /** The flow ID from the plan. */\n flowId: string;\n}\n\nexport interface ReadFlowOptions {\n /** Matrix room ID to read from. */\n roomId: string;\n /** Authenticated Matrix client. */\n matrixClient: MatrixClient;\n}\n\nexport interface ReadFlowResult {\n /** The current flow plan in BaseUcanFlow format (what the agent reads/writes). */\n plan: BaseUcanFlow;\n /** The compiled flow state (lower-level representation). */\n compiled: CompiledFlow;\n /** The room ID (same as input, for convenience). */\n roomId: string;\n}\n\n// ─── Public API ─────────────────────────────────────────────────────────────\n\n/**\n * Read the current Base UCAN flow plan from a Matrix room.\n *\n * Connects to the room, reads the Y.Doc, decompiles the flow state\n * back into a `BaseUcanFlow`, and disconnects. Returns `null` if the\n * room has no flow state.\n *\n * **This is the lower-level API.** It exists for cases where you need\n * to read a flow from a room you are NOT currently editing — e.g.\n * cross-room operations or background reads. For the common case of\n * \"read the flow the user is currently looking at,\" use\n * `readFlowFromEditor(editor)` instead. That function takes no\n * parameters from the agent and reads from the editor's existing\n * Y.Doc directly — no Matrix connection, no async, no room ID\n * resolution. The browser tool that exposes `read_flow` to the AI\n * agent should wrap `readFlowFromEditor`, not this function.\n */\nexport async function readFlowAsBaseUcan(options: ReadFlowOptions): Promise<ReadFlowResult | null> {\n const { roomId, matrixClient } = options;\n\n // `adoptRuns: false` is load-bearing, not a default being spelled out.\n // This function is documented as read-only and is pointed at rooms the caller\n // is not editing. Adoption is a *writer* — it materialises `runs` containers\n // — and there is no \"it never escapes\" get-out: `MatrixProvider` hooks\n // `doc.on('update')` in its constructor, and `ThrottledMatrixWriter`'s flush\n // is a lodash throttle with the default `leading: true`, so the very first\n // local write starts an HTTP send synchronously. `dispose()` calls\n // `.cancel()`, which drops only a pending *trailing* invocation; it cannot\n // abort a request already in flight.\n const { yDoc, provider } = await connectToRoom(roomId, matrixClient, { adoptRuns: false });\n\n try {\n const compiled = readCompiledFlowFromYDoc(yDoc);\n if (!compiled) return null;\n\n const plan = decompileToBaseUcanFlow(compiled);\n\n return { plan, compiled, roomId };\n } finally {\n provider.dispose();\n yDoc.destroy();\n }\n}\n\n/**\n * Minimal editor shape required by `readFlowFromEditor` and the active\n * editor registry. The full `IxoEditorType` is fine to pass — this is\n * just a structural lower bound so test harnesses can construct fake\n * editors without pulling in React dependencies.\n */\nexport interface ReadableEditor {\n _yDoc?: import('yjs').Doc;\n getRoomId?: () => string;\n}\n\n/**\n * Read the current flow from a specific editor instance, synchronously.\n *\n * Use this when you have an editor reference in hand (e.g. from inside a\n * React component, a test, or a multi-editor host that needs to target a\n * specific instance). For the common case of \"read the flow the user is\n * currently looking at,\" prefer the parameterless `readFlow()` below — it\n * uses the active editor registry so you don't have to thread an editor\n * reference through your call sites.\n *\n * Returns `null` ONLY when the editor's Y.Doc has no flow state at all\n * (no nodes AND no meta). An empty `flowId` string is no longer treated\n * as \"no flow\" — that was the historical bug where successful\n * `setup_flow` calls authored with `flowId: \"\"` (the documented agent\n * convention) showed up as null on subsequent reads.\n */\nexport function readFlowFromEditor(editor: ReadableEditor): ReadFlowResult | null {\n const yDoc = editor._yDoc;\n if (!yDoc) return null;\n\n const compiled = readCompiledFlowFromYDoc(yDoc);\n if (!compiled) return null;\n\n const plan = decompileToBaseUcanFlow(compiled);\n const roomId = editor.getRoomId?.() || '';\n\n return { plan, compiled, roomId };\n}\n\n// ─── Active editor registry ─────────────────────────────────────────────────\n//\n// Module-level state holding the editor instance the user is currently\n// interacting with. The collaborative editor mount hook\n// (`useCreateCollaborativeIxoEditor`) registers the editor on mount and\n// clears it on unmount.\n//\n// The registry exists so that exported library functions like `readFlow()`\n// and any agent browser tool can be parameterless. The agent doesn't have\n// to pass an editor reference; the editor package keeps track of which\n// instance is live.\n//\n// **Single-editor assumption.** This is a singleton. If a host app ever\n// mounts two editors in the same JS context, only the most recently\n// registered one is reachable through `readFlow()`. Use\n// `readFlowFromEditor(editor)` (the explicit form) when you need to target\n// a specific instance — tests and multi-editor hosts both go this route.\n\nlet activeEditor: ReadableEditor | null = null;\n\n/**\n * Register an editor as the current active editor. Called by the editor's\n * mount hook when the document is connected and ready. Pass `null` on\n * unmount to clear the registry.\n *\n * If a different editor is already registered, it is replaced silently —\n * the most recent registration wins. This matches the single-editor\n * assumption above.\n */\nexport function setActiveEditor(editor: ReadableEditor | null): void {\n activeEditor = editor;\n}\n\n/**\n * Get the currently registered active editor, or null if none is set.\n * Provided for cases where a caller wants to check the registry directly\n * (e.g. for diagnostics) without going through `readFlow()`.\n */\nexport function getActiveEditor(): ReadableEditor | null {\n return activeEditor;\n}\n\n/**\n * Read the current flow from the active editor, with no parameters at all.\n *\n * This is the parameterless API the AI agent's `read_flow` browser tool\n * should wrap. The browser tool literally becomes `read_flow: () => readFlow()`.\n *\n * Returns `null` if there is no active editor registered (e.g. the editor\n * hasn't finished mounting yet, or no editor is open in this JS context),\n * OR if the active editor's Y.Doc has no flow state at all.\n *\n * If `null` is returned and the user is referencing an existing flow, that\n * is a hard signal to STOP and report to the user — never silently rebuild,\n * because the duplicate-blocks bug is the inevitable consequence.\n */\nexport function readFlow(): ReadFlowResult | null {\n if (!activeEditor) {\n console.warn('[readFlow] No active editor registered. Did the editor finish mounting?');\n return null;\n }\n return readFlowFromEditor(activeEditor);\n}\n\n/**\n * One-shot function that compiles a Base UCAN flow plan and writes it\n * into a Matrix room's Y.Doc. After this completes, the room is a\n * normal flow that anyone can open via `useCreateCollaborativeIxoEditor`.\n *\n * Supports three strategies:\n * - `full` (default): clears any existing flow and rebuilds from scratch.\n * - `merge`: adds new capabilities alongside existing ones.\n * - `patch`: replaces matching nodes and adds new ones.\n */\nexport async function setupFlowFromBaseUcan(options: SetupFlowOptions): Promise<SetupFlowResult> {\n const { plan: rawPlan, roomId, matrixClient, creatorDid, docId, templateId, strategy = 'full' } = options;\n\n // The agent convention is \"leave flowId empty — set at instantiation.\"\n // The runtime is responsible for honoring that. If the plan came in with\n // an empty flowId, fill it from docId or roomId so the resulting Y.Doc\n // has a non-empty `qi.flow.meta.flowId`. Without this, downstream reads\n // that check the flowId field as a presence signal would silently treat\n // a real flow as missing — which was the read_flow null bug.\n const identified = rawPlan.flowId ? rawPlan : { ...rawPlan, flowId: docId || roomId };\n\n // Instantiation from a template is the clone path: the schedule INTENT\n // survives, the activated schedule ID never does (IXO-4429). An active\n // scheduleRef names one authorized binding, not a reusable default.\n const plan = templateId ? stripActiveScheduleBindings(identified) : identified;\n\n // 1. Compile the incoming plan (pure, synchronous)\n const incomingCompiled = compileBaseUcanFlow(plan, { getActionByCan });\n\n // 2. Connect to the Matrix room. This IS a writer path, so adoption is on:\n // every generation that opens the doc must converge on the same shape.\n const { yDoc, provider } = await connectToRoom(roomId, matrixClient, { adoptRuns: true });\n\n let finalCompiled: CompiledFlow;\n\n try {\n finalCompiled = applyFlowPlanToYDoc(yDoc, { plan, incomingCompiled, creatorDid, docId, templateId, strategy });\n\n // Wait for the provider to flush all writes to Matrix\n await provider.waitForFlush();\n } finally {\n provider.dispose();\n yDoc.destroy();\n }\n\n return {\n compiled: finalCompiled,\n roomId,\n flowId: plan.flowId,\n };\n}\n\nexport interface SeedDesignPodTemplateOptions {\n methodId: DesignPodMethodId;\n roomId: string;\n matrixClient: MatrixClient;\n creatorDid: string;\n}\n\n/**\n * Turn an empty room into a ready Design POD template in one connection: the\n * journey plan compiled into blocks AND the method manifest pinned. The\n * headless replacement for the seed panel, which did these as two steps\n * against an open editor — creation-time seeding has no editor to lean on,\n * and two connections would race their own flushes.\n */\nexport async function seedDesignPodTemplateFlow(options: SeedDesignPodTemplateOptions): Promise<SetupFlowResult> {\n const { methodId, roomId, matrixClient, creatorDid } = options;\n const rawPlan = createDesignPodPortalJourneyPlan(methodId);\n const plan = rawPlan.flowId ? rawPlan : { ...rawPlan, flowId: roomId };\n const incomingCompiled = compileBaseUcanFlow(plan, { getActionByCan });\n const { yDoc, provider } = await connectToRoom(roomId, matrixClient, { adoptRuns: true });\n let finalCompiled: CompiledFlow;\n try {\n finalCompiled = applyFlowPlanToYDoc(yDoc, { plan, incomingCompiled, creatorDid, strategy: 'full' });\n seedDesignPodMethodDefinition(yDoc, methodId);\n await provider.waitForFlush();\n } finally {\n provider.dispose();\n yDoc.destroy();\n }\n return { compiled: finalCompiled, roomId, flowId: plan.flowId };\n}\n\nexport interface ApplyFlowPlanOptions {\n plan: BaseUcanFlow;\n /** `compileBaseUcanFlow(plan, …)` — passed in so this function stays synchronous and pure of the registry. */\n incomingCompiled: CompiledFlow;\n creatorDid: string;\n docId?: string;\n templateId?: string;\n strategy: FlowStrategy;\n /** Session run to (re-)initialise. Phase A: always the single legacy run. */\n runId?: string;\n}\n\n/**\n * Apply a compiled plan to an already-connected Y.Doc — the whole doc-mutating\n * body of {@link setupFlowFromBaseUcan}, with no Matrix in it.\n *\n * Extracted so the rebuild path is directly testable. It is the path that\n * poisons a live room if it is not run-aware: block ids are deterministic\n * (`flow_block_<nodeId>`), so a `full` rebuild that clears only the flat\n * `runtime` map leaves the pre-rebuild `completed` run entries matching the\n * newly-written blocks one-for-one, and every one of them reads back as\n * pre-completed.\n */\nexport function applyFlowPlanToYDoc(yDoc: Y.Doc, options: ApplyFlowPlanOptions): CompiledFlow {\n const { plan, incomingCompiled, creatorDid, docId, templateId, strategy, runId } = options;\n\n const root = yDoc.getMap('root');\n const fragment = yDoc.getXmlFragment('document');\n const existingFlow = readCompiledFlowFromYDoc(yDoc);\n\n if (strategy === 'full') {\n // ── Full strategy: clear existing state and rebuild ──\n if (existingFlow) {\n clearFlowState(yDoc);\n removeAllFlowBlocks(fragment);\n // Preserve per-action execution state: run facts and terminal summaries\n // are immutable history even when the live definition is replaced.\n }\n\n // Set metadata\n setRootMetadata(yDoc, root, plan, creatorDid, docId, templateId);\n\n hydrateYDocFromCompiledFlow(yDoc, incomingCompiled);\n\n if (!existingFlow) {\n initializeRuntime(yDoc, incomingCompiled, runId);\n }\n\n yDoc.transact(() => {\n writeCompiledBlocksToFragment(fragment, incomingCompiled.blocks);\n });\n\n return incomingCompiled;\n }\n\n // ── Merge / Patch strategy ──\n if (!existingFlow) {\n // No existing flow — fall back to full behavior\n setRootMetadata(yDoc, root, plan, creatorDid, docId, templateId);\n\n hydrateYDocFromCompiledFlow(yDoc, incomingCompiled);\n\n initializeRuntime(yDoc, incomingCompiled, runId);\n\n yDoc.transact(() => {\n writeCompiledBlocksToFragment(fragment, incomingCompiled.blocks);\n });\n\n return incomingCompiled;\n }\n\n // Merge or patch the incoming plan into the existing flow\n const mergeResult = mergeCompiledFlows(existingFlow, incomingCompiled, strategy);\n\n hydrateYDocFromMergeResult(yDoc, mergeResult);\n\n const nodesToInit = [...mergeResult.added, ...mergeResult.replaced];\n initializeRuntimeForNodes(yDoc, mergeResult.merged, nodesToInit, runId);\n\n yDoc.transact(() => {\n applyMergeResultToFragment(fragment, mergeResult);\n });\n\n return mergeResult.merged;\n}\n\n// ─── Internal Helpers ───────────────────────────────────────────────────────\n\ninterface ConnectToRoomOptions {\n /**\n * Whether this entry point is allowed to write. `true` collects the phantom\n * run left behind by pre-migration builds; `false` leaves the doc\n * byte-identical to what the room sent us.\n *\n * **Required, not defaulted.** Every caller must state which side of the\n * read/write line it is on, so a future read-only entry point cannot inherit\n * a writer's default by omission.\n */\n adoptRuns: boolean;\n}\n\n/** Connect to a Matrix room and return a synced Y.Doc + provider. */\nasync function connectToRoom(roomId: string, matrixClient: MatrixClient, options: ConnectToRoomOptions): Promise<{ yDoc: Y.Doc; provider: MatrixProvider }> {\n const yDoc = new Y.Doc();\n\n const client = matrixClient;\n (client as any).canSupportVoip = false;\n (client as any).clientOpts = { lazyLoadMembers: true };\n\n const provider = new MatrixProvider(\n yDoc,\n client,\n { type: 'id', id: roomId },\n {\n translator: {\n updateEventType: 'matrix-crdt.doc_update',\n snapshotEventType: 'matrix-crdt.doc_snapshot',\n enableMediaSnapshots: true,\n },\n enableExperimentalWebrtcSync: false,\n enableAwareness: false,\n reader: { snapshotInterval: 10 },\n writer: { flushInterval: 300, retryIfForbiddenInterval: 30000 },\n }\n );\n\n await new Promise<void>((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(new Error(`Timed out connecting to room ${roomId}`));\n }, 30000);\n\n provider.onDocumentAvailable(() => {\n clearTimeout(timeout);\n resolve();\n });\n\n provider.onDocumentUnavailable(() => {\n clearTimeout(timeout);\n reject(new Error(`Room ${roomId} is unavailable`));\n });\n\n provider.initialize().catch((err: Error) => {\n clearTimeout(timeout);\n reject(err);\n });\n });\n\n // The headless counterpart of the connect-time collection in\n // `useCollaborativeIxoEditor`: remove the phantom run that pre-migration\n // builds created here. Connecting to a room creates nothing else — a run now\n // comes only from starting a session or migrating a legacy flow.\n //\n // Gated on `options.adoptRuns` because **collection is a writer**, and this\n // helper is shared with read-only entry points. `provider.canWrite` alone is\n // not that gate: it reports whether the homeserver would accept our writes,\n // not whether this caller is entitled to make any. Nor is disposal a gate —\n // `MatrixProvider` hooks `doc.on('update')` in its constructor and the\n // throttled writer flushes on the leading edge, so the send is already in\n // flight before `dispose()` runs, and `.cancel()` only drops a queued\n // trailing flush. A documented read-only API must not create containers in\n // someone else's room.\n if (options.adoptRuns && provider.canWrite) {\n collectPhantomLegacyRun(yDoc);\n }\n\n return { yDoc, provider };\n}\n\n/** Set root metadata on the Y.Doc (shared between full and fallback paths). */\nfunction setRootMetadata(yDoc: Y.Doc, root: Y.Map<unknown>, plan: BaseUcanFlow, creatorDid: string, docId?: string, templateId?: string): void {\n yDoc.transact(() => {\n if (!root.get('@context')) root.set('@context', 'https://ixo.world/flow/0.3');\n if (!root.get('_type')) root.set('_type', 'ixo.flow.crdt');\n if (!root.get('schema_version')) root.set('schema_version', '0.3');\n if (!root.get('doc_id')) root.set('doc_id', docId || plan.flowId);\n if (!root.get('createdAt')) root.set('createdAt', new Date().toISOString());\n if (!root.get('createdBy')) root.set('createdBy', creatorDid);\n root.set('flowOwnerDid', creatorDid);\n\n // A flow created now is session-based from birth.\n //\n // The condition is the *absence of pre-session history*, not the absence of\n // the version key: version 1 is the default precisely when the key is\n // missing, so keying off that would silently latch every legacy document\n // the moment someone edited its definition — a one-way migration nobody\n // asked for. A document with no history has nothing to migrate, so latching\n // it here is the same no-op that `migrateFlowToSessions` would perform.\n if (!hasLegacyRuntimeHistory(yDoc)) setMultiRunStorage(yDoc);\n\n // Template lineage — record alongside doc_id, never overwriting an\n // existing value (e.g. one stamped at clone time).\n if (templateId && !root.get('source_template_id')) {\n root.set('source_template_id', templateId);\n }\n\n const titleText = yDoc.getText('title');\n if (titleText.length === 0 && plan.title) {\n titleText.insert(0, plan.title);\n }\n });\n}\n","import * as Y from 'yjs';\nimport type { Doc as YDoc } from 'yjs';\nimport type { ActorConstraint, CompiledBlock, CompiledEdge, CompiledFlow, CompiledFlowNode, FlowCapability } from '../../types/baseUcan';\nimport type { FlowNodeRuntimeState } from '../../types/authorization';\nimport { sha256Digest } from '../actionRegistry/digest';\nimport { getAction } from '../actionRegistry/registry';\nimport { readCompiledFlowFromYDoc } from './readFlow';\nimport { compileBlockProps, COMPILED_BLOCK_TYPE } from './blockMapping';\nimport { createYMapFromNode } from './hydrate';\nimport { isYMapLike, isYXmlElementLike } from '../yjsTypes';\nimport { readActionState, resolveRunIdForExecution, resolveRunIdForRead, writeActionState } from '../flowEngine/runs';\nimport {\n readBlocksFromFragment,\n insertCompiledBlockIntoFragment,\n replaceBlockInFragment,\n removeBlockFromFragment,\n removeAllFlowBlocks,\n writeCompiledBlocksToFragment,\n swapBlocksInFragment,\n} from './documentFragment';\n\n/**\n * A single flow node as read from a live Y.Doc, assembled from all three sources:\n * structure (`qi.flow.*`), per-block `props` (the `document` fragment), and per-block\n * `runtime` (the `runtime` map). `props` and `runtime` are what the graph map cannot provide.\n */\nexport interface FlowDocumentNode {\n nodeId: string;\n blockId: string;\n can: string;\n with: string;\n title: string;\n description: string;\n /** Authoritative per-block props, recovered from the document fragment. */\n props: Record<string, string>;\n /** Per-block runtime; `{}` for a fresh/never-run node (e.g. a template). */\n runtime: FlowNodeRuntimeState;\n}\n\nexport interface FlowDocumentRead {\n meta: CompiledFlow['meta'];\n order: string[];\n edges: CompiledEdge[];\n blockIndex: Record<string, string>;\n nodes: FlowDocumentNode[];\n}\n\n// ─── Read ─────────────────────────────────────────────────────────────────────\n\n/**\n * Read a flow document **losslessly** from a headless Y.Doc, in one call.\n *\n * Why this exists: `readCompiledFlowFromYDoc` returns nodes with **empty `props`** (the\n * `qi.flow.nodes` map omits props — they live only in the `document` fragment), and\n * `decompileToBaseUcanFlow` is lossy for the same reason. `readFlowDocument` merges the three\n * sources so a consumer (e.g. an authoring agent) sees the *true* current flow:\n *\n * - structure ← `readCompiledFlowFromYDoc` (nodes, order, edges, `can`/`with`)\n * - per-block props ← `readBlocksFromFragment` (inputs/conditions/trigger/ttl/icon/…)\n * - per-block runtime ← the run's `actions` map, resolved against the flat `runtime` mirror\n *\n * For vNext drafts, complete node-map props are authoritative and the BlockNote\n * fragment is a rebuildable projection. Pre-vNext documents retain the fragment\n * as their read authority until they are explicitly republished.\n *\n * Returns `null` when the doc has no flow at all (mirrors `readCompiledFlowFromYDoc`).\n */\nexport function readFlowDocument(yDoc: YDoc, runId?: string): FlowDocumentRead | null {\n const compiled = readCompiledFlowFromYDoc(yDoc);\n if (!compiled) return null;\n\n const propsByBlockId = new Map<string, Record<string, string>>();\n for (const block of readBlocksFromFragment(yDoc.getXmlFragment('document'))) {\n propsByBlockId.set(block.id, block.props);\n }\n\n const resolvedRunId = resolveRunIdForRead(yDoc, runId);\n const nodePropsAreAuthoritative = yDoc.getMap('qi.flow.meta').get('draftSchemaVersion') === 1;\n\n const nodes: FlowDocumentNode[] = compiled.order\n .filter((nodeId) => compiled.nodes[nodeId])\n .map((nodeId) => {\n const node = compiled.nodes[nodeId];\n const projectedProps = propsByBlockId.get(node.blockId) ?? {};\n const props = nodePropsAreAuthoritative && Object.keys(node.props ?? {}).length > 0 ? { ...node.props } : projectedProps;\n // Pure read — `readActionState` never writes, so this stays safe on a\n // read-only viewer and on a flow with no session at all.\n const runtime: FlowNodeRuntimeState = resolvedRunId ? readActionState(yDoc, resolvedRunId, node.blockId) : {};\n\n return {\n nodeId,\n blockId: node.blockId,\n can: node.can,\n with: node.with,\n title: props.title ?? node.title,\n description: props.description ?? node.description,\n props,\n runtime,\n };\n });\n\n return {\n meta: compiled.meta,\n order: compiled.order,\n edges: compiled.edges,\n blockIndex: compiled.blockIndex,\n nodes,\n };\n}\n\n// ─── Add (template authoring — the inverse of removeFlowNode) ─────────────────\n\nexport interface AddFlowNodeOptions {\n /** Registry action type, e.g. `'qi/form.submit'`. Must exist in the registry. */\n type: string;\n /** Insert into the logical order right after this node id; appended to the end if omitted. */\n afterNodeId?: string;\n /** Optional starting title (defaults to the action's `can` / type). */\n title?: string;\n /** Optional extra block props merged over the compiled defaults. */\n props?: Record<string, string>;\n /** Stable ids supplied by a graph-aware command. Generated only for legacy callers. */\n nodeId?: string;\n blockId?: string;\n}\n\n/**\n * Add a step to the flow document — the inverse of `removeFlowNode`. Inserts an\n * attr-only `action` block into the `document` fragment and registers the\n * matching `qi.flow.*` structure (`nodes`, `blockIndex`, `order`) in one\n * transaction, mirroring exactly what the compiler's `hydrate` writes for a\n * single node. No recompile, no runtime entry (a template node is never-run).\n *\n * Returns the new ids, or `null` if `type` is not a known registry action.\n */\nexport function addFlowNode(yDoc: YDoc, opts: AddFlowNodeOptions): { nodeId: string; blockId: string } | null {\n const action = getAction(opts.type);\n if (!action) return null;\n\n const nodeId = opts.nodeId ?? `node_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;\n const blockId = opts.blockId ?? `flow_block_${nodeId}`;\n if (yDoc.getMap('qi.flow.nodes').has(nodeId) || [...yDoc.getMap('qi.flow.blockIndex').values()].includes(blockId)) return null;\n\n const flowId = (yDoc.getMap('qi.flow.meta').get('flowId') as string | undefined) || '';\n const withUri = flowId ? `ixo:flow:${flowId}:${nodeId}` : `ixo:flow:${nodeId}`;\n const can = action.can ?? '';\n const title = opts.title || can || action.type;\n\n const cap: FlowCapability = { id: nodeId, can, with: withUri, title, nb: {} };\n const props: Record<string, string> = { ...compileBlockProps(cap, action.type), triggerMode: 'manual', ...(opts.props ?? {}) };\n\n const node: CompiledFlowNode = {\n id: nodeId,\n blockId,\n can,\n with: withUri,\n registryType: action.type,\n title,\n description: '',\n props,\n };\n\n yDoc.transact(() => {\n writeCompiledBlocksToFragment(yDoc.getXmlFragment('document'), [{ id: blockId, type: COMPILED_BLOCK_TYPE, props }]);\n yDoc.getMap('qi.flow.nodes').set(nodeId, createYMapFromNode(node));\n yDoc.getMap('qi.flow.blockIndex').set(nodeId, blockId);\n\n const order = yDoc.getArray<string>('qi.flow.order');\n if (opts.afterNodeId) {\n const idx = order.toArray().indexOf(opts.afterNodeId);\n if (idx >= 0) order.insert(idx + 1, [nodeId]);\n else order.push([nodeId]);\n } else {\n order.push([nodeId]);\n }\n advanceDraftRevision(yDoc);\n });\n\n return { nodeId, blockId };\n}\n\n// ─── Per-block config writes (template authoring — surgical, no recompile) ─────\n\n/**\n * Edit one block's config props in place, in the `document` fragment. Surgical: it touches\n * only the target block (siblings untouched), does **not** recompile, and does **not** touch\n * the `runtime` map. Pass `''` for a prop to clear it (the writer drops empty values).\n *\n * Keeps the denormalized node-map fields in sync — `title`/`description` and the `actor`\n * object (derived from `authorisedActors`/`parentCapability`) live in BOTH the fragment and\n * `qi.flow.nodes`, so a fragment-only write would desync structural readers.\n *\n * Returns `false` when no block with `blockId` exists.\n */\nexport function setBlockProps(yDoc: YDoc, blockId: string, partial: Record<string, string>): boolean {\n const fragment = yDoc.getXmlFragment('document');\n const existing = readBlocksFromFragment(fragment).find((b) => b.id === blockId);\n if (!existing) return false;\n\n const nodeId = findNodeIdForBlock(yDoc, blockId);\n const node = nodeId ? yDoc.getMap('qi.flow.nodes').get(nodeId) : undefined;\n const isVNextDraft = yDoc.getMap('qi.flow.meta').get('draftSchemaVersion') === 1;\n const canonicalProps = isYMapLike<unknown>(node) ? (node.get('props') as Record<string, string> | undefined) : undefined;\n const baseline = isVNextDraft && canonicalProps ? canonicalProps : existing.props;\n const merged: Record<string, string> = { ...baseline, ...partial };\n\n let ok = false;\n yDoc.transact(() => {\n ok = replaceBlockInFragment(fragment, { id: blockId, type: existing.type, props: merged });\n\n if (isYMapLike<unknown>(node)) {\n node.set('props', { ...merged });\n if ('title' in partial) node.set('title', merged.title ?? '');\n if ('description' in partial) node.set('description', merged.description ?? '');\n if ('authorisedActors' in partial || 'parentCapability' in partial) {\n const actor = actorFromProps(merged);\n if (actor) node.set('actor', actor);\n else node.delete('actor');\n }\n }\n advanceDraftRevision(yDoc);\n });\n\n return ok;\n}\n\n/**\n * Mirror a BlockNote prop mutation into the canonical typed Flow draft.\n * BlockNote already wrote its own projection before this function runs.\n */\nexport function syncFlowNodePropsFromProjection(yDoc: YDoc, blockId: string, partial: Record<string, string>, legacyBaseline: Record<string, string> = {}): boolean {\n const nodeId = findNodeIdForBlock(yDoc, blockId);\n if (!nodeId) return false;\n const node = yDoc.getMap('qi.flow.nodes').get(nodeId);\n if (!isYMapLike<unknown>(node)) return false;\n const isVNextDraft = yDoc.getMap('qi.flow.meta').get('draftSchemaVersion') === 1;\n const projectedBaseline = readBlocksFromFragment(yDoc.getXmlFragment('document')).find((block) => block.id === blockId)?.props;\n const nodeProps = node.get('props') as Record<string, string> | undefined;\n const baseline = isVNextDraft ? nodeProps ?? legacyBaseline : projectedBaseline ?? legacyBaseline;\n if (!isVNextDraft && !nodeProps && Object.keys(baseline).length === 0) return false;\n\n yDoc.transact(() => {\n const merged = { ...baseline, ...partial };\n node.set('props', merged);\n if ('title' in partial) node.set('title', merged.title ?? '');\n if ('description' in partial) node.set('description', merged.description ?? '');\n if ('authorisedActors' in partial || 'parentCapability' in partial) {\n const actor = actorFromProps(merged);\n if (actor) node.set('actor', actor);\n else node.delete('actor');\n }\n if (isVNextDraft) advanceDraftRevision(yDoc);\n });\n return true;\n}\n\nexport interface FlowProjectionDrift {\n nodeId: string;\n blockId: string;\n kind: 'missing_block' | 'props_mismatch';\n}\n\n/** Pure projection audit. Executable meaning always comes from qi.flow.nodes. */\nexport function auditFlowProjections(yDoc: YDoc): FlowProjectionDrift[] {\n const projected = new Map(readBlocksFromFragment(yDoc.getXmlFragment('document')).map((block) => [block.id, block.props] as const));\n const drift: FlowProjectionDrift[] = [];\n yDoc.getMap('qi.flow.nodes').forEach((value, nodeId) => {\n if (!isYMapLike<unknown>(value)) return;\n const blockId = String(value.get('blockId') ?? '');\n const canonical = (value.get('props') as Record<string, string> | undefined) ?? {};\n const projection = projected.get(blockId);\n if (!projection) drift.push({ nodeId, blockId, kind: 'missing_block' });\n else if (stableProps(canonical) !== stableProps(projection)) drift.push({ nodeId, blockId, kind: 'props_mismatch' });\n });\n return drift.sort((left, right) => left.nodeId.localeCompare(right.nodeId));\n}\n\n/** Rebuild only Flow action-block props. Narrative BlockNote content is preserved. */\nexport function repairFlowProjections(yDoc: YDoc): FlowProjectionDrift[] {\n const before = auditFlowProjections(yDoc);\n if (before.length === 0) return before;\n const fragment = yDoc.getXmlFragment('document');\n const projected = new Map(readBlocksFromFragment(fragment).map((block) => [block.id, block] as const));\n const orderedNodeIds = yDoc.getArray<string>('qi.flow.order').toArray();\n yDoc.transact(() => {\n for (const item of before) {\n const node = yDoc.getMap('qi.flow.nodes').get(item.nodeId);\n if (!isYMapLike<unknown>(node)) continue;\n const props = (node.get('props') as Record<string, string> | undefined) ?? {};\n const block = projected.get(item.blockId);\n if (block) {\n replaceBlockInFragment(fragment, { ...block, props });\n continue;\n }\n\n const nodeIndex = orderedNodeIds.indexOf(item.nodeId);\n const nextProjectedBlockId = orderedNodeIds.slice(nodeIndex + 1).find((candidateNodeId) => {\n const candidate = yDoc.getMap('qi.flow.nodes').get(candidateNodeId);\n if (!isYMapLike<unknown>(candidate)) return false;\n return projected.has(String(candidate.get('blockId') ?? ''));\n });\n const nextNode = nextProjectedBlockId ? yDoc.getMap('qi.flow.nodes').get(nextProjectedBlockId) : undefined;\n const beforeBlockId = isYMapLike<unknown>(nextNode) ? String(nextNode.get('blockId') ?? '') : undefined;\n insertCompiledBlockIntoFragment(fragment, { id: item.blockId, type: COMPILED_BLOCK_TYPE, props }, beforeBlockId);\n projected.set(item.blockId, { id: item.blockId, type: COMPILED_BLOCK_TYPE, props });\n }\n yDoc.getMap('qi.flow.projections').set('document', {\n draftRevision: Number(yDoc.getMap('qi.flow.meta').get('draftRevision') ?? 0),\n repairedAt: new Date().toISOString(),\n });\n });\n return before;\n}\n\n/**\n * Remove one step from the flow document — fragment block + `qi.flow.*` entries + its\n * `runtime` entry + any edges touching it — in one transaction. Siblings untouched.\n *\n * Guards against orphaning references: if another node's trigger, condition, or a\n * `{{nodeId.output.*}}` input ref points at this node, removal is refused and the referring\n * node ids are returned so the caller can surface them.\n */\nexport function removeFlowNode(yDoc: YDoc, nodeId: string, runId?: string): { ok: true } | { ok: false; referencedBy: string[] } {\n const doc = readFlowDocument(yDoc, resolveRunIdForRead(yDoc, runId));\n if (!doc) return { ok: false, referencedBy: [] };\n\n const target = doc.nodes.find((n) => n.nodeId === nodeId);\n if (!target) return { ok: false, referencedBy: [] };\n\n const referencedBy = doc.nodes.filter((n) => n.nodeId !== nodeId && nodeReferences(n, nodeId, target.blockId)).map((n) => n.nodeId);\n if (referencedBy.length > 0) return { ok: false, referencedBy };\n\n const blockId = target.blockId;\n yDoc.transact(() => {\n removeBlockFromFragment(yDoc.getXmlFragment('document'), blockId);\n yDoc.getMap('qi.flow.nodes').delete(nodeId);\n yDoc.getMap('qi.flow.blockIndex').delete(nodeId);\n\n const order = yDoc.getArray<string>('qi.flow.order');\n const idx = order.toArray().indexOf(nodeId);\n if (idx >= 0) order.delete(idx, 1);\n\n const edges = yDoc.getMap('qi.flow.edges');\n for (const key of [...edges.keys()]) {\n const e = edges.get(key);\n if (isYMapLike<unknown>(e) && (e.get('source') === nodeId || e.get('target') === nodeId)) edges.delete(key);\n }\n\n // Do not delete run state here. Definition edits must leave frozen\n // manifests and historical action facts inspectable.\n advanceDraftRevision(yDoc);\n });\n\n return { ok: true };\n}\n\n/**\n * Reorder the flow's steps. Always rewrites the logical order (`qi.flow.order`). Also\n * reorders the visual `document` fragment to match — but only when every block is an\n * attr-only compiled block; if the doc contains inline prose, the fragment is left untouched\n * (recreating it would lose content) and only the logical order changes.\n *\n * `order` must be a permutation of the current `qi.flow.order` (same ids, no dups); returns\n * `false` otherwise.\n */\nexport function reorderFlowNodes(yDoc: YDoc, order: string[]): boolean {\n const orderArr = yDoc.getArray<string>('qi.flow.order');\n const current = orderArr.toArray();\n if (order.length !== current.length) return false;\n if (new Set(order).size !== order.length) return false;\n const currentSet = new Set(current);\n if (!order.every((id) => currentSet.has(id))) return false;\n\n const blockIndex = yDoc.getMap('qi.flow.blockIndex');\n const fragment = yDoc.getXmlFragment('document');\n\n yDoc.transact(() => {\n orderArr.delete(0, orderArr.length);\n orderArr.push(order);\n\n if (!fragmentHasContentBlocks(fragment)) {\n const blocks = readBlocksFromFragment(fragment);\n const byId = new Map(blocks.map((b) => [b.id, b] as const));\n const orderedIds = order.map((nid) => blockIndex.get(nid) as string | undefined).filter((id): id is string => !!id);\n const ordered = orderedIds.map((id) => byId.get(id)).filter((b): b is CompiledBlock => !!b);\n const extras = blocks.filter((b) => !orderedIds.includes(b.id));\n removeAllFlowBlocks(fragment);\n writeCompiledBlocksToFragment(fragment, [...ordered, ...extras]);\n }\n advanceDraftRevision(yDoc);\n });\n\n return true;\n}\n\n/**\n * Swap two step blocks by document position — the move-up/move-down primitive\n * for template authoring. Reorders the visual `document` fragment (so the change\n * is what the author sees), and keeps `qi.flow.order` consistent when BOTH\n * blocks are graph-registered nodes. Works for slash-menu (\"legacy\") blocks too,\n * since it operates on document position rather than the graph.\n *\n * Returns `false` if either block id is missing.\n */\nexport function swapFlowBlocks(yDoc: YDoc, blockIdA: string, blockIdB: string): boolean {\n const fragment = yDoc.getXmlFragment('document');\n let ok = false;\n yDoc.transact(() => {\n ok = swapBlocksInFragment(fragment, blockIdA, blockIdB);\n if (!ok) return;\n\n // Mirror the swap in the logical order for graph-registered nodes.\n const blockIndex = yDoc.getMap<string>('qi.flow.blockIndex');\n let nodeA: string | undefined;\n let nodeB: string | undefined;\n for (const [nodeId, bId] of blockIndex.entries()) {\n if (bId === blockIdA) nodeA = nodeId;\n else if (bId === blockIdB) nodeB = nodeId;\n }\n if (nodeA && nodeB) {\n const order = yDoc.getArray<string>('qi.flow.order');\n const arr = order.toArray();\n const ia = arr.indexOf(nodeA);\n const ib = arr.indexOf(nodeB);\n if (ia >= 0 && ib >= 0) {\n [arr[ia], arr[ib]] = [arr[ib], arr[ia]];\n order.delete(0, order.length);\n order.push(arr);\n }\n }\n advanceDraftRevision(yDoc);\n });\n return ok;\n}\n\n// ─── Runtime writes (copilot on a running flow — benign, non-executing) ────────\n\n/**\n * Merge a partial into a node's action state — the headless twin of the React `updateRuntime`.\n *\n * Goes through `writeActionState`, so the run entry and the flat mirror are\n * written in one transaction from one resolved `prev`. A flat-only write here\n * would be invisible to run-scoped readers the moment they land.\n */\nexport function updateNodeRuntime(yDoc: YDoc, blockId: string, partial: Partial<FlowNodeRuntimeState>, runId?: string): void {\n writeActionState(yDoc, resolveRunIdForExecution(yDoc, runId), blockId, partial);\n}\n\n/**\n * Clear a failed step back to idle so the user can cleanly re-run it. The headless twin of\n * the editor's \"Reset\" recovery affordance — benign and non-executing.\n *\n * Resetting only the flat map is the failure this exists to avoid: a surviving\n * `completed`/`failed` run entry beats a fresh `idle` flat entry under\n * `resolveActionState` rule (a), so \"Reset\" would appear to do nothing at all\n * once readers go run-first.\n */\nexport function resetStepRuntime(yDoc: YDoc, blockId: string, runId?: string): void {\n updateNodeRuntime(yDoc, blockId, { state: 'idle', error: undefined, output: {} }, runId);\n}\n\n/**\n * Pre-fill a (live) form step's answers at `runtime.output.form.answers` (a JSON string,\n * matching `FormPanel`). Merges into existing `output`; **never** sets `state:'completed'` —\n * submission stays the user's action.\n */\nexport function setFormAnswers(yDoc: YDoc, blockId: string, answers: Record<string, unknown>, runId?: string): void {\n const resolvedRunId = resolveRunIdForExecution(yDoc, runId);\n const base = readActionState(yDoc, resolvedRunId, blockId);\n const output: Record<string, any> = base.output && typeof base.output === 'object' ? base.output : {};\n const form: Record<string, any> = output.form && typeof output.form === 'object' ? output.form : {};\n writeActionState(yDoc, resolvedRunId, blockId, { output: { ...output, form: { ...form, answers: JSON.stringify(answers) } } });\n}\n\n// ─── Internal helpers ──────────────────────────────────────────────────────────\n\nfunction safeParseJson<T>(value: unknown, fallback: T): T {\n if (typeof value !== 'string' || value.length === 0) return fallback;\n try {\n return JSON.parse(value) as T;\n } catch {\n return fallback;\n }\n}\n\nfunction advanceDraftRevision(yDoc: YDoc): number {\n const meta = yDoc.getMap('qi.flow.meta');\n const current = Number(meta.get('draftRevision') ?? 0);\n if (meta.get('draftSchemaVersion') !== 1) return current;\n const next = current + 1;\n meta.set('draftRevision', next);\n meta.set(\n 'definitionDigest',\n sha256Digest({\n nodes: yDoc.getMap('qi.flow.nodes').toJSON(),\n edges: yDoc.getMap('qi.flow.edges').toJSON(),\n order: yDoc.getArray<string>('qi.flow.order').toArray(),\n })\n );\n meta.set('executionSchemaVersion', 3);\n meta.set('draftUpdatedAt', new Date().toISOString());\n return next;\n}\n\nfunction stableProps(props: Record<string, string>): string {\n return JSON.stringify(\n Object.fromEntries(\n Object.entries(props)\n .filter(([, value]) => value !== '')\n .sort(([left], [right]) => left.localeCompare(right))\n )\n );\n}\n\nfunction findNodeIdForBlock(yDoc: YDoc, blockId: string): string | undefined {\n const blockIndex = yDoc.getMap('qi.flow.blockIndex');\n for (const [nodeId, bId] of blockIndex.entries()) {\n if (bId === blockId) return nodeId;\n }\n return undefined;\n}\n\nfunction actorFromProps(props: Record<string, string>): ActorConstraint | undefined {\n const authorisedActors = safeParseJson<string[] | undefined>(props.authorisedActors, undefined);\n const parentCapability = props.parentCapability && props.parentCapability.length > 0 ? props.parentCapability : undefined;\n const hasActors = Array.isArray(authorisedActors) && authorisedActors.length > 0;\n if (!hasActors && !parentCapability) return undefined;\n const actor: ActorConstraint = {};\n if (hasActors) actor.authorisedActors = authorisedActors as string[];\n if (parentCapability) actor.parentCapability = parentCapability;\n return actor;\n}\n\nfunction nodeReferences(node: FlowDocumentNode, nodeId: string, blockId: string): boolean {\n // The compiler serializes trigger source references as block ids; docs\n // compiled before that remap carry node ids. Guard against both.\n const trigger = safeParseJson<{ sourceBlockId?: string; sources?: Array<{ sourceBlockId?: string }> } | undefined>(node.props.trigger, undefined);\n if (trigger?.sourceBlockId === nodeId || trigger?.sourceBlockId === blockId) return true;\n if (Array.isArray(trigger?.sources) && trigger.sources.some((s) => s?.sourceBlockId === nodeId || s?.sourceBlockId === blockId)) return true;\n\n const cond = safeParseJson<{ conditions?: Array<{ sourceBlockId?: string }> } | undefined>(node.props.conditions, undefined);\n if (Array.isArray(cond?.conditions) && cond.conditions.some((c) => c?.sourceBlockId === blockId)) return true;\n\n const inputs = typeof node.props.inputs === 'string' ? node.props.inputs : '';\n if (inputs.includes(`${nodeId}.output`)) return true;\n\n return false;\n}\n\nfunction fragmentHasContentBlocks(fragment: Y.XmlFragment): boolean {\n if (fragment.length === 0) return false;\n const root = fragment.get(0);\n if (!isYXmlElementLike(root) || root.nodeName !== 'blockGroup') return false;\n for (let i = 0; i < root.length; i++) {\n const container = root.get(i);\n if (!isYXmlElementLike(container)) continue;\n const content = container.get(0);\n if (isYXmlElementLike(content) && content.length > 0) return true; // inline children = prose\n }\n return false;\n}\n","import type { FlowAgentCommandType, FlowAgentPolicyDecision } from '../../types/flowAgent';\nimport type { StoredDelegation, UcanCapability } from '../../types/ucan';\nimport { capabilityPatternCoversCan } from '../actionRegistry/registry';\nimport type { UcanDelegationStore } from '../ucanDelegationStore';\nimport { capabilityForCommand } from './utils';\n\nconst COMMAND_CAPABILITIES: Record<FlowAgentCommandType, string> = {\n diagnose_blocker: 'flow/observe',\n assign_actor: 'flow/node/assign',\n notify_actor: 'flow/notify',\n execute_action: 'flow/node/execute',\n validate_external_state: 'flow/mutation/execute',\n archive_flow: 'flow/archive',\n propose_config_change: 'flow/config/propose',\n};\n\nexport function requiredCapabilityForCommand(type: FlowAgentCommandType, flowUri: string, nodeId: string): UcanCapability {\n return capabilityForCommand(COMMAND_CAPABILITIES[type], flowUri, nodeId);\n}\n\nexport function isCapabilityMatch(granted: UcanCapability, required: UcanCapability): boolean {\n return canMatches(granted.can, required.can) && resourceMatches(granted.with, required.with);\n}\n\n/**\n * Match a granted capability pattern against a required `can`.\n *\n * ⚠️ This is the **trusted flow-agent policy** matcher: it allows the global\n * `'*'` wildcard, so a delegation granting `can: '*'` matches every ability.\n * It is re-exported from `src/core/index.ts` — do not use it to gate public or\n * untrusted matching. For that, call `capabilityPatternCoversCan` directly and\n * leave `allowGlobalWildcard` off (the default), which rejects `'*'`.\n *\n * Note: the granted side is normalized (`normalizeCan`), so dotted legacy\n * grants such as `flow.notify` / `flow.*` now match `flow/notify` where they\n * were previously inert.\n */\nexport function canMatches(granted: string, required: string): boolean {\n return capabilityPatternCoversCan(granted, required, { allowGlobalWildcard: true });\n}\n\nexport function resourceMatches(granted: string, required: string): boolean {\n if (granted === '*' || granted === required) return true;\n if (granted.endsWith('*')) {\n const prefix = granted.slice(0, -1);\n return required.startsWith(prefix);\n }\n return false;\n}\n\nexport interface EvaluateFlowAgentPolicyParams {\n actorDid: string;\n commandType: FlowAgentCommandType;\n flowUri: string;\n nodeId: string;\n delegationStore?: UcanDelegationStore;\n delegations?: StoredDelegation[];\n now?: number;\n}\n\nexport function evaluateFlowAgentPolicy({\n actorDid,\n commandType,\n flowUri,\n nodeId,\n delegationStore,\n delegations,\n now = Date.now(),\n}: EvaluateFlowAgentPolicyParams): FlowAgentPolicyDecision {\n const required = requiredCapabilityForCommand(commandType, flowUri, nodeId);\n const candidates = delegations || delegationStore?.getByAudience(actorDid) || [];\n\n for (const delegation of candidates) {\n if (delegation.audienceDid !== actorDid) continue;\n if (delegation.expiration != null && delegation.expiration <= now) continue;\n if (!delegation.capabilities.some((capability) => isCapabilityMatch(capability, required))) continue;\n\n return {\n allowed: true,\n reason: 'Allowed by UCAN delegation',\n capability: required,\n proofCids: [delegation.cid, ...delegation.proofCids],\n };\n }\n\n return {\n allowed: false,\n reason: `Actor ${actorDid} lacks ${required.can} on ${required.with}`,\n capability: required,\n proofCids: [],\n };\n}\n","import type { FlowAgentActor, FlowAgentCommand, FlowAgentCommandType } from '../../types/flowAgent';\nimport type { UcanCapability } from '../../types/ucan';\nimport { computeAgentCommandId } from './store';\nimport { requiredCapabilityForCommand } from './policy';\nimport { createIntentHash } from './utils';\n\nexport interface CreateAgentCommandParams {\n type: FlowAgentCommandType;\n flowId: string;\n sessionRunId: string;\n flowUri: string;\n nodeId: string;\n actor: FlowAgentActor;\n reason: string;\n payload?: Record<string, unknown>;\n now?: number;\n}\n\nexport function createAgentCommand({ type, flowId, sessionRunId, flowUri, nodeId, actor, reason, payload = {}, now = Date.now() }: CreateAgentCommandParams): FlowAgentCommand {\n const capability: UcanCapability = requiredCapabilityForCommand(type, flowUri, nodeId);\n const id = computeAgentCommandId({ flowId, sessionRunId, nodeId, type, payload });\n return {\n id,\n type,\n flowId,\n sessionRunId,\n flowUri,\n nodeId,\n actorDid: actor.did,\n status: 'queued',\n capability,\n idempotencyKey: `${id}:${createIntentHash({ capability, payload })}`,\n createdAt: now,\n updatedAt: now,\n reason,\n payload,\n };\n}\n\nexport function validateAgentCommand(command: FlowAgentCommand): { valid: boolean; error?: string } {\n if (!command.id) return { valid: false, error: 'Command id is required' };\n if (!command.flowId) return { valid: false, error: 'flowId is required' };\n if (!command.sessionRunId) return { valid: false, error: 'sessionRunId is required' };\n if (!command.flowUri) return { valid: false, error: 'flowUri is required' };\n if (!command.nodeId) return { valid: false, error: 'nodeId is required' };\n if (!command.actorDid) return { valid: false, error: 'actorDid is required' };\n if (!command.capability?.can || !command.capability?.with) return { valid: false, error: 'capability is required' };\n if (!command.idempotencyKey) return { valid: false, error: 'idempotencyKey is required' };\n\n if (isExternalMutation(command.type) && !command.payload.validator) {\n return {\n valid: false,\n error: `${command.type} requires payload.validator for post-action read-back validation`,\n };\n }\n\n if (command.type === 'propose_config_change' && !command.payload.proposal) {\n return { valid: false, error: 'Config changes must be expressed as payload.proposal' };\n }\n\n return { valid: true };\n}\n\nexport function isExternalMutation(type: FlowAgentCommandType): boolean {\n return type === 'validate_external_state';\n}\n","import type { FlowAgentActor, FlowAgentContext } from '../../types/flowAgent';\nimport type { IxoEditorType } from '../../types/editor';\nimport type { Doc } from 'yjs';\n\nexport interface BuildFlowAgentContextParams {\n yDoc: Doc;\n flowId: string;\n sessionRunId: string;\n flowUri?: string;\n actor: FlowAgentActor;\n blocks?: unknown[];\n documentBlocks?: unknown[];\n editor?: IxoEditorType;\n now?: () => number;\n}\n\n/**\n * Builds the host-facing runtime context expected by the Flow Agent.\n *\n * Headless hosts own Matrix login, room joins, and Y.Doc sync. Once a host has\n * a live room document and an agent identity, this helper gives it the stable\n * context shape to pass into `tickFlowAgent` or `FlowAgentService`.\n */\nexport function buildFlowAgentContext({\n yDoc,\n flowId,\n sessionRunId,\n flowUri = `ixo:flow:${flowId}`,\n actor,\n blocks,\n documentBlocks,\n editor,\n now,\n}: BuildFlowAgentContextParams): FlowAgentContext {\n return {\n yDoc,\n flowId,\n sessionRunId,\n flowUri,\n actor,\n ...(blocks ? { blocks } : {}),\n ...(documentBlocks ? { documentBlocks } : {}),\n ...(editor ? { editor } : {}),\n ...(now ? { now } : {}),\n };\n}\n","import type { Map as YMap } from 'yjs';\nimport type { FlowAgentLease } from '../../types/flowAgent';\n\nexport const DEFAULT_FLOW_AGENT_LEASE_TTL_MS = 60_000;\n\nexport interface AcquireFlowAgentLeaseParams {\n leases: YMap<FlowAgentLease>;\n commandId: string;\n sessionRunId: string;\n nodeId: string;\n actorDid: string;\n now?: number;\n ttlMs?: number;\n}\n\nexport function acquireFlowAgentLease({\n leases,\n commandId,\n sessionRunId,\n nodeId,\n actorDid,\n now = Date.now(),\n ttlMs = DEFAULT_FLOW_AGENT_LEASE_TTL_MS,\n}: AcquireFlowAgentLeaseParams): FlowAgentLease | null {\n const current = leases.get(commandId);\n if (current && current.expiresAt > now && current.actorDid !== actorDid) {\n return null;\n }\n\n const nextEpoch = current ? current.epoch + 1 : 1;\n const lease: FlowAgentLease = {\n id: `${commandId}:lease:${nextEpoch}`,\n commandId,\n sessionRunId,\n nodeId,\n actorDid,\n acquiredAt: now,\n expiresAt: now + ttlMs,\n epoch: nextEpoch,\n };\n\n leases.set(commandId, lease);\n return lease;\n}\n\nexport function validateFlowAgentLease(leases: YMap<FlowAgentLease>, lease: FlowAgentLease, now = Date.now()): boolean {\n const current = leases.get(lease.commandId);\n return !!current && current.actorDid === lease.actorDid && current.epoch === lease.epoch && current.expiresAt > now;\n}\n\nexport function releaseFlowAgentLease(leases: YMap<FlowAgentLease>, lease: FlowAgentLease): boolean {\n const current = leases.get(lease.commandId);\n if (!current || current.actorDid !== lease.actorDid || current.epoch !== lease.epoch) return false;\n leases.delete(lease.commandId);\n return true;\n}\n\nexport function cleanupExpiredFlowAgentLeases(leases: YMap<FlowAgentLease>, now = Date.now()): FlowAgentLease[] {\n const expired: FlowAgentLease[] = [];\n leases.forEach((lease, commandId) => {\n if (lease.expiresAt <= now) {\n expired.push(lease);\n leases.delete(commandId);\n }\n });\n return expired;\n}\n","import type { FlowNodeRuntimeState } from '../../types/authorization';\nimport type { CompletionVerification } from '../flowEngine/verifiedCompletion';\nimport { deriveBlockPhase } from '../flowEngine/blockPhase';\nimport type { FlowAgentBlockerCause, FlowAgentNodeSnapshot, FlowAgentPublicNodeState } from '../../types/flowAgent';\nimport { getAssigneeDid, getBlockActionType, getBlockId, getBlockTitle, getBlockType, getDueAt, getBlockProps, parseJsonProp } from './utils';\n\ninterface ConditionConfig {\n enabled?: boolean;\n conditions?: Array<Record<string, unknown>>;\n}\n\nexport interface ClassifyNodeStateInput {\n block: unknown;\n runtime: FlowNodeRuntimeState;\n now: number;\n pendingInvocationCount?: number;\n /** Diagnostic completion result. The stored completed state remains Done. */\n completionVerification?: CompletionVerification;\n}\n\nexport function classifyBlockerCause(block: unknown, runtime: FlowNodeRuntimeState): FlowAgentBlockerCause | undefined {\n const props = getBlockProps(block);\n if (runtime.error?.code === 'missing_ucan') return 'missing_ucan';\n if (runtime.error?.code === 'validation_mismatch') return 'validation_mismatch';\n if (runtime.error?.code === 'external_confirmation_pending') return 'external_confirmation_pending';\n if (runtime.error) return 'service_error';\n\n const conditions = parseJsonProp<ConditionConfig>(props.conditions, {});\n if (conditions.enabled && Array.isArray(conditions.conditions) && conditions.conditions.length > 0) {\n return 'failed_upstream';\n }\n\n const inputs = parseJsonProp<Record<string, unknown>>(props.inputs, {});\n const requiredInputs = parseJsonProp<string[]>(props.requiredInputs, []);\n if (requiredInputs.some((key) => inputs[key] == null || inputs[key] === '')) {\n return 'missing_input';\n }\n\n return undefined;\n}\n\nexport function classifyNodeState({ block, runtime, now, pendingInvocationCount = 0, completionVerification }: ClassifyNodeStateInput): FlowAgentPublicNodeState {\n const derived = deriveBlockPhase({\n runtime,\n actionType: getBlockActionType(block),\n completionVerification,\n pendingInvocationCount,\n });\n\n // `failed` covers plain failures, `needs_verification`, and unknown state\n // strings from newer clients. These states route to diagnosis.\n if (derived.phase === 'failed') return 'Blocked';\n if (derived.phase === 'complete') return 'Done';\n // A repeatable ('many') block that has fired stays a standing capability —\n // it never latches Done while invocations are queued on it. With an empty\n // queue there is nothing for the planner to do, which is what Done means\n // here; the block itself remains invocable.\n if (derived.detail === 'standing' && pendingInvocationCount === 0) return 'Done';\n if (runtime.error) return 'Blocked';\n\n const dueAt = getDueAt(block);\n if (dueAt != null && dueAt <= now) return 'Overdue';\n\n return 'Pending';\n}\n\nexport function snapshotNode(\n block: unknown,\n runtime: FlowNodeRuntimeState,\n now: number,\n pendingInvocationCount = 0,\n completionVerification?: CompletionVerification\n): FlowAgentNodeSnapshot {\n const nodeId = getBlockId(block);\n if (!nodeId) {\n throw new Error('Cannot snapshot a block without an id');\n }\n\n const publicState = classifyNodeState({ block, runtime, now, pendingInvocationCount, completionVerification });\n const dueAt = getDueAt(block);\n const assigneeDid = getAssigneeDid(block);\n\n const snapshot: FlowAgentNodeSnapshot = {\n nodeId,\n blockType: getBlockType(block),\n runtime,\n publicState,\n pendingInvocationCount,\n };\n\n const actionType = getBlockActionType(block);\n if (actionType) snapshot.actionType = actionType;\n\n const title = getBlockTitle(block);\n if (title) snapshot.title = title;\n\n if (publicState === 'Blocked') {\n if (runtime.state === 'needs_verification') {\n snapshot.blockerCause = 'awaiting_verification';\n } else {\n snapshot.blockerCause = classifyBlockerCause(block, runtime) || 'unknown';\n }\n }\n\n if (assigneeDid) snapshot.assigneeDid = assigneeDid;\n if (dueAt != null) snapshot.dueAt = dueAt;\n\n return snapshot;\n}\n","import type { FlowAgentCommand } from '../../types/flowAgent';\nimport { getBlockActionType, getBlockProps, parseJsonProp } from './utils';\n\nexport type FlowAgentActionExecutionMode = 'saved-input' | 'runtime-input-required' | 'human-only';\n\nexport interface FlowAgentActionExecutionPolicy {\n mode: FlowAgentActionExecutionMode;\n requiredRuntimeInputs: string[];\n}\n\nexport interface FlowAgentExecuteActionValidation {\n valid: boolean;\n reason?: string;\n mode: FlowAgentActionExecutionMode;\n missingRuntimeInputs: string[];\n}\n\nconst RUNTIME_INPUT_REQUIRED_ACTIONS = new Set(['qi/form.submit', 'qi/human.form.submit', 'qi/human.checkbox.set', 'qi/protocol.select']);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value != null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction parseStringList(value: unknown): string[] {\n const parsed = parseJsonProp<unknown>(value, []);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter((item): item is string => typeof item === 'string' && item.length > 0);\n}\n\nfunction normalizeMode(value: unknown): FlowAgentActionExecutionMode | undefined {\n if (value === 'saved-input' || value === 'saved_input' || value === 'savedInput') return 'saved-input';\n if (value === 'runtime-input-required' || value === 'runtime_input_required' || value === 'runtimeInputRequired') return 'runtime-input-required';\n if (value === 'human-only' || value === 'human_only' || value === 'humanOnly') return 'human-only';\n return undefined;\n}\n\nfunction parseExecutionConfig(value: unknown): Partial<FlowAgentActionExecutionPolicy> {\n if (value == null || value === '') return {};\n if (typeof value === 'string') {\n const directMode = normalizeMode(value);\n if (directMode) return { mode: directMode };\n }\n\n const parsed = parseJsonProp<Record<string, unknown>>(value, {});\n if (!isRecord(parsed)) return {};\n\n return {\n mode: normalizeMode(parsed.mode),\n requiredRuntimeInputs: parseStringList(parsed.requiredRuntimeInputs),\n };\n}\n\nfunction inferDefaultMode(actionType: string | undefined, requiredRuntimeInputs: string[]): FlowAgentActionExecutionMode {\n if (requiredRuntimeInputs.length > 0) return 'runtime-input-required';\n if (actionType && RUNTIME_INPUT_REQUIRED_ACTIONS.has(actionType)) return 'runtime-input-required';\n return 'saved-input';\n}\n\nexport function getFlowAgentActionExecutionPolicy(block: unknown): FlowAgentActionExecutionPolicy {\n const props = getBlockProps(block);\n const actionType = getBlockActionType(block);\n const config = parseExecutionConfig(props.flowAgentExecution || props.flowAgentExecutionMode || props.agentExecutionMode);\n const requiredRuntimeInputs = [\n ...(config.requiredRuntimeInputs || []),\n ...parseStringList(props.requiredRuntimeInputs || props.runtimeRequiredInputs || props.flowAgentRequiredRuntimeInputs),\n ];\n\n return {\n mode: config.mode || inferDefaultMode(actionType, requiredRuntimeInputs),\n requiredRuntimeInputs: Array.from(new Set(requiredRuntimeInputs)),\n };\n}\n\nexport function getCommandRuntimeInputs(payload: FlowAgentCommand['payload']): Record<string, unknown> | undefined {\n return isRecord(payload.runtimeInputs) ? payload.runtimeInputs : undefined;\n}\n\nexport function validateFlowAgentExecuteActionPayload(block: unknown, payload: FlowAgentCommand['payload']): FlowAgentExecuteActionValidation {\n const policy = getFlowAgentActionExecutionPolicy(block);\n if (policy.mode === 'human-only') {\n return {\n valid: false,\n mode: policy.mode,\n missingRuntimeInputs: [],\n reason: 'Action requires human execution and cannot be run by the Flow Agent',\n };\n }\n\n if (policy.mode !== 'runtime-input-required') {\n return { valid: true, mode: policy.mode, missingRuntimeInputs: [] };\n }\n\n const runtimeInputs = getCommandRuntimeInputs(payload);\n const missingRuntimeInputs =\n policy.requiredRuntimeInputs.length > 0\n ? policy.requiredRuntimeInputs.filter((key) => runtimeInputs?.[key] == null || runtimeInputs[key] === '')\n : runtimeInputs\n ? []\n : ['runtimeInputs'];\n\n if (missingRuntimeInputs.length > 0) {\n return {\n valid: false,\n mode: policy.mode,\n missingRuntimeInputs,\n reason:\n policy.requiredRuntimeInputs.length > 0\n ? `Missing required runtimeInputs: ${missingRuntimeInputs.join(', ')}`\n : 'Action requires runtimeInputs before the Flow Agent can execute it',\n };\n }\n\n return { valid: true, mode: policy.mode, missingRuntimeInputs: [] };\n}\n","import type { Doc } from 'yjs';\nimport type {\n FlowAgentActor,\n FlowAgentCommand,\n FlowAgentCommandResult,\n FlowAgentContext,\n FlowAgentExecutor,\n FlowAgentNodeSnapshot,\n FlowAgentTickResult,\n} from '../../types/flowAgent';\nimport type { StoredDelegation } from '../../types/ucan';\nimport type { UcanDelegationStore } from '../ucanDelegationStore';\nimport { readPendingInvocations } from '../flowEngine/triggers';\nimport { readActionState } from '../flowEngine/runs';\nimport { createAgentCommand, validateAgentCommand } from './commands';\nimport { acquireFlowAgentLease, releaseFlowAgentLease, validateFlowAgentLease } from './lease';\nimport { evaluateFlowAgentPolicy } from './policy';\nimport { appendAgentLedgerEvent, getFlowAgentMaps, queueAgentCommand, readQueuedAgentCommands, updateAgentCommand } from './store';\nimport { getAssigneeDid, getBlockActionType, getBlockId, getBlockProps, parseJsonProp } from './utils';\nimport { snapshotNode } from './state';\nimport { validateFlowAgentExecuteActionPayload } from './actionExecutionPolicy';\nimport { evaluateBlockExecutionEligibilityForRun, parseConditionConfigStrict } from '../flowEngine/conditions';\n\nconst BLOCKER_DIAGNOSIS_VERSION = 2;\n\nexport interface FlowAgentOrchestratorOptions {\n delegationStore?: UcanDelegationStore;\n delegations?: StoredDelegation[];\n candidateActors?: FlowAgentActor[];\n executor?: FlowAgentExecutor;\n leaseTtlMs?: number;\n archiveWhenDone?: boolean;\n}\n\ninterface InputsValidation {\n valid: boolean;\n reason?: string;\n}\n\nfunction getBlocks(context: FlowAgentContext): unknown[] {\n const flattened: unknown[] = [];\n const visit = (block: unknown) => {\n flattened.push(block);\n const children = (block as { children?: unknown[] } | null)?.children;\n if (Array.isArray(children)) children.forEach(visit);\n };\n (context.blocks || context.editor?.document || []).forEach(visit);\n return flattened;\n}\n\nfunction getConditionDocument(context: FlowAgentContext): unknown[] {\n return context.documentBlocks || context.blocks || context.editor?.document || [];\n}\n\n/**\n * IGNITION PHASE A: the planner's read of a node's action state.\n *\n * This used to be a raw `yDoc.getMap<Record<string, any>>('runtime').get(nodeId)`\n * — the flat map, unresolved — while its structural twin in `execution.ts`\n * (`getRuntimeRecord`) had already been converted to the waist. The generic type\n * argument is why nobody noticed: the guard's regex era matched\n * `getMap\\s*(?:<[^>]*>)?\\s*\\(` and `[^>]*` cannot cross the inner `>` of\n * `Record<string, any>`, so the line was invisible to every rule.\n *\n * It matters more than a read usually would: the value goes straight to\n * `snapshotNode`, which is what decides whether to queue\n * `execute_action`. A block whose latest state reached the run container but not\n * the flat mirror reads here as never having run → the planner re-queues a\n * side-effecting action. That is §9.1's double-execution hazard on the read side.\n *\n * `readActionState` resolves the run entry against the flat mirror through the\n * freshness predicate, so under dual-write it returns the same value and where\n * the two disagree it returns the fresher one.\n */\nfunction getRuntime(yDoc: Doc, sessionRunId: string, nodeId: string): Record<string, any> {\n const value = readActionState(yDoc, sessionRunId, nodeId);\n return value && typeof value === 'object' ? (value as Record<string, any>) : {};\n}\n\nfunction validateInputs(block: unknown): InputsValidation {\n const props = getBlockProps(block);\n const inputs = parseJsonProp<Record<string, unknown>>(props.inputs, {});\n const requiredInputs = parseJsonProp<string[]>(props.requiredInputs, []);\n const missing = requiredInputs.filter((key) => inputs[key] == null || inputs[key] === '');\n if (missing.length > 0) {\n return { valid: false, reason: `Missing required inputs: ${missing.join(', ')}` };\n }\n return { valid: true };\n}\n\nfunction chooseActor(block: unknown, options: FlowAgentOrchestratorOptions): FlowAgentActor | undefined {\n const props = getBlockProps(block);\n const actionType = getBlockActionType(block);\n const requiredSkill = typeof props.requiredSkill === 'string' ? props.requiredSkill : actionType;\n if (!options.candidateActors || options.candidateActors.length === 0) return undefined;\n if (!requiredSkill) return options.candidateActors[0];\n return options.candidateActors.find((actor) => actor.skills?.includes(requiredSkill)) || options.candidateActors[0];\n}\n\nfunction canQueueCommand(type: FlowAgentCommand['type'], nodeId: string, context: FlowAgentContext, options: FlowAgentOrchestratorOptions): boolean {\n return evaluateFlowAgentPolicy({\n actorDid: context.actor.did,\n commandType: type,\n flowUri: context.flowUri,\n nodeId,\n delegationStore: options.delegationStore,\n delegations: options.delegations,\n now: context.now?.() || Date.now(),\n }).allowed;\n}\n\nfunction safeAppendAgentLedgerEvent(yDoc: Doc, event: Parameters<typeof appendAgentLedgerEvent>[1]): void {\n try {\n appendAgentLedgerEvent(yDoc, event);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to append flow-agent ledger event';\n if (message.includes('Unexpected content type') || message.includes('already been defined with a different constructor')) {\n return;\n }\n throw error;\n }\n}\n\nfunction queueIfAuthorized(\n context: FlowAgentContext,\n options: FlowAgentOrchestratorOptions,\n type: FlowAgentCommand['type'],\n nodeId: string,\n reason: string,\n payload: Record<string, unknown>\n): FlowAgentCommand | null {\n const now = context.now?.() || Date.now();\n const policy = evaluateFlowAgentPolicy({\n actorDid: context.actor.did,\n commandType: type,\n flowUri: context.flowUri,\n nodeId,\n delegationStore: options.delegationStore,\n delegations: options.delegations,\n now,\n });\n\n safeAppendAgentLedgerEvent(context.yDoc, {\n type: 'agent.decision',\n flowId: context.flowId,\n sessionRunId: context.sessionRunId,\n nodeId,\n actorDid: context.actor.did,\n timestamp: now,\n details: {\n commandType: type,\n allowed: policy.allowed,\n reason: policy.reason,\n capability: policy.capability,\n },\n });\n\n if (!policy.allowed) return null;\n\n const command = createAgentCommand({\n type,\n flowId: context.flowId,\n sessionRunId: context.sessionRunId,\n flowUri: context.flowUri,\n nodeId,\n actor: context.actor,\n reason,\n payload,\n now,\n });\n const validation = validateAgentCommand(command);\n if (!validation.valid) {\n safeAppendAgentLedgerEvent(context.yDoc, {\n type: 'agent.validation',\n flowId: context.flowId,\n sessionRunId: context.sessionRunId,\n nodeId,\n commandId: command.id,\n actorDid: context.actor.did,\n timestamp: now,\n details: { valid: false, error: validation.error },\n });\n return null;\n }\n return queueAgentCommand(context.yDoc, command).created ? command : null;\n}\n\nfunction statusForResult(result: FlowAgentCommandResult): FlowAgentCommand['status'] {\n if (result.status) return result.status;\n if (!result.success) return 'failed';\n return result.confirmed === false ? 'awaiting_readback' : 'confirmed';\n}\n\nfunction planForSnapshot(context: FlowAgentContext, options: FlowAgentOrchestratorOptions, block: unknown, snapshot: FlowAgentNodeSnapshot): FlowAgentCommand[] {\n const queued: FlowAgentCommand[] = [];\n const actionType = getBlockActionType(block);\n\n if (snapshot.publicState === 'Done') {\n return queued;\n }\n\n if (snapshot.publicState === 'Overdue') {\n const command = queueIfAuthorized(context, options, 'notify_actor', snapshot.nodeId, 'Action node is overdue', {\n assigneeDid: snapshot.assigneeDid,\n dueAt: snapshot.dueAt,\n severity: 'overdue',\n });\n if (command) queued.push(command);\n return queued;\n }\n\n if (snapshot.publicState === 'Blocked') {\n const command = queueIfAuthorized(context, options, 'diagnose_blocker', snapshot.nodeId, 'Action node is blocked and requires diagnosis', {\n cause: snapshot.blockerCause || 'unknown',\n error: snapshot.runtime.error,\n diagnosisVersion: BLOCKER_DIAGNOSIS_VERSION,\n });\n if (command) queued.push(command);\n return queued;\n }\n\n const assigneeDid = getAssigneeDid(block);\n if (!assigneeDid) {\n const actor = chooseActor(block, options);\n const command = queueIfAuthorized(context, options, 'assign_actor', snapshot.nodeId, 'Action node has no assigned actor', {\n targetActorDid: actor?.did,\n targetMatrixUserId: actor?.matrixUserId,\n requiredActionType: actionType,\n });\n if (command) queued.push(command);\n return queued;\n }\n\n const inputValidation = validateInputs(block);\n if (!inputValidation.valid) {\n const command = queueIfAuthorized(context, options, 'diagnose_blocker', snapshot.nodeId, inputValidation.reason || 'Action node inputs are not ready', {\n cause: 'missing_input',\n });\n if (command) queued.push(command);\n return queued;\n }\n\n if (actionType && canQueueCommand('execute_action', snapshot.nodeId, context, options)) {\n const pendingInvocation = readPendingInvocations(context.yDoc, snapshot.nodeId, context.sessionRunId)[0];\n const payload = {\n actionType,\n ...(pendingInvocation ? { pendingInvocationId: pendingInvocation.id } : {}),\n };\n const actionValidation = validateFlowAgentExecuteActionPayload(block, payload);\n if (!actionValidation.valid) {\n const commandType = actionValidation.mode === 'human-only' ? 'notify_actor' : 'diagnose_blocker';\n const command = queueIfAuthorized(context, options, commandType, snapshot.nodeId, actionValidation.reason || 'Action node cannot be executed by Flow Agent yet', {\n cause: actionValidation.mode === 'runtime-input-required' ? 'missing_input' : 'unknown',\n requiredActionType: actionType,\n requiredRuntimeInputs: actionValidation.missingRuntimeInputs,\n severity: actionValidation.mode === 'human-only' ? 'attention' : undefined,\n });\n if (command) queued.push(command);\n return queued;\n }\n\n const command = queueIfAuthorized(context, options, 'execute_action', snapshot.nodeId, 'Action node is pending and executable', {\n ...payload,\n });\n if (command) queued.push(command);\n return queued;\n }\n\n const notifyCommand = queueIfAuthorized(context, options, 'notify_actor', snapshot.nodeId, 'Action node is pending but the Flow Agent cannot execute it', {\n assigneeDid,\n requiredActionType: actionType,\n severity: 'attention',\n });\n if (notifyCommand) queued.push(notifyCommand);\n return queued;\n}\n\nexport function planRalphLoopCommands(\n context: FlowAgentContext,\n options: FlowAgentOrchestratorOptions = {}\n): { snapshots: FlowAgentNodeSnapshot[]; queuedCommands: FlowAgentCommand[]; flowDone: boolean } {\n const now = context.now?.() || Date.now();\n const blocks = getBlocks(context);\n const conditionDocument = getConditionDocument(context);\n const snapshots: FlowAgentNodeSnapshot[] = [];\n const queuedCommands: FlowAgentCommand[] = [];\n\n for (const block of blocks) {\n const nodeId = getBlockId(block);\n if (!nodeId) continue;\n const pendingInvocationCount = readPendingInvocations(context.yDoc, nodeId, context.sessionRunId).length;\n const runtime = getRuntime(context.yDoc, context.sessionRunId, nodeId);\n const snapshot = snapshotNode(block, runtime, now, pendingInvocationCount);\n try {\n const eligibility = evaluateBlockExecutionEligibilityForRun(\n parseConditionConfigStrict(getBlockProps(block).conditions),\n conditionDocument,\n context.yDoc,\n context.sessionRunId\n );\n if (!eligibility.eligible && snapshot.publicState !== 'Done') {\n snapshot.publicState = 'Blocked';\n snapshot.blockerCause = 'failed_upstream';\n }\n } catch {\n if (snapshot.publicState !== 'Done') {\n snapshot.publicState = 'Blocked';\n snapshot.blockerCause = 'validation_mismatch';\n }\n }\n snapshots.push(snapshot);\n queuedCommands.push(...planForSnapshot(context, options, block, snapshot));\n }\n\n const flowDone = snapshots.length > 0 && snapshots.every((snapshot) => snapshot.publicState === 'Done');\n // Completion is a readiness signal only. A run closes through the explicit\n // flow/run.close capability; legacy archive behaviour is opt-in.\n if (flowDone && options.archiveWhenDone === true) {\n const archiveCommand = queueIfAuthorized(context, options, 'archive_flow', context.flowId, 'All Ralph loop action nodes are done', {\n restartIfRepeats: true,\n });\n if (archiveCommand) queuedCommands.push(archiveCommand);\n }\n\n return { snapshots, queuedCommands, flowDone };\n}\n\nasync function callExecutor(command: FlowAgentCommand, context: FlowAgentContext, executor: FlowAgentExecutor): Promise<FlowAgentCommandResult> {\n switch (command.type) {\n case 'execute_action':\n return executor.executeAction ? executor.executeAction(command, context) : { commandId: command.id, success: false, error: 'No executeAction handler configured' };\n case 'assign_actor':\n return executor.assignActor ? executor.assignActor(command, context) : { commandId: command.id, success: false, error: 'No assignActor handler configured' };\n case 'notify_actor':\n return executor.notifyActor ? executor.notifyActor(command, context) : { commandId: command.id, success: false, error: 'No notifyActor handler configured' };\n case 'validate_external_state':\n return executor.validateExternalState\n ? executor.validateExternalState(command, context)\n : { commandId: command.id, success: false, error: 'No validateExternalState handler configured' };\n case 'archive_flow':\n return executor.archiveFlow ? executor.archiveFlow(command, context) : { commandId: command.id, success: false, error: 'No archiveFlow handler configured' };\n case 'propose_config_change':\n return executor.proposeConfigChange\n ? executor.proposeConfigChange(command, context)\n : { commandId: command.id, success: false, error: 'No proposeConfigChange handler configured' };\n case 'diagnose_blocker':\n return executor.diagnoseBlocker ? executor.diagnoseBlocker(command, context) : { commandId: command.id, success: false, error: 'No diagnoseBlocker handler configured' };\n }\n}\n\nexport async function executeQueuedAgentCommands(context: FlowAgentContext, options: FlowAgentOrchestratorOptions = {}): Promise<FlowAgentCommandResult[]> {\n const executor = options.executor;\n if (!executor) return [];\n\n const now = context.now?.() || Date.now();\n const { leases } = getFlowAgentMaps(context.yDoc);\n const results: FlowAgentCommandResult[] = [];\n\n for (const command of readQueuedAgentCommands(context.yDoc, context.sessionRunId)) {\n const validation = validateAgentCommand(command);\n if (!validation.valid) {\n updateAgentCommand(context.yDoc, command.id, { status: 'failed', error: validation.error, updatedAt: now });\n results.push({ commandId: command.id, success: false, error: validation.error });\n continue;\n }\n\n const policy = evaluateFlowAgentPolicy({\n actorDid: context.actor.did,\n commandType: command.type,\n flowUri: context.flowUri,\n nodeId: command.nodeId,\n delegationStore: options.delegationStore,\n delegations: options.delegations,\n now,\n });\n\n if (!policy.allowed) {\n updateAgentCommand(context.yDoc, command.id, { status: 'skipped', error: policy.reason, updatedAt: now });\n results.push({ commandId: command.id, success: false, error: policy.reason });\n continue;\n }\n\n const lease = acquireFlowAgentLease({\n leases,\n commandId: command.id,\n sessionRunId: context.sessionRunId,\n nodeId: command.nodeId,\n actorDid: context.actor.did,\n now,\n ttlMs: options.leaseTtlMs,\n });\n\n if (!lease) {\n continue;\n }\n\n updateAgentCommand(context.yDoc, command.id, { status: 'running', lease, updatedAt: now });\n\n try {\n const result = await callExecutor({ ...command, lease, status: 'running' }, context, executor);\n if (!validateFlowAgentLease(leases, lease, context.now?.() || Date.now())) {\n const leaseError = 'Lease expired or was superseded before command commit';\n updateAgentCommand(context.yDoc, command.id, { status: 'failed', error: leaseError, updatedAt: context.now?.() || Date.now() });\n results.push({ commandId: command.id, success: false, error: leaseError });\n continue;\n }\n\n updateAgentCommand(context.yDoc, command.id, {\n status: statusForResult(result),\n error: result.error,\n updatedAt: context.now?.() || Date.now(),\n });\n\n safeAppendAgentLedgerEvent(context.yDoc, {\n type: result.success ? 'agent.validation' : 'agent.escalation',\n flowId: context.flowId,\n sessionRunId: context.sessionRunId,\n nodeId: command.nodeId,\n commandId: command.id,\n actorDid: context.actor.did,\n timestamp: context.now?.() || Date.now(),\n details: {\n success: result.success,\n confirmed: result.confirmed,\n output: result.output,\n error: result.error,\n },\n });\n\n results.push(result);\n } finally {\n releaseFlowAgentLease(leases, lease);\n }\n }\n\n return results;\n}\n\nexport async function tickFlowAgent(context: FlowAgentContext, options: FlowAgentOrchestratorOptions = {}): Promise<FlowAgentTickResult> {\n const plan = planRalphLoopCommands(context, options);\n const executedCommands = await executeQueuedAgentCommands(context, options);\n return {\n flowDone: plan.flowDone,\n snapshots: plan.snapshots,\n queuedCommands: plan.queuedCommands,\n executedCommands,\n };\n}\n","import type { Doc } from 'yjs';\nimport type { ActionHandlers, ActionServices } from '../actionRegistry/types';\nimport { executeActionBlock } from '../flowEngine';\nimport { createYDocRuntimeManager } from '../flowEngine/runtime';\nimport { readActionState, resetActionState, resolveRunIdForExecution } from '../flowEngine/runs';\nimport type { FlowNodeRuntimeState } from '../../types/authorization';\nimport type { UcanService } from '../../services/ucanService';\nimport type { StoredDelegation } from '../../types/ucan';\nimport type { InvocationStore } from '../invocationStore';\nimport type { UcanDelegationStore } from '../ucanDelegationStore';\nimport type { FlowAgentCommand, FlowAgentCommandResult, FlowAgentContext, FlowAgentExecutor } from '../../types/flowAgent';\nimport { acquireFlowAgentLease, releaseFlowAgentLease, validateFlowAgentLease } from './lease';\nimport { evaluateFlowAgentPolicy } from './policy';\nimport { appendAgentLedgerEvent, getFlowAgentMaps, readAgentCommands, readQueuedAgentCommands, updateAgentCommand } from './store';\nimport { getBlockId, getBlockProps } from './utils';\nimport { validateAgentCommand } from './commands';\nimport { getCommandRuntimeInputs, validateFlowAgentExecuteActionPayload } from './actionExecutionPolicy';\nimport type { RunEventAppender } from '../flowEngine/runLifecycle';\nimport { boundRunActionOutput, readPendingRunTimelineEvents, retryPendingRunTimelineEvents } from '../flowEngine/runTimeline';\n\nexport interface ExecuteFlowAgentCoreCommandOptions {\n ucanService: UcanService;\n pin: string;\n actorType: 'entity' | 'user';\n entityRoomId?: string;\n actionServices?: ActionServices;\n actionHandlers?: ActionHandlers;\n delegationStore?: UcanDelegationStore;\n delegations?: StoredDelegation[];\n invocationStore?: InvocationStore;\n leaseTtlMs?: number;\n flowOwnerDid?: string;\n schemaVersion?: string;\n runEventLog?: RunEventAppender;\n now?: () => number;\n}\n\nexport interface ExecuteQueuedFlowAgentCoreCommandsOptions extends ExecuteFlowAgentCoreCommandOptions {\n executor?: FlowAgentExecutor;\n commandTypes?: FlowAgentCommand['type'][];\n}\n\nconst DEFAULT_SCHEMA_VERSION = '1.0.0';\n\nfunction resolveExecutionContext(context: FlowAgentContext): FlowAgentContext {\n const sessionRunId = resolveRunIdForExecution(context.yDoc, context.sessionRunId);\n return sessionRunId === context.sessionRunId ? context : { ...context, sessionRunId };\n}\n\nfunction safeAppendAgentLedgerEvent(yDoc: Doc, event: Parameters<typeof appendAgentLedgerEvent>[1]): void {\n try {\n appendAgentLedgerEvent(yDoc, event);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to append flow-agent ledger event';\n if (message.includes('Unexpected content type') || message.includes('already been defined with a different constructor')) {\n return;\n }\n throw error;\n }\n}\n\n/**\n * IGNITION PHASE A: this module used to carry a **private duplicate** of the\n * runtime manager writing straight to `yDoc.getMap('runtime')`. Converting\n * `flowEngine/runtime.ts` did nothing for it — it had to be deleted, not\n * patched — so the flow agent is now on the shared, run-scoped manager and\n * every write below dual-writes the run entry and the flat mirror.\n */\nfunction getRuntimeRecord(yDoc: Doc, sessionRunId: string, nodeId: string): Record<string, unknown> {\n return readActionState(yDoc, sessionRunId, nodeId) as unknown as Record<string, unknown>;\n}\n\n/**\n * Strip the blocker (`state`, `error`) off a node's runtime and stamp the\n * diagnosis metadata.\n *\n * This is a **replace**, not a merge — dropping `state` and `error` by\n * destructuring is the whole point — which makes it the single most dangerous\n * statement in the flow agent under a live adoption gate: written flat-only it\n * downgrades the block to an unstarted-looking entry that the freshness\n * predicate can never materialise, leaving the run entry stuck on the failed\n * state forever. `resetActionState` writes the *identical* object to both\n * sides in one transaction, so the two converge and there is nothing left for\n * adoption to strand.\n */\nfunction clearRuntimeBlocker(yDoc: Doc, sessionRunId: string, nodeId: string, updates: Record<string, unknown>): void {\n const current = getRuntimeRecord(yDoc, sessionRunId, nodeId);\n const { state: _state, error: _error, ...rest } = current;\n resetActionState(yDoc, sessionRunId, nodeId, {\n ...rest,\n ...updates,\n } as FlowNodeRuntimeState);\n}\n\nfunction findContextBlock(context: FlowAgentContext, nodeId: string): Record<string, unknown> | null {\n const visit = (blocks: unknown[]): Record<string, unknown> | null => {\n for (const entry of blocks) {\n if (getBlockId(entry) === nodeId && entry && typeof entry === 'object') {\n return entry as Record<string, unknown>;\n }\n const children = (entry as { children?: unknown[] } | null)?.children;\n if (Array.isArray(children)) {\n const found = visit(children);\n if (found) return found;\n }\n }\n return null;\n };\n return visit(context.blocks || context.documentBlocks || context.editor?.document || []);\n}\n\ntype YXmlAttributeReader = {\n getAttribute: (key: string) => unknown;\n};\n\nfunction getXmlAttribute<T>(element: YXmlAttributeReader, key: string): T | undefined {\n return element.getAttribute(key) as T | undefined;\n}\n\nfunction setXmlAttribute(element: { setAttribute: (key: string, value: unknown) => unknown }, key: string, value: unknown): void {\n (element as unknown as { setAttribute: (key: string, value: unknown) => void }).setAttribute(key, value);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value != null && typeof value === 'object' && !Array.isArray(value);\n}\n\ntype YXmlContainerLike = {\n toArray: () => unknown[];\n};\n\ntype YXmlElementLike = YXmlContainerLike & {\n nodeName: string;\n getAttribute: (key: string) => unknown;\n setAttribute: (key: string, value: unknown) => unknown;\n};\n\nfunction isYXmlContainerLike(value: unknown): value is YXmlContainerLike {\n return value != null && typeof value === 'object' && typeof (value as { toArray?: unknown }).toArray === 'function';\n}\n\nfunction isYXmlElementLike(value: unknown): value is YXmlElementLike {\n return (\n isYXmlContainerLike(value) &&\n typeof (value as { nodeName?: unknown }).nodeName === 'string' &&\n typeof (value as { getAttribute?: unknown }).getAttribute === 'function' &&\n typeof (value as { setAttribute?: unknown }).setAttribute === 'function'\n );\n}\n\nfunction getElementBlockId(element: YXmlElementLike): string | undefined {\n const directId = getXmlAttribute<string>(element, 'id');\n if (typeof directId === 'string' && directId.length > 0) return directId;\n\n const attrs = getXmlAttribute<Record<string, unknown>>(element, 'attrs');\n const attrsId = isRecord(attrs) ? attrs.id : undefined;\n return typeof attrsId === 'string' && attrsId.length > 0 ? attrsId : undefined;\n}\n\nfunction updateXmlElementProps(element: YXmlElementLike, blockId: string, propsPatch: Record<string, unknown>): void {\n const attrs = getXmlAttribute<Record<string, unknown>>(element, 'attrs');\n if (isRecord(attrs)) {\n const existingProps = isRecord(attrs.props) ? attrs.props : {};\n setXmlAttribute(element, 'attrs', {\n ...attrs,\n id: typeof attrs.id === 'string' ? attrs.id : blockId,\n props: {\n ...existingProps,\n ...propsPatch,\n },\n });\n }\n\n for (const [key, value] of Object.entries(propsPatch)) {\n element.setAttribute(key, typeof value === 'string' ? value : JSON.stringify(value));\n }\n}\n\nfunction findXmlElementById(container: YXmlContainerLike, blockId: string): YXmlElementLike | null {\n for (const node of container.toArray()) {\n if (!isYXmlElementLike(node)) continue;\n const id = getElementBlockId(node);\n if (id === blockId) return node;\n const nested = findXmlElementById(node, blockId);\n if (nested) return nested;\n }\n return null;\n}\n\nfunction updateDocumentBlockProps(yDoc: Doc, blockId: string, propsPatch: Record<string, unknown>): boolean {\n const target = findXmlElementById(yDoc.getXmlFragment('document'), blockId);\n if (!target) return false;\n\n updateXmlElementProps(target, blockId, propsPatch);\n\n const content = target.toArray().find((node): node is YXmlElementLike => isYXmlElementLike(node) && node.nodeName !== 'blockGroup');\n if (content) {\n updateXmlElementProps(content, blockId, propsPatch);\n }\n\n return true;\n}\n\nfunction assignActorInYDoc(yDoc: Doc, command: FlowAgentCommand, context: FlowAgentContext): Record<string, unknown> {\n const targetActorDid = typeof command.payload.targetActorDid === 'string' && command.payload.targetActorDid.length > 0 ? command.payload.targetActorDid : context.actor.did;\n const targetMatrixUserId = typeof command.payload.targetMatrixUserId === 'string' ? command.payload.targetMatrixUserId : undefined;\n const assignment = {\n assignedActor: {\n did: targetActorDid,\n avatar: '',\n displayName: targetMatrixUserId || targetActorDid,\n },\n assignedBy: {\n did: context.actor.did,\n avatar: '',\n displayName: context.actor.displayName || context.actor.matrixUserId || '',\n },\n assignedTimestamp: new Date(context.now?.() || Date.now()).toISOString(),\n };\n const assignmentJson = JSON.stringify(assignment);\n\n const updatedDocument = updateDocumentBlockProps(yDoc, command.nodeId, {\n assignment: assignmentJson,\n });\n\n if (!updatedDocument) {\n throw new Error(`Block ${command.nodeId} was not found for assignment`);\n }\n\n const runtime = createYDocRuntimeManager(yDoc, context.sessionRunId);\n runtime.update(command.nodeId, {\n assignedActorDid: targetActorDid,\n assignedByDid: context.actor.did,\n assignedAt: assignment.assignedTimestamp,\n lastCommandId: command.id,\n } as Record<string, unknown>);\n\n return assignment;\n}\n\nasync function executeAssignActorCommand(command: FlowAgentCommand, context: FlowAgentContext, options: ExecuteFlowAgentCoreCommandOptions): Promise<FlowAgentCommandResult> {\n const capability = { can: 'flow/node/assign', with: `${context.flowUri}:${command.nodeId}` };\n const proofs = await options.ucanService.findValidProofs(context.actor.did, capability);\n if (!proofs.found || !proofs.proofCids) {\n return {\n commandId: command.id,\n success: false,\n error: proofs.error || 'No valid delegation found for assignment',\n };\n }\n\n const result = await options.ucanService.executeWithInvocation(\n {\n invokerDid: context.actor.did,\n invokerType: options.actorType,\n entityRoomId: options.entityRoomId,\n capability,\n proofs: proofs.proofCids,\n pin: options.pin,\n },\n async () => assignActorInYDoc(context.yDoc, command, context),\n context.flowId,\n command.nodeId,\n context.sessionRunId\n );\n\n return {\n commandId: command.id,\n success: result.success,\n confirmed: result.success,\n output:\n result.actionResult && typeof result.actionResult === 'object'\n ? { assignment: result.actionResult as Record<string, unknown>, invocationCid: result.invocationCid }\n : { invocationCid: result.invocationCid },\n error: result.error,\n };\n}\n\nasync function recoverPendingActionTimeline(\n command: FlowAgentCommand,\n context: FlowAgentContext,\n options: ExecuteFlowAgentCoreCommandOptions\n): Promise<FlowAgentCommandResult | undefined> {\n const pendingTimeline = readPendingRunTimelineEvents(context.yDoc, context.sessionRunId, command.nodeId);\n if (pendingTimeline.length === 0) return undefined;\n if (!options.runEventLog) {\n return {\n commandId: command.id,\n success: false,\n confirmed: false,\n status: 'awaiting_readback',\n error: 'Canonical run history is pending and no run event log is available for replay.',\n };\n }\n const replay = await retryPendingRunTimelineEvents({\n yDoc: context.yDoc,\n sessionRunId: context.sessionRunId,\n blockId: command.nodeId,\n eventLog: options.runEventLog,\n now: options.now || context.now,\n });\n const current = readActionState(context.yDoc, context.sessionRunId, command.nodeId);\n const replayedOutput = boundRunActionOutput(current.output || {}).output;\n const replayStatus: FlowAgentCommand['status'] =\n replay.remaining > 0 || current.state === 'awaiting_readback' ? 'awaiting_readback' : current.state === 'completed' ? 'confirmed' : 'failed';\n return {\n commandId: command.id,\n success: replayStatus === 'confirmed',\n confirmed: replayStatus === 'confirmed',\n status: replayStatus,\n output: {\n ...replayedOutput,\n ...(current.lastEventId ? { lastEventId: current.lastEventId } : {}),\n replayedTimelineEvents: replay.attempted,\n remainingTimelineEvents: replay.remaining,\n },\n ...(replay.remaining > 0\n ? { error: 'Canonical run history replay remains incomplete.' }\n : replayStatus === 'failed'\n ? {\n error: current.error?.message || 'The action completed in a non-confirmable terminal state.',\n }\n : {}),\n completionState:\n current.state === 'completed'\n ? 'completed'\n : current.state === 'needs_verification'\n ? 'needs_verification'\n : current.state === 'awaiting_readback'\n ? 'awaiting_readback'\n : 'failed',\n };\n}\n\nasync function executeActionCommand(command: FlowAgentCommand, context: FlowAgentContext, options: ExecuteFlowAgentCoreCommandOptions): Promise<FlowAgentCommandResult> {\n const recoveredTimeline = await recoverPendingActionTimeline(command, context, options);\n if (recoveredTimeline) return recoveredTimeline;\n\n const actionType = typeof command.payload.actionType === 'string' ? command.payload.actionType : undefined;\n if (!actionType) {\n return { commandId: command.id, success: false, error: 'execute_action command is missing payload.actionType' };\n }\n\n const block = findContextBlock(context, command.nodeId);\n if (!block) {\n return { commandId: command.id, success: false, error: `Block ${command.nodeId} was not found in runtime context` };\n }\n\n const props = getBlockProps(block);\n if (typeof props.actionType === 'string' && props.actionType !== actionType) {\n return {\n commandId: command.id,\n success: false,\n error: `execute_action payload.actionType ${actionType} does not match block actionType ${props.actionType}`,\n };\n }\n\n const runtimeInputs = command.payload.runtimeInputs;\n if (runtimeInputs != null && !isRecord(runtimeInputs)) {\n return { commandId: command.id, success: false, error: 'execute_action payload.runtimeInputs must be an object when provided' };\n }\n\n const inputValidation = validateFlowAgentExecuteActionPayload(block, command.payload);\n if (!inputValidation.valid) {\n return {\n commandId: command.id,\n success: false,\n confirmed: false,\n status: inputValidation.mode === 'human-only' ? 'skipped' : 'failed',\n error: inputValidation.reason,\n };\n }\n\n const pendingInvocationId = typeof command.payload.pendingInvocationId === 'string' ? command.payload.pendingInvocationId : undefined;\n const outcome = await executeActionBlock({\n editorOrYDoc: context.editor || context.yDoc,\n // The SESSION run (runs.ts), not the per-execution audit id. Constant in\n // Phase A; passed explicitly so the headless path is already shaped for\n // Phase B run selection instead of falling back to a doc-level default.\n runId: context.sessionRunId,\n block,\n blockId: command.nodeId,\n document: (context.documentBlocks || context.blocks || context.editor?.document || []) as any[],\n actorDid: context.actor.did,\n actorType: options.actorType,\n entityRoomId: options.entityRoomId,\n ucanService: options.ucanService,\n invocationStore: options.invocationStore,\n services: options.actionServices || {},\n handlers: options.actionHandlers,\n runtimeInputs: getCommandRuntimeInputs(command.payload),\n pendingInvocationId,\n pin: options.pin,\n flowUri: context.flowUri,\n flowId: context.flowId,\n flowOwnerDid: options.flowOwnerDid || '',\n schemaVersion: options.schemaVersion || DEFAULT_SCHEMA_VERSION,\n runEventLog: options.runEventLog,\n now: options.now || context.now,\n });\n const persisted = readActionState(context.yDoc, context.sessionRunId, command.nodeId);\n const durableOutput = boundRunActionOutput(persisted.output || {}).output;\n const pendingAfterExecution = readPendingRunTimelineEvents(context.yDoc, context.sessionRunId, command.nodeId);\n const timelinePending = pendingAfterExecution.length > 0;\n\n return {\n commandId: command.id,\n success: outcome.success,\n confirmed: !timelinePending && outcome.success && outcome.completionState === 'completed',\n ...(timelinePending ? { status: 'awaiting_readback' as const } : {}),\n output: {\n ...durableOutput,\n ...(persisted.lastEventId ? { lastEventId: persisted.lastEventId } : {}),\n ...(outcome.invocationCid ? { invocationCid: outcome.invocationCid } : {}),\n ...(outcome.capabilityId ? { capabilityId: outcome.capabilityId } : {}),\n // Execution audit id under both names: `runId` is what flow-manager and\n // flow-agent read today (deprecated), `executionId` is the forward name.\n ...(outcome.runId ? { runId: outcome.runId } : {}),\n ...(outcome.executionId ? { executionId: outcome.executionId } : {}),\n ...(pendingInvocationId ? { pendingInvocationId, pendingInvocationRemoved: outcome.pendingInvocationRemoved } : {}),\n completionState: outcome.completionState,\n ...(timelinePending ? { remainingTimelineEvents: pendingAfterExecution.length } : {}),\n },\n error: timelinePending ? 'The action effect completed, but canonical run history is pending replay.' : outcome.error,\n completionState: outcome.completionState,\n };\n}\n\nfunction getRecoverableBlockerReason(runtime: Record<string, unknown>): string | null {\n const error = runtime.error;\n const message =\n error && typeof error === 'object' && typeof (error as Record<string, unknown>).message === 'string'\n ? ((error as Record<string, unknown>).message as string)\n : typeof error === 'string'\n ? error\n : undefined;\n\n if (!message) return null;\n if (message.includes('Invalid DID') && message.includes(\"must start with 'did:'\")) {\n return 'matrix_did_normalization';\n }\n if (message.includes('Failed to parse URL from undefined')) {\n return 'http_endpoint_input_normalization';\n }\n if (message.includes('Unexpected content type') || message.includes('already been defined with a different constructor')) {\n return 'audit_trail_shape';\n }\n return null;\n}\n\nfunction resetFailedActionCommands(context: FlowAgentContext, nodeId: string, now: number): string[] {\n const { outbox } = getFlowAgentMaps(context.yDoc);\n const resetIds: string[] = [];\n outbox.forEach((command) => {\n if (command.sessionRunId !== context.sessionRunId || command.nodeId !== nodeId || command.type !== 'execute_action' || command.status !== 'failed') {\n return;\n }\n outbox.set(command.id, {\n ...command,\n status: 'queued',\n error: undefined,\n lease: undefined,\n updatedAt: now,\n reason: `Retry after blocker diagnosis: ${command.reason}`,\n });\n resetIds.push(command.id);\n });\n return resetIds;\n}\n\nasync function executeDiagnoseBlockerCommand(command: FlowAgentCommand, context: FlowAgentContext, options: ExecuteFlowAgentCoreCommandOptions): Promise<FlowAgentCommandResult> {\n const now = options.now?.() || context.now?.() || Date.now();\n const runtime = getRuntimeRecord(context.yDoc, context.sessionRunId, command.nodeId);\n const recovery = getRecoverableBlockerReason(runtime);\n\n if (!recovery) {\n return {\n commandId: command.id,\n success: true,\n confirmed: true,\n output: {\n blockerCause: command.payload.cause || 'unknown',\n recovery: 'manual_intervention_required',\n },\n };\n }\n\n clearRuntimeBlocker(context.yDoc, context.sessionRunId, command.nodeId, {\n diagnosedAt: now,\n diagnosedByDid: context.actor.did,\n lastDiagnosisCommandId: command.id,\n lastRecovery: recovery,\n });\n const resetCommandIds = resetFailedActionCommands(context, command.nodeId, now);\n\n return {\n commandId: command.id,\n success: true,\n confirmed: true,\n output: {\n blockerCause: command.payload.cause || 'unknown',\n recovery,\n resetCommandIds,\n },\n };\n}\n\nexport async function executeFlowAgentCoreCommand(\n command: FlowAgentCommand,\n context: FlowAgentContext,\n options: ExecuteFlowAgentCoreCommandOptions\n): Promise<FlowAgentCommandResult> {\n const executionContext = resolveExecutionContext(context);\n switch (command.type) {\n case 'assign_actor':\n return executeAssignActorCommand(command, executionContext, options);\n case 'execute_action':\n return executeActionCommand(command, executionContext, options);\n case 'diagnose_blocker':\n return executeDiagnoseBlockerCommand(command, executionContext, options);\n default:\n return { commandId: command.id, success: false, error: `No editor-core executor for ${command.type}` };\n }\n}\n\nasync function callConfiguredExecutor(\n command: FlowAgentCommand,\n context: FlowAgentContext,\n options: ExecuteQueuedFlowAgentCoreCommandsOptions\n): Promise<FlowAgentCommandResult | undefined> {\n if (!options.executor) return undefined;\n switch (command.type) {\n case 'assign_actor':\n return options.executor.assignActor?.(command, context);\n case 'execute_action':\n return options.executor.executeAction?.(command, context);\n case 'notify_actor':\n return options.executor.notifyActor?.(command, context);\n case 'diagnose_blocker':\n return options.executor.diagnoseBlocker?.(command, context);\n default:\n return undefined;\n }\n}\n\nfunction statusForResult(result: FlowAgentCommandResult): FlowAgentCommand['status'] {\n if (result.status) return result.status;\n if (!result.success) return 'failed';\n return result.confirmed === false ? 'awaiting_readback' : 'confirmed';\n}\n\nexport async function executeQueuedFlowAgentCoreCommands(context: FlowAgentContext, options: ExecuteQueuedFlowAgentCoreCommandsOptions): Promise<FlowAgentCommandResult[]> {\n context = resolveExecutionContext(context);\n const now = options.now?.() || context.now?.() || Date.now();\n const { leases } = getFlowAgentMaps(context.yDoc);\n const results: FlowAgentCommandResult[] = [];\n const queued = readQueuedAgentCommands(context.yDoc, context.sessionRunId);\n const queuedIds = new Set(queued.map((command) => command.id));\n const retainedTimelineRecoveries = readAgentCommands(context.yDoc, context.sessionRunId).filter(\n (command) =>\n command.status === 'awaiting_readback' &&\n command.type === 'execute_action' &&\n !queuedIds.has(command.id) &&\n readPendingRunTimelineEvents(context.yDoc, context.sessionRunId, command.nodeId).length > 0\n );\n\n for (const command of [...retainedTimelineRecoveries, ...queued]) {\n if (options.commandTypes && !options.commandTypes.includes(command.type)) {\n continue;\n }\n\n const validation = validateAgentCommand(command);\n if (!validation.valid) {\n updateAgentCommand(context.yDoc, command.id, { status: 'failed', error: validation.error, updatedAt: now });\n results.push({ commandId: command.id, success: false, error: validation.error });\n continue;\n }\n\n const policy = evaluateFlowAgentPolicy({\n actorDid: context.actor.did,\n commandType: command.type,\n flowUri: context.flowUri,\n nodeId: command.nodeId,\n delegationStore: options.delegationStore,\n delegations: options.delegations,\n now,\n });\n if (!policy.allowed) {\n updateAgentCommand(context.yDoc, command.id, { status: 'skipped', error: policy.reason, updatedAt: now });\n results.push({ commandId: command.id, success: false, error: policy.reason });\n continue;\n }\n\n const lease = acquireFlowAgentLease({\n leases,\n commandId: command.id,\n sessionRunId: context.sessionRunId,\n nodeId: command.nodeId,\n actorDid: context.actor.did,\n now,\n ttlMs: options.leaseTtlMs,\n });\n if (!lease) continue;\n\n updateAgentCommand(context.yDoc, command.id, { status: 'running', lease, updatedAt: now });\n\n try {\n const runningCommand = { ...command, lease, status: 'running' as const };\n const result = (await Promise.resolve(callConfiguredExecutor(runningCommand, context, options))) || (await executeFlowAgentCoreCommand(runningCommand, context, options));\n const normalized = result || {\n commandId: command.id,\n success: false,\n error: `No executor configured for ${command.type}`,\n };\n\n if (!validateFlowAgentLease(leases, lease, options.now?.() || context.now?.() || Date.now())) {\n const error = 'Lease expired or was superseded before command commit';\n updateAgentCommand(context.yDoc, command.id, { status: 'failed', error, updatedAt: options.now?.() || context.now?.() || Date.now() });\n results.push({ commandId: command.id, success: false, error });\n continue;\n }\n\n updateAgentCommand(context.yDoc, command.id, {\n status: statusForResult(normalized),\n error: normalized.error,\n updatedAt: options.now?.() || context.now?.() || Date.now(),\n });\n safeAppendAgentLedgerEvent(context.yDoc, {\n type: normalized.success ? 'agent.validation' : 'agent.escalation',\n flowId: context.flowId,\n sessionRunId: context.sessionRunId,\n nodeId: command.nodeId,\n commandId: command.id,\n actorDid: context.actor.did,\n timestamp: options.now?.() || context.now?.() || Date.now(),\n details: {\n success: normalized.success,\n confirmed: normalized.confirmed,\n output: boundRunActionOutput(normalized.output || {}).output,\n error: normalized.error,\n },\n });\n results.push(normalized);\n } finally {\n releaseFlowAgentLease(leases, lease);\n }\n }\n\n return results;\n}\n","import type { FlowAgentContext, FlowAgentTickResult } from '../../types/flowAgent';\nimport type { FlowAgentOrchestratorOptions } from './orchestrator';\nimport { tickFlowAgent } from './orchestrator';\n\nexport interface FlowAgentServiceOptions extends FlowAgentOrchestratorOptions {\n intervalMs?: number;\n onTick?: (result: FlowAgentTickResult) => void | Promise<void>;\n onError?: (error: unknown) => void;\n}\n\n/**\n * Headless-service adapter boundary.\n *\n * Host applications own Matrix login, room joins, and Y.Doc sync. Once they\n * have a live Y.Doc/editor snapshot, this service provides the deterministic\n * Ralph-loop tick and command execution cycle.\n */\nexport class FlowAgentService {\n private timer: ReturnType<typeof setInterval> | null = null;\n private running = false;\n\n constructor(\n private readonly context: FlowAgentContext,\n private readonly options: FlowAgentServiceOptions = {}\n ) {}\n\n async tick(): Promise<FlowAgentTickResult> {\n if (this.running) {\n return {\n flowDone: false,\n snapshots: [],\n queuedCommands: [],\n executedCommands: [],\n };\n }\n\n this.running = true;\n try {\n const result = await tickFlowAgent(this.context, this.options);\n await this.options.onTick?.(result);\n return result;\n } catch (error) {\n this.options.onError?.(error);\n throw error;\n } finally {\n this.running = false;\n }\n }\n\n start(): void {\n if (this.timer) return;\n const intervalMs = this.options.intervalMs || 30_000;\n this.timer = setInterval(() => {\n this.tick().catch((error) => {\n this.options.onError?.(error);\n });\n }, intervalMs);\n }\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CAAC,CAAC,EAAE;AAAA,UACtD,OAAO,WAAW;AAAA,QACpB;AAAA,MACF,CAAC;AACD,cAAQ,KAAK,UAAU;AAAA,IACzB,UAAE;AACA,4BAAsB,QAAQ,KAAK;AAAA,IACrC;AAAA,EACF;AAEA,SAAO;AACT;;;ACxnBO,IAAM,mBAAN,MAAuB;AAAA,EAI5B,YACmB,SACA,UAAmC,CAAC,GACrD;AAFiB;AACA;AALnB,SAAQ,QAA+C;AACvD,SAAQ,UAAU;AAAA,EAKf;AAAA,EAEH,MAAM,OAAqC;AACzC,QAAI,KAAK,SAAS;AAChB,aAAO;AAAA,QACL,UAAU;AAAA,QACV,WAAW,CAAC;AAAA,QACZ,gBAAgB,CAAC;AAAA,QACjB,kBAAkB,CAAC;AAAA,MACrB;AAAA,IACF;AAEA,SAAK,UAAU;AACf,QAAI;AACF,YAAM,SAAS,MAAM,cAAc,KAAK,SAAS,KAAK,OAAO;AAC7D,YAAM,KAAK,QAAQ,SAAS,MAAM;AAClC,aAAO;AAAA,IACT,SAAS,OAAO;AACd,WAAK,QAAQ,UAAU,KAAK;AAC5B,YAAM;AAAA,IACR,UAAE;AACA,WAAK,UAAU;AAAA,IACjB;AAAA,EACF;AAAA,EAEA,QAAc;AACZ,QAAI,KAAK,MAAO;AAChB,UAAM,aAAa,KAAK,QAAQ,cAAc;AAC9C,SAAK,QAAQ,YAAY,MAAM;AAC7B,WAAK,KAAK,EAAE,MAAM,CAAC,UAAU;AAC3B,aAAK,QAAQ,UAAU,KAAK;AAAA,MAC9B,CAAC;AAAA,IACH,GAAG,UAAU;AAAA,EACf;AAAA,EAEA,OAAa;AACX,QAAI,CAAC,KAAK,MAAO;AACjB,kBAAc,KAAK,KAAK;AACxB,SAAK,QAAQ;AAAA,EACf;AACF;","names":["room","Y","Y","Y","MatrixProvider","MatrixProvider","command","safeAppendAgentLedgerEvent","isRecord","isYXmlElementLike","statusForResult"]}