@ixo/editor 7.1.0 → 7.2.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.
@@ -1,18 +1,25 @@
1
1
  import {
2
+ COMPILED_BLOCK_TYPE,
2
3
  addFlowNode,
3
4
  auditFlowProjections,
5
+ createYMapFromNode,
6
+ ensureFlowExecutionMetadata,
7
+ legacyPropsByBlockId,
4
8
  readFlowDocument,
5
9
  removeFlowNode,
6
10
  reorderFlowNodes,
7
11
  repairFlowProjections,
8
12
  setBlockProps
9
- } from "./chunk-3WLWIA7D.js";
13
+ } from "./chunk-IUC6B2NF.js";
10
14
  import {
11
15
  readFlowConnections
12
16
  } from "./chunk-DVZU2FI6.js";
13
17
  import {
14
18
  signFlowDefinitionRevision
15
19
  } from "./chunk-UTLM6U75.js";
20
+ import {
21
+ getAction
22
+ } from "./chunk-QW7LA67J.js";
16
23
  import {
17
24
  canonicalizeJson,
18
25
  deepFreezeJson,
@@ -22,8 +29,117 @@ import {
22
29
  isYMapLike
23
30
  } from "./chunk-NCSGIRRQ.js";
24
31
 
25
- // src/core/lib/flowCompiler/draftRepository.ts
32
+ // src/core/lib/flowCompiler/stepListMigration.ts
26
33
  import * as Y from "yjs";
34
+ function actionBlocksInOrder(yDoc) {
35
+ const propsByBlockId = legacyPropsByBlockId(yDoc);
36
+ const blocks = [];
37
+ const walk = (parent) => {
38
+ for (let index = 0; index < parent.length; index += 1) {
39
+ const child = parent.get(index);
40
+ if (!(child instanceof Y.XmlElement)) continue;
41
+ if (child.nodeName === "blockContainer") {
42
+ const content = child.get(0);
43
+ const attrs = child.getAttribute("attrs");
44
+ const directId = child.getAttribute("id");
45
+ const blockId = typeof directId === "string" && directId ? directId : typeof attrs?.id === "string" ? attrs.id : "";
46
+ if (blockId && content instanceof Y.XmlElement && content.nodeName === COMPILED_BLOCK_TYPE) {
47
+ blocks.push({ blockId, props: propsByBlockId.get(blockId) ?? {} });
48
+ }
49
+ }
50
+ walk(child);
51
+ }
52
+ };
53
+ walk(yDoc.getXmlFragment("document"));
54
+ return blocks;
55
+ }
56
+ function listedBlockIds(yDoc) {
57
+ const listed = /* @__PURE__ */ new Set();
58
+ yDoc.getMap("qi.flow.nodes").forEach((value, nodeId) => {
59
+ listed.add(nodeId);
60
+ const blockId = value instanceof Y.Map ? value.get("blockId") : void 0;
61
+ if (typeof blockId === "string" && blockId) listed.add(blockId);
62
+ });
63
+ yDoc.getMap("qi.flow.blockIndex").forEach((blockId) => listed.add(blockId));
64
+ return listed;
65
+ }
66
+ function governedByStepList(yDoc) {
67
+ return yDoc.getMap("qi.flow.meta").get("draftSchemaVersion") === 1 || yDoc.getMap("qi.flow.nodes").size === 0;
68
+ }
69
+ function findUnlistedActionBlocks(yDoc) {
70
+ if (!governedByStepList(yDoc)) return [];
71
+ const listed = listedBlockIds(yDoc);
72
+ return actionBlocksInOrder(yDoc).filter((block) => !listed.has(block.blockId)).map((block) => {
73
+ const actionType = block.props.actionType ?? "";
74
+ return { blockId: block.blockId, actionType, known: Boolean(actionType && getAction(actionType)) };
75
+ });
76
+ }
77
+ function flowSegment(yDoc) {
78
+ const docId = yDoc.getMap("root").get("doc_id");
79
+ if (typeof docId === "string" && docId) return `ixo:flow:${docId}`;
80
+ const flowId = yDoc.getMap("qi.flow.meta").get("flowId");
81
+ return typeof flowId === "string" && flowId ? `ixo:flow:${flowId}` : "ixo:flow";
82
+ }
83
+ function addUnlistedSteps(yDoc) {
84
+ const unlisted = findUnlistedActionBlocks(yDoc).filter((block) => block.known);
85
+ if (unlisted.length === 0) return [];
86
+ const blocks = actionBlocksInOrder(yDoc);
87
+ const propsByBlockId = new Map(blocks.map((block) => [block.blockId, block.props]));
88
+ const flowPrefix = flowSegment(yDoc);
89
+ const added = [];
90
+ yDoc.transact(() => {
91
+ const nodes = yDoc.getMap("qi.flow.nodes");
92
+ const blockIndex = yDoc.getMap("qi.flow.blockIndex");
93
+ for (const { blockId, actionType } of unlisted) {
94
+ const action = getAction(actionType);
95
+ if (!action) continue;
96
+ const props = propsByBlockId.get(blockId) ?? {};
97
+ const resource = `${flowPrefix}:${blockId}`;
98
+ const node = {
99
+ id: blockId,
100
+ blockId,
101
+ can: action.can ?? "",
102
+ with: resource,
103
+ registryType: action.type,
104
+ title: props.title || action.can || action.type,
105
+ description: props.description ?? "",
106
+ props: { ...props, with: resource }
107
+ };
108
+ nodes.set(blockId, createYMapFromNode(node));
109
+ blockIndex.set(blockId, blockId);
110
+ added.push(blockId);
111
+ }
112
+ const order = yDoc.getArray("qi.flow.order");
113
+ if (order.length > 0) {
114
+ const nodeIdByBlock = /* @__PURE__ */ new Map();
115
+ nodes.forEach((value, nodeId) => {
116
+ const blockId = value instanceof Y.Map ? value.get("blockId") : void 0;
117
+ nodeIdByBlock.set(typeof blockId === "string" && blockId ? blockId : nodeId, nodeId);
118
+ });
119
+ for (const blockId of added) {
120
+ const position = blocks.findIndex((block) => block.blockId === blockId);
121
+ let insertAt = 0;
122
+ for (let previous = position - 1; previous >= 0; previous -= 1) {
123
+ const previousNode = nodeIdByBlock.get(blocks[previous].blockId);
124
+ const index = previousNode ? order.toArray().indexOf(previousNode) : -1;
125
+ if (index >= 0) {
126
+ insertAt = index + 1;
127
+ break;
128
+ }
129
+ }
130
+ order.insert(insertAt, [blockId]);
131
+ }
132
+ }
133
+ const meta = yDoc.getMap("qi.flow.meta");
134
+ if (meta.get("draftSchemaVersion") !== 1) meta.set("draftSchemaVersion", 1);
135
+ meta.delete("definitionDigest");
136
+ ensureFlowExecutionMetadata(yDoc);
137
+ }, "step-list-migration");
138
+ return added;
139
+ }
140
+
141
+ // src/core/lib/flowCompiler/draftRepository.ts
142
+ import * as Y2 from "yjs";
27
143
  var FlowDraftCommandError = class extends Error {
28
144
  constructor(code, message, details) {
29
145
  super(message);
@@ -140,14 +256,14 @@ function createYjsFlowDefinitionDraftRepository(yDoc) {
140
256
  },
141
257
  applyBatch: (commands) => {
142
258
  if (commands.length === 0) return [];
143
- const beforeVector = Y.encodeStateVector(yDoc);
144
- const stagedDoc = new Y.Doc();
259
+ const beforeVector = Y2.encodeStateVector(yDoc);
260
+ const stagedDoc = new Y2.Doc();
145
261
  try {
146
- Y.applyUpdate(stagedDoc, Y.encodeStateAsUpdate(yDoc));
262
+ Y2.applyUpdate(stagedDoc, Y2.encodeStateAsUpdate(yDoc));
147
263
  const stagedRepository = createYjsFlowDefinitionDraftRepository(stagedDoc);
148
264
  const results = commands.map((command) => stagedRepository.apply(command));
149
- const update = Y.encodeStateAsUpdate(stagedDoc, beforeVector);
150
- yDoc.transact(() => Y.applyUpdate(yDoc, update), "flow-draft-command-batch");
265
+ const update = Y2.encodeStateAsUpdate(stagedDoc, beforeVector);
266
+ yDoc.transact(() => Y2.applyUpdate(yDoc, update), "flow-draft-command-batch");
151
267
  return results;
152
268
  } finally {
153
269
  stagedDoc.destroy();
@@ -160,7 +276,7 @@ function createYjsFlowDefinitionDraftRepository(yDoc) {
160
276
  }
161
277
 
162
278
  // src/core/lib/flowCompiler/participants.ts
163
- import * as Y2 from "yjs";
279
+ import * as Y3 from "yjs";
164
280
  var FLOW_PARTICIPANTS_MAP_KEY = "qi.flow.participants";
165
281
  function readFlowParticipants(yDoc) {
166
282
  const participants = [];
@@ -220,7 +336,7 @@ function getParticipantsMap(yDoc) {
220
336
  function ensureEntry(map, userId) {
221
337
  const existing = map.get(userId);
222
338
  if (isYMapLike(existing)) return existing;
223
- const created = new Y2.Map();
339
+ const created = new Y3.Map();
224
340
  map.set(userId, created);
225
341
  return created;
226
342
  }
@@ -539,6 +655,8 @@ async function applyApprovedFlowDraftProposal(repository, proposal, approval) {
539
655
  }
540
656
 
541
657
  export {
658
+ findUnlistedActionBlocks,
659
+ addUnlistedSteps,
542
660
  FlowDraftCommandError,
543
661
  createYjsFlowDefinitionDraftRepository,
544
662
  FLOW_PARTICIPANTS_MAP_KEY,
@@ -553,4 +671,4 @@ export {
553
671
  createFlowDraftProposal,
554
672
  applyApprovedFlowDraftProposal
555
673
  };
556
- //# sourceMappingURL=chunk-IMN2PXVU.js.map
674
+ //# sourceMappingURL=chunk-VWJNCOHW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/lib/flowCompiler/stepListMigration.ts","../src/core/lib/flowCompiler/draftRepository.ts","../src/core/lib/flowCompiler/participants.ts","../src/core/lib/flowCompiler/publication.ts","../src/core/lib/flowCompiler/draftProposal.ts"],"sourcesContent":["import type { Doc as YDoc } from 'yjs';\nimport * as Y from 'yjs';\nimport type { CompiledFlowNode } from '../../types/baseUcan';\nimport { getAction } from '../actionRegistry';\nimport { COMPILED_BLOCK_TYPE } from './blockMapping';\nimport { createYMapFromNode, ensureFlowExecutionMetadata, legacyPropsByBlockId } from './hydrate';\n\n/**\n * A step on the page with no entry in the step list.\n *\n * Flows authored before the step list existed (`qi.flow.nodes`) kept their\n * steps only as blocks in the BlockNote document. Adoption fills in the props\n * of steps already in the list, but it never adds one. Everything that decides\n * what a flow may do reads the list alone: the Portal builds the flow\n * manager's grant from it, and the flow manager finds a step there before it\n * sends any work for it. A step missing from the list can still be run by hand\n * from the page, so the work it produces is real — and then nothing will send\n * it, and no grant ever covers it.\n */\nexport interface UnlistedActionBlock {\n blockId: string;\n actionType: string;\n /** Whether the registry knows the action. An unknown one cannot be listed. */\n known: boolean;\n}\n\n/**\n * Action blocks on the page, in document order, with the props adoption reads\n * for them. Nested blocks count: a step can sit inside another block's group.\n */\nfunction actionBlocksInOrder(yDoc: YDoc): Array<{ blockId: string; props: Record<string, string> }> {\n const propsByBlockId = legacyPropsByBlockId(yDoc);\n const blocks: Array<{ blockId: string; props: Record<string, string> }> = [];\n const walk = (parent: Y.XmlFragment | Y.XmlElement): 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') {\n const content = child.get(0);\n const attrs = child.getAttribute('attrs') as unknown as { id?: unknown } | undefined;\n const directId = child.getAttribute('id');\n const blockId = typeof directId === 'string' && directId ? directId : typeof attrs?.id === 'string' ? attrs.id : '';\n if (blockId && content instanceof Y.XmlElement && content.nodeName === COMPILED_BLOCK_TYPE) {\n blocks.push({ blockId, props: propsByBlockId.get(blockId) ?? {} });\n }\n }\n walk(child);\n }\n };\n walk(yDoc.getXmlFragment('document'));\n return blocks;\n}\n\nfunction listedBlockIds(yDoc: YDoc): Set<string> {\n const listed = new Set<string>();\n yDoc.getMap('qi.flow.nodes').forEach((value, nodeId) => {\n listed.add(nodeId);\n const blockId = value instanceof Y.Map ? value.get('blockId') : undefined;\n if (typeof blockId === 'string' && blockId) listed.add(blockId);\n });\n yDoc.getMap<string>('qi.flow.blockIndex').forEach((blockId) => listed.add(blockId));\n return listed;\n}\n\n/**\n * Whether this document is one the step list governs: typed (draft schema 1),\n * or with no step list at all.\n *\n * An untyped document that lists some steps is adopted on open\n * (`adoptLegacyFlowDocument`), which types it, and this check picks it up on\n * the next pass. An empty list is a different case: adoption skips it because\n * it has no nodes to fill, so nothing else would ever list its steps. Flows\n * made from templates authored before the step list existed look like that.\n */\nfunction governedByStepList(yDoc: YDoc): boolean {\n return yDoc.getMap('qi.flow.meta').get('draftSchemaVersion') === 1 || yDoc.getMap('qi.flow.nodes').size === 0;\n}\n\n/** Action blocks on the page that the step list does not have, in page order. */\nexport function findUnlistedActionBlocks(yDoc: YDoc): UnlistedActionBlock[] {\n if (!governedByStepList(yDoc)) return [];\n const listed = listedBlockIds(yDoc);\n return actionBlocksInOrder(yDoc)\n .filter((block) => !listed.has(block.blockId))\n .map((block) => {\n const actionType = block.props.actionType ?? '';\n return { blockId: block.blockId, actionType, known: Boolean(actionType && getAction(actionType)) };\n });\n}\n\nfunction flowSegment(yDoc: YDoc): string {\n const docId = yDoc.getMap('root').get('doc_id');\n if (typeof docId === 'string' && docId) return `ixo:flow:${docId}`;\n const flowId = yDoc.getMap('qi.flow.meta').get('flowId');\n return typeof flowId === 'string' && flowId ? `ixo:flow:${flowId}` : 'ixo:flow';\n}\n\n/**\n * Add a step-list entry for every action block that has none.\n *\n * Additive only: the page is not touched, listed steps are not changed, and a\n * block whose action the registry does not know is left out rather than given\n * an entry nothing can run. Each new step takes its block's id as its own, so\n * the resource it is addressed by — `ixo:flow:<doc_id>:<block id>` — is the one\n * the page already ran it under, and work that names the block finds it.\n *\n * Runs in one transaction. Called inside a caller's transaction it joins that\n * one, which is how the Portal writes the new steps and the grant that covers\n * them as a single change. Returns the ids it added; an empty list means the\n * document was already complete.\n */\nexport function addUnlistedSteps(yDoc: YDoc): string[] {\n const unlisted = findUnlistedActionBlocks(yDoc).filter((block) => block.known);\n if (unlisted.length === 0) return [];\n const blocks = actionBlocksInOrder(yDoc);\n const propsByBlockId = new Map(blocks.map((block) => [block.blockId, block.props]));\n const flowPrefix = flowSegment(yDoc);\n const added: string[] = [];\n\n yDoc.transact(() => {\n const nodes = yDoc.getMap('qi.flow.nodes');\n const blockIndex = yDoc.getMap<string>('qi.flow.blockIndex');\n for (const { blockId, actionType } of unlisted) {\n const action = getAction(actionType);\n if (!action) continue;\n const props = propsByBlockId.get(blockId) ?? {};\n const resource = `${flowPrefix}:${blockId}`;\n const node: CompiledFlowNode = {\n id: blockId,\n blockId,\n can: action.can ?? '',\n with: resource,\n registryType: action.type,\n title: props.title || action.can || action.type,\n description: props.description ?? '',\n props: { ...props, with: resource },\n };\n nodes.set(blockId, createYMapFromNode(node));\n blockIndex.set(blockId, blockId);\n added.push(blockId);\n }\n\n // A flow with an explicit order runs in it, so a new step goes after the\n // step that precedes it on the page. An empty order is left empty: such a\n // flow runs in page order already.\n const order = yDoc.getArray<string>('qi.flow.order');\n if (order.length > 0) {\n const nodeIdByBlock = new Map<string, string>();\n nodes.forEach((value, nodeId) => {\n const blockId = value instanceof Y.Map ? value.get('blockId') : undefined;\n nodeIdByBlock.set(typeof blockId === 'string' && blockId ? blockId : nodeId, nodeId);\n });\n for (const blockId of added) {\n const position = blocks.findIndex((block) => block.blockId === blockId);\n let insertAt = 0;\n for (let previous = position - 1; previous >= 0; previous -= 1) {\n const previousNode = nodeIdByBlock.get(blocks[previous].blockId);\n const index = previousNode ? order.toArray().indexOf(previousNode) : -1;\n if (index >= 0) {\n insertAt = index + 1;\n break;\n }\n }\n order.insert(insertAt, [blockId]);\n }\n }\n\n // The definition changed, so its digest must be recomputed. Clearing it is\n // what makes the stamp below write a fresh one; on its own the stamp sees\n // contracts that already match and leaves the stale digest in place. A flow\n // that had no list was never typed, and the stamp skips untyped documents.\n const meta = yDoc.getMap('qi.flow.meta');\n if (meta.get('draftSchemaVersion') !== 1) meta.set('draftSchemaVersion', 1);\n meta.delete('definitionDigest');\n ensureFlowExecutionMetadata(yDoc);\n }, 'step-list-migration');\n\n return added;\n}\n","import * as Y from 'yjs';\nimport type { Doc as YDoc } from 'yjs';\nimport { canonicalizeJson, type CanonicalJsonValue } from '../flowEngine/vnext/canonical';\nimport {\n addFlowNode,\n auditFlowProjections,\n readFlowDocument,\n removeFlowNode,\n reorderFlowNodes,\n repairFlowProjections,\n setBlockProps,\n type FlowDocumentRead,\n type FlowProjectionDrift,\n} from './authoring';\n\nexport type FlowDraftCommandOperation =\n | {\n kind: 'add-step';\n nodeId: string;\n blockId: string;\n actionType: string;\n afterNodeId?: string;\n title?: string;\n props?: Record<string, string>;\n }\n | { kind: 'update-step-props'; blockId: string; props: Record<string, string> }\n | { kind: 'remove-step'; nodeId: string }\n | { kind: 'reorder-steps'; order: string[] }\n | { kind: 'set-meta'; values: Record<string, string | number | boolean | null> };\n\nexport interface FlowDraftCommand {\n kind: 'qi.flow.draft-command';\n schemaVersion: '1.0';\n commandId: string;\n expectedRevision: number;\n actorDid: string;\n operation: FlowDraftCommandOperation;\n}\n\nexport interface FlowDraftCommandResult {\n outcome: 'applied' | 'duplicate';\n commandId: string;\n revision: number;\n nodeId?: string;\n blockId?: string;\n}\n\nexport interface FlowDraftSnapshot {\n revision: number;\n document: FlowDocumentRead | null;\n}\n\nexport interface FlowDefinitionDraftRepository {\n read(): FlowDraftSnapshot;\n apply(command: FlowDraftCommand): FlowDraftCommandResult;\n applyBatch(commands: readonly FlowDraftCommand[]): FlowDraftCommandResult[];\n auditProjections(): FlowProjectionDrift[];\n repairProjections(): FlowProjectionDrift[];\n}\n\ninterface StoredDraftCommand {\n fingerprint: string;\n result: FlowDraftCommandResult;\n}\n\nexport class FlowDraftCommandError extends Error {\n constructor(\n readonly code: 'REVISION_CONFLICT' | 'IDEMPOTENCY_CONFLICT' | 'INVALID_COMMAND' | 'REFERENCED_STEP',\n message: string,\n readonly details?: Record<string, unknown>\n ) {\n super(message);\n this.name = 'FlowDraftCommandError';\n }\n}\n\nconst COMMANDS_MAP = 'qi.flow.draftCommands';\nconst DRAFT_CONTROL_MAP = 'qi.flow.draftControl';\nconst LEGACY_COMMAND_REVISION_KEY = 'legacyCommandRevision';\nconst RESERVED_META_KEYS = new Set(['draftRevision', 'draftSchemaVersion', 'draftUpdatedAt']);\n\nfunction currentRevision(yDoc: YDoc): number {\n const meta = yDoc.getMap('qi.flow.meta');\n if (meta.get('draftSchemaVersion') === 1) return Number(meta.get('draftRevision') ?? 0);\n return Number(yDoc.getMap(DRAFT_CONTROL_MAP).get(LEGACY_COMMAND_REVISION_KEY) ?? 0);\n}\n\nfunction fingerprint(command: FlowDraftCommand): string {\n return canonicalizeJson(command as unknown as CanonicalJsonValue);\n}\n\nfunction advanceCommandRevision(yDoc: YDoc): number {\n const meta = yDoc.getMap('qi.flow.meta');\n const next = currentRevision(yDoc) + 1;\n if (meta.get('draftSchemaVersion') !== 1) {\n yDoc.getMap(DRAFT_CONTROL_MAP).set(LEGACY_COMMAND_REVISION_KEY, next);\n return next;\n }\n meta.set('draftRevision', next);\n meta.set('draftUpdatedAt', new Date().toISOString());\n return next;\n}\n\nfunction setMeta(yDoc: YDoc, values: Record<string, string | number | boolean | null>): void {\n const meta = yDoc.getMap('qi.flow.meta');\n for (const [key, value] of Object.entries(values)) {\n if (value === null) meta.delete(key);\n else meta.set(key, value);\n }\n advanceCommandRevision(yDoc);\n}\n\n/** One idempotent mutation waist for Portal, Oracles, and headless authoring. */\nexport function createYjsFlowDefinitionDraftRepository(yDoc: YDoc): FlowDefinitionDraftRepository {\n const repository: FlowDefinitionDraftRepository = {\n read: () => ({ revision: currentRevision(yDoc), document: readFlowDocument(yDoc) }),\n apply: (command) => {\n if (command.kind !== 'qi.flow.draft-command' || command.schemaVersion !== '1.0' || !command.commandId || !command.actorDid) {\n throw new FlowDraftCommandError('INVALID_COMMAND', 'A versioned command id and actor are required');\n }\n if (command.operation.kind === 'set-meta') {\n const reservedKeys = Object.keys(command.operation.values).filter((key) => RESERVED_META_KEYS.has(key));\n if (reservedKeys.length > 0) {\n throw new FlowDraftCommandError('INVALID_COMMAND', `Flow metadata keys are reserved for draft bookkeeping: ${reservedKeys.sort().join(', ')}`, {\n reservedKeys: reservedKeys.sort(),\n });\n }\n }\n const commands = yDoc.getMap<StoredDraftCommand>(COMMANDS_MAP);\n const commandFingerprint = fingerprint(command);\n const existing = commands.get(command.commandId);\n if (existing) {\n if (existing.fingerprint !== commandFingerprint) {\n throw new FlowDraftCommandError('IDEMPOTENCY_CONFLICT', `Draft command ${command.commandId} was reused with different content`);\n }\n return { ...existing.result, outcome: 'duplicate' };\n }\n\n const beforeRevision = currentRevision(yDoc);\n if (command.expectedRevision !== beforeRevision) {\n throw new FlowDraftCommandError('REVISION_CONFLICT', `Expected draft revision ${command.expectedRevision}, found ${beforeRevision}`);\n }\n\n let nodeId: string | undefined;\n let blockId: string | undefined;\n yDoc.transact(() => {\n const operation = command.operation;\n if (operation.kind === 'add-step') {\n const added = addFlowNode(yDoc, {\n type: operation.actionType,\n nodeId: operation.nodeId,\n blockId: operation.blockId,\n afterNodeId: operation.afterNodeId,\n title: operation.title,\n props: operation.props,\n });\n if (!added) throw new FlowDraftCommandError('INVALID_COMMAND', 'Action type or requested Flow step identity is unavailable');\n nodeId = added.nodeId;\n blockId = added.blockId;\n } else if (operation.kind === 'update-step-props') {\n if (!setBlockProps(yDoc, operation.blockId, operation.props)) {\n throw new FlowDraftCommandError('INVALID_COMMAND', `Unknown Flow block: ${operation.blockId}`);\n }\n blockId = operation.blockId;\n } else if (operation.kind === 'remove-step') {\n const removed = removeFlowNode(yDoc, operation.nodeId);\n if (!removed.ok) {\n throw new FlowDraftCommandError('REFERENCED_STEP', `Flow step ${operation.nodeId} is still referenced`, { referencedBy: removed.referencedBy });\n }\n nodeId = operation.nodeId;\n } else if (operation.kind === 'reorder-steps') {\n if (!reorderFlowNodes(yDoc, operation.order)) throw new FlowDraftCommandError('INVALID_COMMAND', 'Step order must be a complete permutation');\n } else {\n setMeta(yDoc, operation.values);\n }\n\n const afterOperationRevision = currentRevision(yDoc);\n if (afterOperationRevision === beforeRevision) advanceCommandRevision(yDoc);\n const result: FlowDraftCommandResult = {\n outcome: 'applied',\n commandId: command.commandId,\n revision: currentRevision(yDoc),\n ...(nodeId ? { nodeId } : {}),\n ...(blockId ? { blockId } : {}),\n };\n commands.set(command.commandId, { fingerprint: commandFingerprint, result });\n });\n\n const stored = commands.get(command.commandId);\n if (!stored) throw new FlowDraftCommandError('INVALID_COMMAND', 'Draft command did not commit');\n return { ...stored.result };\n },\n applyBatch: (commands) => {\n if (commands.length === 0) return [];\n const beforeVector = Y.encodeStateVector(yDoc);\n const stagedDoc = new Y.Doc();\n try {\n Y.applyUpdate(stagedDoc, Y.encodeStateAsUpdate(yDoc));\n const stagedRepository = createYjsFlowDefinitionDraftRepository(stagedDoc);\n const results = commands.map((command) => stagedRepository.apply(command));\n const update = Y.encodeStateAsUpdate(stagedDoc, beforeVector);\n yDoc.transact(() => Y.applyUpdate(yDoc, update), 'flow-draft-command-batch');\n return results;\n } finally {\n stagedDoc.destroy();\n }\n },\n auditProjections: () => auditFlowProjections(yDoc),\n repairProjections: () => repairFlowProjections(yDoc),\n };\n return repository;\n}\n","import * as Y from 'yjs';\nimport type { Doc as YDoc, Map as YMap } from 'yjs';\nimport { isYMapLike } from '../yjsTypes';\n\n/**\n * Top-level Y.Doc map holding the flow's **human** participant roster, keyed by\n * Matrix user id. Deliberately not called \"agents\": everything under\n * `lib/flowAgent/*` means an AI/oracle actor, and the two must not be conflated.\n *\n * This is template *configuration*, not execution state — the roster records who\n * a flow is meant to be run with, at what Matrix power level, and which of the\n * flow's connections (`connections.ts`) each of them needs access to, so that\n * instantiating a template into a room can invite exactly those users and ask\n * for exactly the right grants. It is therefore NOT cleared by\n * `clearRuntimeForTemplateClone` (`flowEngine/runtime.ts`), which only clears\n * observation/execution maps; a clone must carry the roster forward or the\n * instantiated room comes up empty.\n */\nexport const FLOW_PARTICIPANTS_MAP_KEY = 'qi.flow.participants';\n\nexport type FlowParticipant = {\n /** Matrix user id, e.g. `'@alice:matrix.example.org'`. */\n userId: string;\n /** Matrix power level; integer, `0` when unknown. */\n powerLevel: number;\n displayName?: string;\n /** `mxc://` url. */\n avatarUrl?: string;\n /**\n * Toolkit keys (`FlowConnection.toolkit`) this participant needs access to.\n * Absent when the participant needs none.\n */\n requires?: string[];\n /**\n * Block ids of the steps this participant may carry out. Absent when none\n * were chosen — being on the roster is not the same as being allowed to\n * execute: plenty of actors are only there to watch. A step id that no longer\n * exists in the document is ignored.\n */\n steps?: string[];\n /** Epoch ms. Supplied by the caller — this module never calls `Date.now()`. */\n addedAt?: number;\n};\n\n/**\n * Read the participant roster.\n *\n * Normalizes defensively rather than trusting the map: this is read against a\n * live, replicated doc, so an entry can be observed mid-sync, written by an older\n * client, or malformed outright. Anything that is not a `Y.Map` carrying a\n * non-empty `userId` is skipped, and a read never throws.\n *\n * Order is stable across peers — `addedAt` ascending with unstamped entries last,\n * tie-broken by `userId` — so a rendered roster does not reshuffle on every sync.\n */\nexport function readFlowParticipants(yDoc: YDoc): FlowParticipant[] {\n const participants: FlowParticipant[] = [];\n getParticipantsMap(yDoc).forEach((value) => {\n const participant = toParticipant(value);\n if (participant) participants.push(participant);\n });\n\n return participants.sort((a, b) => {\n const aAt = a.addedAt ?? Number.POSITIVE_INFINITY;\n const bAt = b.addedAt ?? Number.POSITIVE_INFINITY;\n if (aAt !== bAt) return aAt < bAt ? -1 : 1;\n return compareUserIds(a.userId, b.userId);\n });\n}\n\n/**\n * Add a participant, or merge into the existing entry for the same `userId`.\n *\n * `addedAt` is write-once: an existing stamp is preserved so a later edit\n * (a power-level bump, a display-name refresh) cannot reorder the roster.\n * Optional string fields are merged — omit one to leave it as it is, pass `''`\n * to clear it; `requires` follows the same rule with `[]` as the clearing value.\n */\nexport function upsertFlowParticipant(yDoc: YDoc, participant: FlowParticipant): void {\n const userId = participant.userId;\n if (typeof userId !== 'string' || userId.length === 0) return;\n\n yDoc.transact(() => {\n const entry = ensureEntry(getParticipantsMap(yDoc), userId);\n entry.set('userId', userId);\n entry.set('powerLevel', toPowerLevel(participant.powerLevel));\n mergeOptionalString(entry, 'displayName', participant.displayName);\n mergeOptionalString(entry, 'avatarUrl', participant.avatarUrl);\n mergeRequirements(entry, participant.requires);\n mergeSteps(entry, participant.steps);\n\n const addedAt = toTimestamp(entry.get('addedAt')) ?? toTimestamp(participant.addedAt);\n if (addedAt !== undefined) entry.set('addedAt', addedAt);\n });\n}\n\n/** Remove a participant. No-op when the roster has no entry for `userId`. */\nexport function removeFlowParticipant(yDoc: YDoc, userId: string): void {\n yDoc.transact(() => {\n const map = getParticipantsMap(yDoc);\n if (map.has(userId)) map.delete(userId);\n });\n}\n\n/**\n * Set an existing participant's power level. No-op when the participant is not on\n * the roster — a power level alone carries no identity, so creating an entry from\n * one would invent a participant nobody added.\n */\nexport function setFlowParticipantPowerLevel(yDoc: YDoc, userId: string, powerLevel: number): void {\n yDoc.transact(() => {\n const entry = getParticipantsMap(yDoc).get(userId);\n if (isYMapLike<unknown>(entry)) entry.set('powerLevel', toPowerLevel(powerLevel));\n });\n}\n\n/**\n * Replace the connections an existing participant needs access to. Pass `[]` to\n * clear them. No-op when the participant is not on the roster, for the same\n * reason as {@link setFlowParticipantPowerLevel}.\n */\nexport function setFlowParticipantRequirements(yDoc: YDoc, userId: string, requires: string[]): void {\n yDoc.transact(() => {\n const entry = getParticipantsMap(yDoc).get(userId);\n if (isYMapLike<unknown>(entry)) mergeRequirements(entry, requires ?? []);\n });\n}\n\n/**\n * Replace the steps an existing participant may carry out. Pass `[]` to take\n * every step away and leave them watching. No-op when the participant is not on\n * the roster, for the same reason as {@link setFlowParticipantPowerLevel}.\n */\nexport function setFlowParticipantSteps(yDoc: YDoc, userId: string, steps: string[]): void {\n yDoc.transact(() => {\n const entry = getParticipantsMap(yDoc).get(userId);\n if (isYMapLike<unknown>(entry)) mergeSteps(entry, steps ?? []);\n });\n}\n\n// ─── Internal helpers ──────────────────────────────────────────────────────────\n\nfunction getParticipantsMap(yDoc: YDoc): YMap<unknown> {\n return yDoc.getMap<unknown>(FLOW_PARTICIPANTS_MAP_KEY);\n}\n\n/** The entry for `userId`, replacing any malformed (non-`Y.Map`) value in place. */\nfunction ensureEntry(map: YMap<unknown>, userId: string): YMap<unknown> {\n const existing = map.get(userId);\n if (isYMapLike<unknown>(existing)) return existing;\n const created = new Y.Map<unknown>();\n map.set(userId, created);\n return created;\n}\n\nfunction toParticipant(value: unknown): FlowParticipant | undefined {\n if (!isYMapLike<unknown>(value)) return undefined;\n\n const userId = value.get('userId');\n if (typeof userId !== 'string' || userId.length === 0) return undefined;\n\n const participant: FlowParticipant = { userId, powerLevel: toPowerLevel(value.get('powerLevel')) };\n\n const displayName = toNonEmptyString(value.get('displayName'));\n if (displayName !== undefined) participant.displayName = displayName;\n\n const avatarUrl = toNonEmptyString(value.get('avatarUrl'));\n if (avatarUrl !== undefined) participant.avatarUrl = avatarUrl;\n\n const requires = toRequirements(value.get('requires'));\n if (requires.length > 0) participant.requires = requires;\n\n const steps = toRequirements(value.get('steps'));\n if (steps.length > 0) participant.steps = steps;\n\n const addedAt = toTimestamp(value.get('addedAt'));\n if (addedAt !== undefined) participant.addedAt = addedAt;\n\n return participant;\n}\n\n/** Absent, non-numeric, or NaN power levels read as `0` — Matrix's default. */\nfunction toPowerLevel(value: unknown): number {\n const numeric = typeof value === 'string' ? Number(value) : value;\n return typeof numeric === 'number' && Number.isFinite(numeric) ? Math.trunc(numeric) : 0;\n}\n\nfunction toTimestamp(value: unknown): number | undefined {\n const numeric = typeof value === 'string' ? Number(value) : value;\n return typeof numeric === 'number' && Number.isFinite(numeric) ? Math.trunc(numeric) : undefined;\n}\n\nfunction toNonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\n/** Non-empty strings only, de-duplicated, in the order they were written. */\nfunction toRequirements(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n const requires: string[] = [];\n for (const entry of value) {\n if (typeof entry !== 'string' || entry.length === 0) continue;\n if (!requires.includes(entry)) requires.push(entry);\n }\n return requires;\n}\n\nfunction mergeOptionalString(entry: YMap<unknown>, key: string, value: string | undefined): void {\n if (value === undefined) return;\n if (value.length === 0) entry.delete(key);\n else entry.set(key, value);\n}\n\n/** Omit to leave the requirements as they are, pass `[]` to clear them. */\nfunction mergeRequirements(entry: YMap<unknown>, value: string[] | undefined): void {\n if (value === undefined) return;\n const requires = toRequirements(value);\n if (requires.length === 0) entry.delete('requires');\n else entry.set('requires', requires);\n}\n\n/** Omit to leave the steps as they are, pass `[]` to clear them. */\nfunction mergeSteps(entry: YMap<unknown>, value: string[] | undefined): void {\n if (value === undefined) return;\n const steps = toRequirements(value);\n if (steps.length === 0) entry.delete('steps');\n else entry.set('steps', steps);\n}\n\nfunction compareUserIds(a: string, b: string): number {\n if (a === b) return 0;\n return a < b ? -1 : 1;\n}\n","import type { Doc as YDoc } from 'yjs';\nimport { canonicalizeJson, deepFreezeJson, type CanonicalJsonValue } from '../flowEngine/vnext/canonical';\nimport {\n signFlowDefinitionRevision,\n type ActionContractRef,\n type DID,\n type FlowDefinitionRef,\n type FlowDefinitionRevisionRepository,\n type FlowDefinitionRevisionSigner,\n type FlowDefinitionRevisionV1,\n type FlowId,\n type FlowJsonObject,\n type FlowRevisionId,\n type FlowStepDefinitionV1,\n type FlowTriggerV1,\n type Sha256Digest,\n} from '../flowEngine/vnext/contracts';\nimport { readFlowDocument } from './authoring';\nimport { readFlowConnections, type FlowConnection } from './connections';\nimport { readFlowParticipants, type FlowParticipant } from './participants';\n\nexport interface PublishFlowDefinitionParams {\n yDoc: YDoc;\n flowId: FlowId;\n revision: FlowRevisionId;\n publishedAt: string;\n publishedBy: DID;\n signer: FlowDefinitionRevisionSigner;\n repository: FlowDefinitionRevisionRepository;\n actionManifestDigest: Sha256Digest;\n actionContracts: Readonly<Record<string, ActionContractRef>>;\n expectedParent?: FlowDefinitionRef;\n source?: { operation: 'republish-legacy' | 'instantiate-template' | 'fork'; ref: string };\n}\n\nexport interface PublishFlowDefinitionResult {\n outcome: 'published' | 'exists';\n ref: FlowDefinitionRef;\n revision: FlowDefinitionRevisionV1;\n}\n\nexport class FlowDefinitionPublicationError extends Error {\n constructor(\n readonly code: 'NOT_VNEXT_DRAFT' | 'EMPTY_FLOW' | 'MISSING_ACTION_CONTRACT' | 'INVALID_CONFIGURATION' | 'INVALID_TRIGGER' | 'PARENT_CONFLICT',\n message: string\n ) {\n super(message);\n this.name = 'FlowDefinitionPublicationError';\n }\n}\n\nfunction parseObject(value: string | undefined, field: string): FlowJsonObject {\n if (!value) return {};\n try {\n const parsed = JSON.parse(value) as unknown;\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed as FlowJsonObject;\n } catch (error) {\n throw new FlowDefinitionPublicationError('INVALID_CONFIGURATION', `Flow step ${field} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);\n }\n throw new FlowDefinitionPublicationError('INVALID_CONFIGURATION', `Flow step ${field} must be a JSON object`);\n}\n\nfunction parseConditions(value: string | undefined): FlowJsonObject[] {\n if (!value) return [];\n const parsed = parseObject(value, 'conditions');\n if (!Array.isArray(parsed.conditions)) throw new FlowDefinitionPublicationError('INVALID_CONFIGURATION', 'Flow step conditions must contain an array');\n if (parsed.conditions.some((condition) => !condition || typeof condition !== 'object' || Array.isArray(condition))) {\n throw new FlowDefinitionPublicationError('INVALID_CONFIGURATION', 'Every Flow step condition must be a JSON object');\n }\n return parsed.conditions as FlowJsonObject[];\n}\n\nfunction participantRequirement(participant: FlowParticipant): FlowJsonObject {\n return {\n userId: participant.userId,\n powerLevel: participant.powerLevel,\n ...(participant.displayName ? { displayName: participant.displayName } : {}),\n ...(participant.avatarUrl ? { avatarUrl: participant.avatarUrl } : {}),\n ...(participant.requires ? { requires: [...participant.requires] } : {}),\n ...(participant.addedAt !== undefined ? { addedAt: participant.addedAt } : {}),\n };\n}\n\nfunction connectionRequirement(connection: FlowConnection): FlowJsonObject {\n return {\n toolkit: connection.toolkit,\n ...(connection.label ? { label: connection.label } : {}),\n ...(connection.optional ? { optional: true } : {}),\n ...(connection.agent !== undefined ? { agent: connection.agent } : {}),\n requires: [...connection.requires],\n ...(connection.addedAt !== undefined ? { addedAt: connection.addedAt } : {}),\n };\n}\n\nfunction parseTrigger(value: string | undefined, triggerMode: string | undefined): FlowTriggerV1 {\n let trigger: Record<string, unknown> = {};\n if (value) {\n try {\n const parsed = JSON.parse(value) as unknown;\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new FlowDefinitionPublicationError('INVALID_TRIGGER', 'Flow trigger must be a JSON object');\n }\n trigger = parsed as Record<string, unknown>;\n } catch (error) {\n if (error instanceof FlowDefinitionPublicationError) throw error;\n throw new FlowDefinitionPublicationError('INVALID_TRIGGER', 'Flow trigger is not valid JSON');\n }\n }\n const type = String(trigger.type ?? triggerMode ?? 'manual');\n if (type === 'manual') return { kind: 'manual' };\n if (type === 'flow.start') return { kind: 'flow.start' };\n if (type === 'topic.request') {\n if (typeof trigger.requestKind !== 'string' || trigger.requestKind.trim().length === 0) {\n throw new FlowDefinitionPublicationError('INVALID_TRIGGER', 'topic.request requires requestKind');\n }\n return { kind: 'topic.request', requestKind: trigger.requestKind };\n }\n if (type === 'block.event') {\n if (typeof trigger.sourceBlockId !== 'string' || typeof trigger.eventName !== 'string') {\n throw new FlowDefinitionPublicationError('INVALID_TRIGGER', 'block.event requires sourceBlockId and eventName');\n }\n return { kind: 'step.event', sourceBlockId: trigger.sourceBlockId, eventName: trigger.eventName };\n }\n if (type === 'block.event.all') {\n if (!Array.isArray(trigger.sources)) throw new FlowDefinitionPublicationError('INVALID_TRIGGER', 'block.event.all requires sources');\n const sources = trigger.sources.map((source) => {\n if (!source || typeof source !== 'object') throw new FlowDefinitionPublicationError('INVALID_TRIGGER', 'Invalid block.event.all source');\n const candidate = source as Record<string, unknown>;\n if (typeof candidate.sourceBlockId !== 'string' || typeof candidate.eventName !== 'string' || typeof candidate.alias !== 'string') {\n throw new FlowDefinitionPublicationError('INVALID_TRIGGER', 'Every block.event.all source requires sourceBlockId, eventName, and alias');\n }\n return {\n sourceBlockId: candidate.sourceBlockId,\n eventName: candidate.eventName,\n alias: candidate.alias,\n ...(candidate.optional === true ? { optional: true } : {}),\n };\n });\n return { kind: 'step.event.all', sources };\n }\n if (type === 'schedule') {\n if (typeof trigger.scheduleRef !== 'string' || trigger.scheduleRef.trim().length === 0) {\n throw new FlowDefinitionPublicationError('INVALID_TRIGGER', 'schedule requires scheduleRef');\n }\n if (trigger.scheduleRevision !== undefined && (!Number.isInteger(trigger.scheduleRevision) || Number(trigger.scheduleRevision) < 1)) {\n throw new FlowDefinitionPublicationError('INVALID_TRIGGER', 'scheduleRevision must be an integer greater than zero');\n }\n return {\n kind: 'schedule',\n scheduleRef: trigger.scheduleRef,\n ...(typeof trigger.scheduleRevision === 'number' ? { scheduleRevision: trigger.scheduleRevision } : {}),\n };\n }\n throw new FlowDefinitionPublicationError('INVALID_TRIGGER', `Unsupported Flow trigger: ${type}`);\n}\n\nfunction actorFromProps(props: Record<string, string>): FlowJsonObject {\n const actor: FlowJsonObject = {};\n if (props.authorisedActors) {\n let actors: unknown;\n try {\n actors = JSON.parse(props.authorisedActors);\n } catch (error) {\n throw new FlowDefinitionPublicationError('INVALID_CONFIGURATION', `Flow step authorisedActors is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (!Array.isArray(actors) || actors.some((actorDid) => typeof actorDid !== 'string')) {\n throw new FlowDefinitionPublicationError('INVALID_CONFIGURATION', 'Flow step authorisedActors must be an array of DID strings');\n }\n actor.authorisedActors = actors;\n }\n if (props.parentCapability) actor.parentCapability = props.parentCapability;\n return actor;\n}\n\nfunction ttlMsFromProps(props: Record<string, string>): number | undefined {\n const raw = props.ttlMs ?? props.ttl;\n if (!raw) return undefined;\n const numeric = Number(raw);\n if (!Number.isFinite(numeric) || numeric < 0) {\n throw new FlowDefinitionPublicationError('INVALID_CONFIGURATION', 'Flow step ttlMs must be a non-negative number');\n }\n return numeric;\n}\n\nfunction isPositiveDuration(value: string): boolean {\n const match = /^P(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?)?$/u.exec(value);\n return Boolean(match && match.slice(1).some((part) => Number(part ?? 0) > 0));\n}\n\nfunction ttlConstraintsFromProps(props: Record<string, string>): FlowStepDefinitionV1['ttl'] | undefined {\n const ttl: NonNullable<FlowStepDefinitionV1['ttl']> = {};\n if (props.ttlAbsoluteDueDate) {\n if (!Number.isFinite(Date.parse(props.ttlAbsoluteDueDate))) {\n throw new FlowDefinitionPublicationError('INVALID_CONFIGURATION', 'Flow step ttlAbsoluteDueDate must be a valid ISO 8601 date');\n }\n ttl.absoluteDueDate = props.ttlAbsoluteDueDate;\n }\n for (const [prop, field] of [\n ['ttlFromEnablement', 'fromEnablement'],\n ['ttlFromCommitment', 'fromCommitment'],\n ] as const) {\n const value = props[prop];\n if (!value) continue;\n if (!isPositiveDuration(value)) {\n throw new FlowDefinitionPublicationError('INVALID_CONFIGURATION', `Flow step ${prop} must be a positive ISO 8601 day/hour/minute duration`);\n }\n ttl[field] = value;\n }\n return Object.keys(ttl).length > 0 ? ttl : undefined;\n}\n\nfunction toStep(node: NonNullable<ReturnType<typeof readFlowDocument>>['nodes'][number], action: ActionContractRef): FlowStepDefinitionV1 {\n const ttlMs = ttlMsFromProps(node.props);\n const ttl = ttlConstraintsFromProps(node.props);\n return {\n stepId: node.nodeId,\n blockId: node.blockId,\n title: node.title,\n ...(node.description ? { description: node.description } : {}),\n action,\n resource: node.with,\n configuration: { ...node.props },\n inputs: parseObject(node.props.inputs, 'inputs'),\n trigger: parseTrigger(node.props.trigger, node.props.triggerMode),\n conditions: parseConditions(node.props.conditions),\n actor: actorFromProps(node.props),\n ...(ttlMs !== undefined ? { ttlMs } : {}),\n ...(ttl ? { ttl } : {}),\n };\n}\n\n/** Publish one immutable revision from the canonical typed draft. */\nexport async function publishFlowDefinitionRevision(params: PublishFlowDefinitionParams): Promise<PublishFlowDefinitionResult> {\n const expectedParent = params.expectedParent\n ? deepFreezeJson(JSON.parse(canonicalizeJson(params.expectedParent as unknown as CanonicalJsonValue)) as FlowDefinitionRef)\n : undefined;\n if (params.yDoc.getMap('qi.flow.meta').get('draftSchemaVersion') !== 1) {\n throw new FlowDefinitionPublicationError('NOT_VNEXT_DRAFT', 'Legacy Flow documents must be explicitly republished before vNext publication');\n }\n const document = readFlowDocument(params.yDoc);\n if (!document || document.nodes.length === 0) throw new FlowDefinitionPublicationError('EMPTY_FLOW', 'A Flow definition requires at least one step');\n\n const steps = document.nodes.map((node) => {\n const actionType = node.props.actionType;\n const action = actionType ? params.actionContracts[actionType] : undefined;\n if (!action) throw new FlowDefinitionPublicationError('MISSING_ACTION_CONTRACT', `No pinned Action contract for ${actionType || node.nodeId}`);\n if (action.type !== actionType || action.can !== node.can) {\n throw new FlowDefinitionPublicationError('MISSING_ACTION_CONTRACT', `Pinned Action contract does not match ${actionType} (${node.can})`);\n }\n if (action.manifestDigest !== params.actionManifestDigest) {\n throw new FlowDefinitionPublicationError('MISSING_ACTION_CONTRACT', `Action ${action.type} is not pinned to the publication manifest`);\n }\n return toStep(node, action);\n });\n\n const signed = await signFlowDefinitionRevision(\n {\n kind: 'qi.flow.definition-revision',\n schemaVersion: '1.0',\n ref: { flowId: params.flowId, revision: params.revision },\n ...(expectedParent ? { parent: expectedParent } : {}),\n publishedAt: params.publishedAt,\n publishedBy: params.publishedBy,\n actionManifestDigest: params.actionManifestDigest,\n title: document.meta.title,\n ...(document.meta.goal ? { goal: document.meta.goal } : {}),\n steps,\n participantRequirements: readFlowParticipants(params.yDoc).map(participantRequirement),\n connectionRequirements: readFlowConnections(params.yDoc).map(connectionRequirement),\n ...(params.source ? { source: params.source } : {}),\n },\n params.signer\n );\n const ref: FlowDefinitionRef = { ...signed.ref, digest: signed.integrity.digest.value };\n const outcome = await params.repository.publish(signed, expectedParent);\n if (outcome === 'parent_conflict') throw new FlowDefinitionPublicationError('PARENT_CONFLICT', 'Flow definition head changed before publication');\n return { outcome, ref, revision: signed };\n}\n","import { canonicalizeJson, deepFreezeJson, digestCanonicalJson, type CanonicalJsonValue } from '../flowEngine/vnext/canonical';\nimport type { Sha256Digest } from '../flowEngine/vnext/contracts';\nimport type { FlowDefinitionDraftRepository, FlowDraftCommandOperation, FlowDraftCommandResult } from './draftRepository';\n\nexport interface FlowDraftProposalPayloadV1 {\n kind: 'qi.flow.draft-proposal';\n schemaVersion: '1.0';\n proposalId: string;\n proposedBy: string;\n proposedAt: string;\n baseRevision: number;\n operations: readonly FlowDraftCommandOperation[];\n summary: string;\n}\n\nexport type FlowDraftProposalV1 = FlowDraftProposalPayloadV1 & { proposalDigest: Sha256Digest };\n\nexport interface FlowDraftProposalApprovalV1 {\n kind: 'qi.flow.draft-proposal-approval';\n schemaVersion: '1.0';\n proposalId: string;\n proposalDigest: Sha256Digest;\n approvedBy: string;\n approvedAt: string;\n approvalReference: string;\n}\n\nfunction canonicalSnapshot<T>(value: T): T {\n return deepFreezeJson(JSON.parse(canonicalizeJson(value as unknown as CanonicalJsonValue))) as T;\n}\n\nexport async function createFlowDraftProposal(payload: FlowDraftProposalPayloadV1): Promise<FlowDraftProposalV1> {\n const snapshot = canonicalSnapshot(payload);\n if (!snapshot.proposalId || !snapshot.proposedBy || snapshot.operations.length === 0) throw new Error('Flow draft proposal identity, proposer, and operations are required');\n return deepFreezeJson({ ...snapshot, proposalDigest: (await digestCanonicalJson(snapshot as unknown as CanonicalJsonValue)) as Sha256Digest });\n}\n\n/**\n * Apply a reviewed Oracle proposal only when an external approval binds the\n * exact proposal digest. The Oracle never receives direct Yjs access.\n */\nexport async function applyApprovedFlowDraftProposal(\n repository: FlowDefinitionDraftRepository,\n proposal: FlowDraftProposalV1,\n approval: FlowDraftProposalApprovalV1\n): Promise<FlowDraftCommandResult[]> {\n const proposalSnapshot = canonicalSnapshot(proposal);\n const approvalSnapshot = canonicalSnapshot(approval);\n const { proposalDigest, ...proposalPayload } = proposalSnapshot;\n const actualProposalDigest = (await digestCanonicalJson(proposalPayload as unknown as CanonicalJsonValue)) as Sha256Digest;\n if (\n approvalSnapshot.kind !== 'qi.flow.draft-proposal-approval' ||\n approvalSnapshot.schemaVersion !== '1.0' ||\n approvalSnapshot.proposalId !== proposalSnapshot.proposalId ||\n approvalSnapshot.proposalDigest !== proposalDigest ||\n actualProposalDigest !== proposalDigest ||\n !approvalSnapshot.approvedBy ||\n !approvalSnapshot.approvalReference\n ) {\n throw new Error('Flow draft proposal requires an approval for its exact digest');\n }\n const approvedRevision = repository.read().revision;\n if (approvedRevision !== proposalSnapshot.baseRevision) {\n throw new Error(`Flow draft proposal was approved for revision ${proposalSnapshot.baseRevision}, but the draft is now revision ${approvedRevision}`);\n }\n const commands = proposalSnapshot.operations.map(\n (operation, index) =>\n ({\n kind: 'qi.flow.draft-command',\n schemaVersion: '1.0',\n commandId: `${proposalSnapshot.proposalId}:${index}`,\n expectedRevision: proposalSnapshot.baseRevision + index,\n actorDid: approvalSnapshot.approvedBy,\n operation,\n }) as const\n );\n return repository.applyBatch(commands);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,YAAY,OAAO;AA6BnB,SAAS,oBAAoB,MAAuE;AAClG,QAAM,iBAAiB,qBAAqB,IAA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UAAU,IAAI,KAAK;AAAA,MAClD,kBAAkB,iBAAiB,eAAe;AAAA,MAClD,UAAU,iBAAiB;AAAA,MAC3B;AAAA,IACF;AAAA,EACJ;AACA,SAAO,WAAW,WAAW,QAAQ;AACvC;","names":["Y","Y"]}
@@ -155,6 +155,7 @@ __export(core_exports, {
155
155
  actionManifestIssues: () => actionManifestIssues,
156
156
  actionTypeToCan: () => actionTypeToCan,
157
157
  addFlowNode: () => addFlowNode,
158
+ addUnlistedSteps: () => addUnlistedSteps,
158
159
  adoptLegacyFlowDocument: () => adoptLegacyFlowDocument,
159
160
  adoptLegacyRuntime: () => adoptLegacyRuntime,
160
161
  appendAgentLedgerEvent: () => appendAgentLedgerEvent,
@@ -277,6 +278,7 @@ __export(core_exports, {
277
278
  executeQueuedAgentCommands: () => executeQueuedAgentCommands,
278
279
  executeQueuedFlowAgentCoreCommands: () => executeQueuedFlowAgentCoreCommands,
279
280
  findFailedListenersForSourceRun: () => findFailedListenersForSourceRun,
281
+ findUnlistedActionBlocks: () => findUnlistedActionBlocks,
280
282
  findXeroWorkItems: () => findXeroWorkItems,
281
283
  findXeroWorkItemsForEditor: () => findXeroWorkItemsForEditor,
282
284
  fingerprintFlowCommand: () => fingerprintFlowCommand,
@@ -28325,12 +28327,121 @@ function createYMapFromNode(node) {
28325
28327
  return yNode;
28326
28328
  }
28327
28329
 
28330
+ // src/core/lib/flowCompiler/stepListMigration.ts
28331
+ var Y7 = __toESM(require("yjs"), 1);
28332
+ function actionBlocksInOrder(yDoc) {
28333
+ const propsByBlockId = legacyPropsByBlockId(yDoc);
28334
+ const blocks = [];
28335
+ const walk = (parent) => {
28336
+ for (let index = 0; index < parent.length; index += 1) {
28337
+ const child = parent.get(index);
28338
+ if (!(child instanceof Y7.XmlElement)) continue;
28339
+ if (child.nodeName === "blockContainer") {
28340
+ const content = child.get(0);
28341
+ const attrs = child.getAttribute("attrs");
28342
+ const directId = child.getAttribute("id");
28343
+ const blockId = typeof directId === "string" && directId ? directId : typeof attrs?.id === "string" ? attrs.id : "";
28344
+ if (blockId && content instanceof Y7.XmlElement && content.nodeName === COMPILED_BLOCK_TYPE) {
28345
+ blocks.push({ blockId, props: propsByBlockId.get(blockId) ?? {} });
28346
+ }
28347
+ }
28348
+ walk(child);
28349
+ }
28350
+ };
28351
+ walk(yDoc.getXmlFragment("document"));
28352
+ return blocks;
28353
+ }
28354
+ function listedBlockIds(yDoc) {
28355
+ const listed = /* @__PURE__ */ new Set();
28356
+ yDoc.getMap("qi.flow.nodes").forEach((value, nodeId) => {
28357
+ listed.add(nodeId);
28358
+ const blockId = value instanceof Y7.Map ? value.get("blockId") : void 0;
28359
+ if (typeof blockId === "string" && blockId) listed.add(blockId);
28360
+ });
28361
+ yDoc.getMap("qi.flow.blockIndex").forEach((blockId) => listed.add(blockId));
28362
+ return listed;
28363
+ }
28364
+ function governedByStepList(yDoc) {
28365
+ return yDoc.getMap("qi.flow.meta").get("draftSchemaVersion") === 1 || yDoc.getMap("qi.flow.nodes").size === 0;
28366
+ }
28367
+ function findUnlistedActionBlocks(yDoc) {
28368
+ if (!governedByStepList(yDoc)) return [];
28369
+ const listed = listedBlockIds(yDoc);
28370
+ return actionBlocksInOrder(yDoc).filter((block) => !listed.has(block.blockId)).map((block) => {
28371
+ const actionType = block.props.actionType ?? "";
28372
+ return { blockId: block.blockId, actionType, known: Boolean(actionType && getAction(actionType)) };
28373
+ });
28374
+ }
28375
+ function flowSegment(yDoc) {
28376
+ const docId = yDoc.getMap("root").get("doc_id");
28377
+ if (typeof docId === "string" && docId) return `ixo:flow:${docId}`;
28378
+ const flowId = yDoc.getMap("qi.flow.meta").get("flowId");
28379
+ return typeof flowId === "string" && flowId ? `ixo:flow:${flowId}` : "ixo:flow";
28380
+ }
28381
+ function addUnlistedSteps(yDoc) {
28382
+ const unlisted = findUnlistedActionBlocks(yDoc).filter((block) => block.known);
28383
+ if (unlisted.length === 0) return [];
28384
+ const blocks = actionBlocksInOrder(yDoc);
28385
+ const propsByBlockId = new Map(blocks.map((block) => [block.blockId, block.props]));
28386
+ const flowPrefix = flowSegment(yDoc);
28387
+ const added = [];
28388
+ yDoc.transact(() => {
28389
+ const nodes = yDoc.getMap("qi.flow.nodes");
28390
+ const blockIndex = yDoc.getMap("qi.flow.blockIndex");
28391
+ for (const { blockId, actionType } of unlisted) {
28392
+ const action = getAction(actionType);
28393
+ if (!action) continue;
28394
+ const props = propsByBlockId.get(blockId) ?? {};
28395
+ const resource = `${flowPrefix}:${blockId}`;
28396
+ const node = {
28397
+ id: blockId,
28398
+ blockId,
28399
+ can: action.can ?? "",
28400
+ with: resource,
28401
+ registryType: action.type,
28402
+ title: props.title || action.can || action.type,
28403
+ description: props.description ?? "",
28404
+ props: { ...props, with: resource }
28405
+ };
28406
+ nodes.set(blockId, createYMapFromNode(node));
28407
+ blockIndex.set(blockId, blockId);
28408
+ added.push(blockId);
28409
+ }
28410
+ const order = yDoc.getArray("qi.flow.order");
28411
+ if (order.length > 0) {
28412
+ const nodeIdByBlock = /* @__PURE__ */ new Map();
28413
+ nodes.forEach((value, nodeId) => {
28414
+ const blockId = value instanceof Y7.Map ? value.get("blockId") : void 0;
28415
+ nodeIdByBlock.set(typeof blockId === "string" && blockId ? blockId : nodeId, nodeId);
28416
+ });
28417
+ for (const blockId of added) {
28418
+ const position = blocks.findIndex((block) => block.blockId === blockId);
28419
+ let insertAt = 0;
28420
+ for (let previous = position - 1; previous >= 0; previous -= 1) {
28421
+ const previousNode = nodeIdByBlock.get(blocks[previous].blockId);
28422
+ const index = previousNode ? order.toArray().indexOf(previousNode) : -1;
28423
+ if (index >= 0) {
28424
+ insertAt = index + 1;
28425
+ break;
28426
+ }
28427
+ }
28428
+ order.insert(insertAt, [blockId]);
28429
+ }
28430
+ }
28431
+ const meta = yDoc.getMap("qi.flow.meta");
28432
+ if (meta.get("draftSchemaVersion") !== 1) meta.set("draftSchemaVersion", 1);
28433
+ meta.delete("definitionDigest");
28434
+ ensureFlowExecutionMetadata(yDoc);
28435
+ }, "step-list-migration");
28436
+ return added;
28437
+ }
28438
+
28328
28439
  // src/core/lib/flowCompiler/setup.ts
28329
- var Y8 = __toESM(require("yjs"), 1);
28440
+ var Y9 = __toESM(require("yjs"), 1);
28330
28441
  var import_matrix_crdt2 = require("@ixo/matrix-crdt");
28331
28442
 
28332
28443
  // src/core/lib/flowCompiler/documentFragment.ts
28333
- var Y7 = __toESM(require("yjs"), 1);
28444
+ var Y8 = __toESM(require("yjs"), 1);
28334
28445
  function writeCompiledBlocksToFragment(fragment, blocks) {
28335
28446
  const documentBlockGroup = getOrCreateDocumentBlockGroup(fragment);
28336
28447
  for (const block of blocks) {
@@ -28452,12 +28563,12 @@ function readBlocksFromFragment(fragment) {
28452
28563
  return blocks;
28453
28564
  }
28454
28565
  function createBlockContainer(block) {
28455
- const blockContainer = new Y7.XmlElement("blockContainer");
28566
+ const blockContainer = new Y8.XmlElement("blockContainer");
28456
28567
  const { backgroundColor: rawBackgroundColor, textColor: rawTextColor, ...contentProps } = block.props;
28457
28568
  blockContainer.setAttribute("id", block.id);
28458
28569
  blockContainer.setAttribute("textColor", rawTextColor || "default");
28459
28570
  blockContainer.setAttribute("backgroundColor", rawBackgroundColor || "default");
28460
- const blockContent = new Y7.XmlElement(block.type);
28571
+ const blockContent = new Y8.XmlElement(block.type);
28461
28572
  for (const [key, value] of Object.entries(contentProps)) {
28462
28573
  if (value !== "") {
28463
28574
  blockContent.setAttribute(key, value);
@@ -28472,7 +28583,7 @@ function appendBlockToGroup(blockGroup, block) {
28472
28583
  }
28473
28584
  function getOrCreateDocumentBlockGroup(fragment) {
28474
28585
  if (fragment.length === 0) {
28475
- const blockGroup = new Y7.XmlElement("blockGroup");
28586
+ const blockGroup = new Y8.XmlElement("blockGroup");
28476
28587
  fragment.insert(0, [blockGroup]);
28477
28588
  return blockGroup;
28478
28589
  }
@@ -28857,7 +28968,7 @@ function applyFlowPlanToYDoc(yDoc, options) {
28857
28968
  return mergeResult.merged;
28858
28969
  }
28859
28970
  async function connectToRoom(roomId, matrixClient, options) {
28860
- const yDoc = new Y8.Doc();
28971
+ const yDoc = new Y9.Doc();
28861
28972
  const client = matrixClient;
28862
28973
  client.canSupportVoip = false;
28863
28974
  client.clientOpts = { lazyLoadMembers: true };
@@ -29265,7 +29376,7 @@ function fragmentHasContentBlocks(fragment) {
29265
29376
  }
29266
29377
 
29267
29378
  // src/core/lib/flowCompiler/draftRepository.ts
29268
- var Y9 = __toESM(require("yjs"), 1);
29379
+ var Y10 = __toESM(require("yjs"), 1);
29269
29380
  var FlowDraftCommandError = class extends Error {
29270
29381
  constructor(code, message, details) {
29271
29382
  super(message);
@@ -29382,14 +29493,14 @@ function createYjsFlowDefinitionDraftRepository(yDoc) {
29382
29493
  },
29383
29494
  applyBatch: (commands) => {
29384
29495
  if (commands.length === 0) return [];
29385
- const beforeVector = Y9.encodeStateVector(yDoc);
29386
- const stagedDoc = new Y9.Doc();
29496
+ const beforeVector = Y10.encodeStateVector(yDoc);
29497
+ const stagedDoc = new Y10.Doc();
29387
29498
  try {
29388
- Y9.applyUpdate(stagedDoc, Y9.encodeStateAsUpdate(yDoc));
29499
+ Y10.applyUpdate(stagedDoc, Y10.encodeStateAsUpdate(yDoc));
29389
29500
  const stagedRepository = createYjsFlowDefinitionDraftRepository(stagedDoc);
29390
29501
  const results = commands.map((command) => stagedRepository.apply(command));
29391
- const update = Y9.encodeStateAsUpdate(stagedDoc, beforeVector);
29392
- yDoc.transact(() => Y9.applyUpdate(yDoc, update), "flow-draft-command-batch");
29502
+ const update = Y10.encodeStateAsUpdate(stagedDoc, beforeVector);
29503
+ yDoc.transact(() => Y10.applyUpdate(yDoc, update), "flow-draft-command-batch");
29393
29504
  return results;
29394
29505
  } finally {
29395
29506
  stagedDoc.destroy();
@@ -29402,7 +29513,7 @@ function createYjsFlowDefinitionDraftRepository(yDoc) {
29402
29513
  }
29403
29514
 
29404
29515
  // src/core/lib/flowCompiler/participants.ts
29405
- var Y10 = __toESM(require("yjs"), 1);
29516
+ var Y11 = __toESM(require("yjs"), 1);
29406
29517
  var FLOW_PARTICIPANTS_MAP_KEY = "qi.flow.participants";
29407
29518
  function readFlowParticipants(yDoc) {
29408
29519
  const participants = [];
@@ -29462,7 +29573,7 @@ function getParticipantsMap(yDoc) {
29462
29573
  function ensureEntry2(map, userId) {
29463
29574
  const existing = map.get(userId);
29464
29575
  if (isYMapLike(existing)) return existing;
29465
- const created = new Y10.Map();
29576
+ const created = new Y11.Map();
29466
29577
  map.set(userId, created);
29467
29578
  return created;
29468
29579
  }
@@ -31096,6 +31207,7 @@ function createOracleInitFlowTemplate() {
31096
31207
  actionManifestIssues,
31097
31208
  actionTypeToCan,
31098
31209
  addFlowNode,
31210
+ addUnlistedSteps,
31099
31211
  adoptLegacyFlowDocument,
31100
31212
  adoptLegacyRuntime,
31101
31213
  appendAgentLedgerEvent,
@@ -31218,6 +31330,7 @@ function createOracleInitFlowTemplate() {
31218
31330
  executeQueuedAgentCommands,
31219
31331
  executeQueuedFlowAgentCoreCommands,
31220
31332
  findFailedListenersForSourceRun,
31333
+ findUnlistedActionBlocks,
31221
31334
  findXeroWorkItems,
31222
31335
  findXeroWorkItemsForEditor,
31223
31336
  fingerprintFlowCommand,