import type { WorkflowTaskExecution } from "./types.js"; export interface ExecutionContext { node: WorkflowTaskExecution; key: string; scope: string[]; loopPath: string; } /** Index real executions by parent task path, loop context and repeated occurrence. */ export function indexExecutionContexts(tree: WorkflowTaskExecution[]): ExecutionContext[] { const result: ExecutionContext[] = []; const entries = new Map(); const occurrences = new Map(); function collect(node: WorkflowTaskExecution, parentId?: string) { if (!node || !node.id || entries.has(node.id)) return; entries.set(node.id, { node, parentId: String(node.parentId || parentId || "") || undefined }); for (const key of ["children", "subTasks", "items", "tasks"]) { const children = node[key]; if (Array.isArray(children)) for (const child of children) collect(child, node.id); } } for (const node of tree) collect(node); const scopes = new Map(); function scopeOf(id: string, visited = new Set()): { parts: string[]; loopPath: string } { const cached = scopes.get(id); if (cached) return cached; const entry = entries.get(id); if (!entry || visited.has(id)) return { parts: [JSON.stringify(["unresolved-parent", id])], loopPath: "" }; visited.add(id); const parent = entry.parentId ? scopeOf(entry.parentId, visited) : { parts: [], loopPath: "" }; const loopPath = String(entry.node.currentLoopPath ?? parent.loopPath); const scope = { parts: [...parent.parts, JSON.stringify([entry.node.name || entry.node.type || "unnamed", loopPath])], loopPath }; scopes.set(id, scope); return scope; } for (const { node } of entries.values()) { const { parts, loopPath } = scopeOf(node.id); const base = JSON.stringify(parts); const occurrence = occurrences.get(base) ?? 0; occurrences.set(base, occurrence + 1); result.push({ node, key: `${base}#${occurrence}`, scope: parts.slice(0, -1), loopPath }); } return result; }