@probelabs/visor 0.1.125 → 0.1.127
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.
- package/dist/ai-review-service.d.ts +1 -0
- package/dist/ai-review-service.d.ts.map +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/docs/ai-configuration.md +23 -0
- package/dist/docs/slack-integration.md +6 -0
- package/dist/docs/workflows.md +30 -1
- package/dist/failure-condition-evaluator.d.ts.map +1 -1
- package/dist/frontends/slack-frontend.d.ts +2 -0
- package/dist/frontends/slack-frontend.d.ts.map +1 -1
- package/dist/generated/config-schema.d.ts +18 -6
- package/dist/generated/config-schema.d.ts.map +1 -1
- package/dist/generated/config-schema.json +18 -6
- package/dist/index.js +7138 -7865
- package/dist/liquid-extensions.d.ts.map +1 -1
- package/dist/output/traces/{run-2026-01-30T09-25-36-981Z.ndjson → run-2026-02-01T09-59-08-165Z.ndjson} +84 -84
- package/dist/output/traces/{run-2026-01-30T09-26-20-969Z.ndjson → run-2026-02-01T09-59-52-595Z.ndjson} +1015 -1015
- package/dist/providers/ai-check-provider.d.ts.map +1 -1
- package/dist/providers/command-check-provider.d.ts.map +1 -1
- package/dist/providers/custom-tool-executor.d.ts.map +1 -1
- package/dist/providers/http-client-provider.d.ts.map +1 -1
- package/dist/providers/mcp-check-provider.d.ts.map +1 -1
- package/dist/providers/memory-check-provider.d.ts.map +1 -1
- package/dist/providers/workflow-check-provider.d.ts.map +1 -1
- package/dist/sdk/{check-provider-registry-3KI5RKXT.mjs → check-provider-registry-CVUONJ5A.mjs} +8 -8
- package/dist/sdk/{chunk-7GUAFV6L.mjs → chunk-BHOKBQPB.mjs} +15 -10
- package/dist/sdk/chunk-BHOKBQPB.mjs.map +1 -0
- package/dist/sdk/{chunk-PXFIALUH.mjs → chunk-EORMDOZU.mjs} +19 -62
- package/dist/sdk/chunk-EORMDOZU.mjs.map +1 -0
- package/dist/sdk/{chunk-SWEEZ5D5.mjs → chunk-MPS4HVQI.mjs} +11 -77
- package/dist/sdk/chunk-MPS4HVQI.mjs.map +1 -0
- package/dist/sdk/{chunk-A4PGHURG.mjs → chunk-TS6BUNAI.mjs} +130 -75
- package/dist/sdk/chunk-TS6BUNAI.mjs.map +1 -0
- package/dist/sdk/{chunk-J6EVEXC2.mjs → chunk-VW2GBXQT.mjs} +56 -8
- package/dist/sdk/chunk-VW2GBXQT.mjs.map +1 -0
- package/dist/sdk/{chunk-RTKJXNZS.mjs → chunk-XWJPT5KQ.mjs} +26 -9
- package/dist/sdk/chunk-XWJPT5KQ.mjs.map +1 -0
- package/dist/sdk/{config-6CUVEH7H.mjs → config-DXX64GD3.mjs} +2 -2
- package/dist/sdk/{failure-condition-evaluator-HB35XRLZ.mjs → failure-condition-evaluator-G4HMJPXF.mjs} +3 -3
- package/dist/sdk/{github-frontend-BZ4N3BFZ.mjs → github-frontend-5PCKKHVC.mjs} +3 -3
- package/dist/sdk/{host-NYWXLIFC.mjs → host-H3AWNZ2F.mjs} +3 -3
- package/dist/sdk/{liquid-extensions-DFDEBMUI.mjs → liquid-extensions-I7O7KMHF.mjs} +3 -2
- package/dist/sdk/{routing-7FXPULTO.mjs → routing-QHTGDIXF.mjs} +4 -4
- package/dist/sdk/sdk.d.mts +6 -0
- package/dist/sdk/sdk.d.ts +6 -0
- package/dist/sdk/sdk.js +255 -214
- package/dist/sdk/sdk.js.map +1 -1
- package/dist/sdk/sdk.mjs +11 -11
- package/dist/sdk/{slack-frontend-J442FJWZ.mjs → slack-frontend-JUT3TYVC.mjs} +34 -6
- package/dist/sdk/slack-frontend-JUT3TYVC.mjs.map +1 -0
- package/dist/sdk/{workflow-check-provider-YUNNF4KC.mjs → workflow-check-provider-3IWBAZP7.mjs} +8 -8
- package/dist/sdk/{workflow-registry-6LZKCWHP.mjs → workflow-registry-KFWSDSLM.mjs} +2 -2
- package/dist/slack/socket-runner.d.ts +2 -0
- package/dist/slack/socket-runner.d.ts.map +1 -1
- package/dist/state-machine/dispatch/stats-manager.d.ts.map +1 -1
- package/dist/state-machine/states/routing.d.ts.map +1 -1
- package/dist/test-runner/index.d.ts.map +1 -1
- package/dist/test-runner/validator.d.ts.map +1 -1
- package/dist/traces/{run-2026-01-30T09-25-36-981Z.ndjson → run-2026-02-01T09-59-08-165Z.ndjson} +84 -84
- package/dist/traces/{run-2026-01-30T09-26-20-969Z.ndjson → run-2026-02-01T09-59-52-595Z.ndjson} +1015 -1015
- package/dist/types/config.d.ts +6 -0
- package/dist/types/config.d.ts.map +1 -1
- package/dist/utils/worktree-manager.d.ts.map +1 -1
- package/dist/workflow-executor.d.ts.map +1 -1
- package/dist/workflow-registry.d.ts +1 -0
- package/dist/workflow-registry.d.ts.map +1 -1
- package/package.json +5 -6
- package/dist/sdk/chunk-7GUAFV6L.mjs.map +0 -1
- package/dist/sdk/chunk-A4PGHURG.mjs.map +0 -1
- package/dist/sdk/chunk-J6EVEXC2.mjs.map +0 -1
- package/dist/sdk/chunk-PXFIALUH.mjs.map +0 -1
- package/dist/sdk/chunk-RTKJXNZS.mjs.map +0 -1
- package/dist/sdk/chunk-SWEEZ5D5.mjs.map +0 -1
- package/dist/sdk/slack-frontend-J442FJWZ.mjs.map +0 -1
- /package/dist/sdk/{check-provider-registry-3KI5RKXT.mjs.map → check-provider-registry-CVUONJ5A.mjs.map} +0 -0
- /package/dist/sdk/{config-6CUVEH7H.mjs.map → config-DXX64GD3.mjs.map} +0 -0
- /package/dist/sdk/{failure-condition-evaluator-HB35XRLZ.mjs.map → failure-condition-evaluator-G4HMJPXF.mjs.map} +0 -0
- /package/dist/sdk/{github-frontend-BZ4N3BFZ.mjs.map → github-frontend-5PCKKHVC.mjs.map} +0 -0
- /package/dist/sdk/{host-NYWXLIFC.mjs.map → host-H3AWNZ2F.mjs.map} +0 -0
- /package/dist/sdk/{liquid-extensions-DFDEBMUI.mjs.map → liquid-extensions-I7O7KMHF.mjs.map} +0 -0
- /package/dist/sdk/{routing-7FXPULTO.mjs.map → routing-QHTGDIXF.mjs.map} +0 -0
- /package/dist/sdk/{workflow-check-provider-YUNNF4KC.mjs.map → workflow-check-provider-3IWBAZP7.mjs.map} +0 -0
- /package/dist/sdk/{workflow-registry-6LZKCWHP.mjs.map → workflow-registry-KFWSDSLM.mjs.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/dependency-resolver.ts","../../src/workflow-registry.ts"],"sourcesContent":["/**\n * Dependency resolution and execution ordering for checks\n */\n\nexport interface CheckNode {\n id: string;\n dependencies: string[];\n dependents: string[];\n depth: number;\n}\n\nexport interface ExecutionGroup {\n /** Checks that can run in parallel */\n parallel: string[];\n /** Execution level/wave (0 = no dependencies, 1 = depends on level 0, etc.) */\n level: number;\n}\n\nexport interface DependencyGraph {\n nodes: Map<string, CheckNode>;\n executionOrder: ExecutionGroup[];\n hasCycles: boolean;\n cycleNodes?: string[];\n}\n\nexport class DependencyResolver {\n /**\n * Build dependency graph from check dependencies\n */\n static buildDependencyGraph(checkDependencies: Record<string, string[]>): DependencyGraph {\n const nodes = new Map<string, CheckNode>();\n\n // Initialize all nodes\n for (const checkId of Object.keys(checkDependencies)) {\n nodes.set(checkId, {\n id: checkId,\n dependencies: checkDependencies[checkId] || [],\n dependents: [],\n depth: 0,\n });\n }\n\n // Build bidirectional relationships\n for (const [checkId, dependencies] of Object.entries(checkDependencies)) {\n for (const depId of dependencies || []) {\n if (!nodes.has(depId)) {\n throw new Error(`Check \"${checkId}\" depends on \"${depId}\" but \"${depId}\" is not defined`);\n }\n\n const depNode = nodes.get(depId)!;\n depNode.dependents.push(checkId);\n }\n }\n\n // Detect cycles using DFS\n const cycleDetection = this.detectCycles(nodes);\n if (cycleDetection.hasCycles) {\n return {\n nodes,\n executionOrder: [],\n hasCycles: true,\n cycleNodes: cycleDetection.cycleNodes,\n };\n }\n\n // Calculate execution order using topological sort\n const executionOrder = this.topologicalSort(nodes);\n\n return {\n nodes,\n executionOrder,\n hasCycles: false,\n };\n }\n\n /**\n * Detect cycles in the dependency graph using DFS\n */\n private static detectCycles(nodes: Map<string, CheckNode>): {\n hasCycles: boolean;\n cycleNodes?: string[];\n } {\n const visited = new Set<string>();\n const recursionStack = new Set<string>();\n const cycleNodes: string[] = [];\n\n const dfs = (nodeId: string): boolean => {\n if (recursionStack.has(nodeId)) {\n cycleNodes.push(nodeId);\n return true;\n }\n if (visited.has(nodeId)) {\n return false;\n }\n\n visited.add(nodeId);\n recursionStack.add(nodeId);\n\n const node = nodes.get(nodeId);\n if (node) {\n for (const depId of node.dependencies) {\n if (dfs(depId)) {\n cycleNodes.push(nodeId);\n return true;\n }\n }\n }\n\n recursionStack.delete(nodeId);\n return false;\n };\n\n for (const nodeId of nodes.keys()) {\n if (!visited.has(nodeId)) {\n if (dfs(nodeId)) {\n return { hasCycles: true, cycleNodes: [...new Set(cycleNodes)] };\n }\n }\n }\n\n return { hasCycles: false };\n }\n\n /**\n * Perform topological sort to determine execution order\n * Groups checks that can run in parallel at each level\n */\n private static topologicalSort(nodes: Map<string, CheckNode>): ExecutionGroup[] {\n const remainingNodes = new Map(nodes);\n const executionGroups: ExecutionGroup[] = [];\n let level = 0;\n\n while (remainingNodes.size > 0) {\n // Find nodes with no remaining dependencies\n const readyNodes: string[] = [];\n\n for (const [nodeId, node] of remainingNodes.entries()) {\n const unmetDependencies = node.dependencies.filter(depId => remainingNodes.has(depId));\n if (unmetDependencies.length === 0) {\n readyNodes.push(nodeId);\n }\n }\n\n if (readyNodes.length === 0) {\n // This shouldn't happen if cycle detection worked correctly\n throw new Error('Unable to resolve dependencies - possible circular dependency detected');\n }\n\n // Add this group to execution order\n executionGroups.push({\n parallel: readyNodes,\n level,\n });\n\n // Remove processed nodes\n for (const nodeId of readyNodes) {\n remainingNodes.delete(nodeId);\n }\n\n level++;\n }\n\n return executionGroups;\n }\n\n /**\n * Validate that all dependencies exist\n */\n static validateDependencies(\n checkIds: string[],\n dependencies: Record<string, string[]>\n ): { valid: boolean; errors: string[] } {\n const errors: string[] = [];\n const checkIdSet = new Set(checkIds);\n\n for (const [checkId, deps] of Object.entries(dependencies)) {\n if (!checkIdSet.has(checkId)) {\n errors.push(`Check \"${checkId}\" is not in the list of available checks`);\n continue;\n }\n\n for (const depId of deps || []) {\n if (!checkIdSet.has(depId)) {\n errors.push(`Check \"${checkId}\" depends on \"${depId}\" which is not available`);\n }\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n };\n }\n\n /**\n * Get all transitive dependencies (ancestors) for a given check\n * This returns all checks that must complete before the given check can run,\n * not just the direct dependencies.\n *\n * For example, if A -> B -> C, then:\n * - getAllDependencies(C) returns [A, B]\n * - getAllDependencies(B) returns [A]\n * - getAllDependencies(A) returns []\n *\n * @param checkId The check to find dependencies for\n * @param nodes The dependency graph nodes\n * @returns Array of all transitive dependency IDs\n */\n static getAllDependencies(checkId: string, nodes: Map<string, CheckNode>): string[] {\n const allDeps = new Set<string>();\n const visited = new Set<string>();\n\n const collectDependencies = (currentId: string) => {\n if (visited.has(currentId)) {\n return;\n }\n visited.add(currentId);\n\n const node = nodes.get(currentId);\n if (!node) {\n return;\n }\n\n // Add direct dependencies and recurse\n for (const depId of node.dependencies) {\n allDeps.add(depId);\n collectDependencies(depId);\n }\n };\n\n collectDependencies(checkId);\n return Array.from(allDeps);\n }\n\n /**\n * Get execution statistics for debugging\n */\n static getExecutionStats(graph: DependencyGraph): {\n totalChecks: number;\n parallelLevels: number;\n maxParallelism: number;\n averageParallelism: number;\n checksWithDependencies: number;\n } {\n const totalChecks = graph.nodes.size;\n const parallelLevels = graph.executionOrder.length;\n const maxParallelism = Math.max(...graph.executionOrder.map(group => group.parallel.length));\n const averageParallelism = totalChecks / parallelLevels;\n const checksWithDependencies = Array.from(graph.nodes.values()).filter(\n node => node.dependencies.length > 0\n ).length;\n\n return {\n totalChecks,\n parallelLevels,\n maxParallelism,\n averageParallelism,\n checksWithDependencies,\n };\n }\n}\n","/**\n * Workflow registry for managing reusable workflow definitions\n */\n\nimport {\n WorkflowDefinition,\n WorkflowRegistryEntry,\n WorkflowValidationResult,\n WorkflowImportOptions,\n JsonSchema,\n} from './types/workflow';\nimport { promises as fs } from 'fs';\nimport * as path from 'path';\nimport * as yaml from 'js-yaml';\nimport { logger } from './logger';\nimport { DependencyResolver } from './dependency-resolver';\nimport Ajv from 'ajv';\nimport addFormats from 'ajv-formats';\n\n/**\n * Registry for managing workflow definitions\n */\nexport class WorkflowRegistry {\n private static instance: WorkflowRegistry;\n private workflows: Map<string, WorkflowRegistryEntry> = new Map();\n private ajv: Ajv;\n\n private constructor() {\n this.ajv = new Ajv({ allErrors: true, strict: false });\n addFormats(this.ajv);\n }\n\n /**\n * Get the singleton instance of the workflow registry\n */\n public static getInstance(): WorkflowRegistry {\n if (!WorkflowRegistry.instance) {\n WorkflowRegistry.instance = new WorkflowRegistry();\n }\n return WorkflowRegistry.instance;\n }\n\n /**\n * Register a workflow definition\n */\n public register(\n workflow: WorkflowDefinition,\n source: string = 'inline',\n options?: { override?: boolean }\n ): WorkflowValidationResult {\n // Validate the workflow\n const validation = this.validateWorkflow(workflow);\n if (!validation.valid) {\n return validation;\n }\n\n // Check if workflow already exists\n if (this.workflows.has(workflow.id) && !options?.override) {\n return {\n valid: false,\n errors: [\n {\n path: 'id',\n message: `Workflow with ID '${workflow.id}' already exists`,\n value: workflow.id,\n },\n ],\n };\n }\n\n // Register the workflow\n this.workflows.set(workflow.id, {\n definition: workflow,\n source,\n registeredAt: new Date(),\n usage: {\n count: 0,\n },\n });\n\n logger.debug(`Registered workflow '${workflow.id}' from ${source}`);\n return { valid: true };\n }\n\n /**\n * Get a workflow by ID\n */\n public get(id: string): WorkflowDefinition | undefined {\n const entry = this.workflows.get(id);\n if (entry) {\n // Update usage statistics\n entry.usage = entry.usage || { count: 0 };\n entry.usage.count++;\n entry.usage.lastUsed = new Date();\n }\n return entry?.definition;\n }\n\n /**\n * Check if a workflow exists\n */\n public has(id: string): boolean {\n return this.workflows.has(id);\n }\n\n /**\n * List all registered workflows\n */\n public list(): WorkflowDefinition[] {\n return Array.from(this.workflows.values()).map(entry => entry.definition);\n }\n\n /**\n * Get workflow metadata\n */\n public getMetadata(id: string): WorkflowRegistryEntry | undefined {\n return this.workflows.get(id);\n }\n\n /**\n * Remove a workflow from the registry\n */\n public unregister(id: string): boolean {\n return this.workflows.delete(id);\n }\n\n /**\n * Clear all workflows\n */\n public clear(): void {\n this.workflows.clear();\n }\n\n /**\n * Import workflows from a file or URL\n */\n public async import(\n source: string,\n options?: WorkflowImportOptions\n ): Promise<WorkflowValidationResult[]> {\n const results: WorkflowValidationResult[] = [];\n\n try {\n // Load the workflow file\n const content = await this.loadWorkflowContent(source, options?.basePath);\n const data = this.parseWorkflowContent(content, source);\n\n // Handle both single workflow and multiple workflows\n const workflows: WorkflowDefinition[] = Array.isArray(data) ? data : [data];\n\n for (const workflow of workflows) {\n // Validate if requested\n if (options?.validate !== false) {\n const validation = this.validateWorkflow(workflow);\n if (!validation.valid) {\n results.push(validation);\n continue;\n }\n\n // Run custom validators if provided\n if (options?.validators) {\n for (const validator of options.validators) {\n const customValidation = validator(workflow);\n if (!customValidation.valid) {\n results.push(customValidation);\n continue;\n }\n }\n }\n }\n\n // Strip out 'tests' field before registering - tests are only for standalone execution\n const workflowWithoutTests = { ...workflow };\n delete (workflowWithoutTests as any).tests;\n\n // Register the workflow (without tests)\n const result = this.register(workflowWithoutTests, source, { override: options?.override });\n results.push(result);\n }\n } catch (error) {\n results.push({\n valid: false,\n errors: [\n {\n path: 'source',\n message: `Failed to import workflows from '${source}': ${error instanceof Error ? error.message : String(error)}`,\n value: source,\n },\n ],\n });\n }\n\n return results;\n }\n\n /**\n * Import multiple workflow sources\n */\n public async importMany(\n sources: string[],\n options?: WorkflowImportOptions\n ): Promise<Map<string, WorkflowValidationResult[]>> {\n const results = new Map<string, WorkflowValidationResult[]>();\n\n for (const source of sources) {\n const importResults = await this.import(source, options);\n results.set(source, importResults);\n }\n\n return results;\n }\n\n /**\n * Validate a workflow definition\n */\n public validateWorkflow(workflow: WorkflowDefinition): WorkflowValidationResult {\n const errors: Array<{ path: string; message: string; value?: unknown }> = [];\n const warnings: Array<{ path: string; message: string }> = [];\n\n // Validate required fields\n if (!workflow.id) {\n errors.push({ path: 'id', message: 'Workflow ID is required' });\n }\n\n if (!workflow.name) {\n errors.push({ path: 'name', message: 'Workflow name is required' });\n }\n\n if (!workflow.steps || Object.keys(workflow.steps).length === 0) {\n errors.push({ path: 'steps', message: 'Workflow must have at least one step' });\n }\n\n // Validate input parameters\n if (workflow.inputs) {\n for (let i = 0; i < workflow.inputs.length; i++) {\n const input = workflow.inputs[i];\n if (!input.name) {\n errors.push({ path: `inputs[${i}].name`, message: 'Input parameter name is required' });\n }\n if (!input.schema) {\n warnings.push({\n path: `inputs[${i}].schema`,\n message: 'Input parameter schema is recommended',\n });\n }\n }\n }\n\n // Validate output parameters\n if (workflow.outputs) {\n for (let i = 0; i < workflow.outputs.length; i++) {\n const output = workflow.outputs[i];\n if (!output.name) {\n errors.push({ path: `outputs[${i}].name`, message: 'Output parameter name is required' });\n }\n if (!output.value && !output.value_js) {\n errors.push({\n path: `outputs[${i}]`,\n message: 'Output parameter must have either value or value_js',\n });\n }\n }\n }\n\n // Validate steps\n for (const [stepId, step] of Object.entries(workflow.steps || {})) {\n // Validate step dependencies\n if (step.depends_on) {\n for (const dep of step.depends_on) {\n if (!workflow.steps[dep]) {\n errors.push({\n path: `steps.${stepId}.depends_on`,\n message: `Step '${stepId}' depends on non-existent step '${dep}'`,\n value: dep,\n });\n }\n }\n }\n\n // Validate input mappings\n if (step.inputs) {\n for (const [inputName, mapping] of Object.entries(step.inputs)) {\n if (typeof mapping === 'object' && mapping !== null && 'source' in mapping) {\n const typedMapping = mapping as any;\n if (typedMapping.source === 'step' && !typedMapping.stepId) {\n errors.push({\n path: `steps.${stepId}.inputs.${inputName}`,\n message: 'Step input mapping with source \"step\" must have stepId',\n });\n }\n if (typedMapping.source === 'param') {\n // Validate that the parameter exists\n const paramExists = workflow.inputs?.some(p => p.name === typedMapping.value);\n if (!paramExists) {\n errors.push({\n path: `steps.${stepId}.inputs.${inputName}`,\n message: `Step input references non-existent parameter '${typedMapping.value}'`,\n value: typedMapping.value,\n });\n }\n }\n }\n }\n }\n }\n\n // Check for circular dependencies\n const circularDeps = this.detectCircularDependencies(workflow);\n if (circularDeps.length > 0) {\n errors.push({\n path: 'steps',\n message: `Circular dependencies detected: ${circularDeps.join(' -> ')}`,\n });\n }\n\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n }\n\n /**\n * Validate input values against workflow input schema\n */\n public validateInputs(\n workflow: WorkflowDefinition,\n inputs: Record<string, unknown>\n ): WorkflowValidationResult {\n const errors: Array<{ path: string; message: string; value?: unknown }> = [];\n\n if (!workflow.inputs) {\n return { valid: true };\n }\n\n // Check required inputs\n for (const param of workflow.inputs) {\n if (param.required !== false && !(param.name in inputs) && param.default === undefined) {\n errors.push({\n path: `inputs.${param.name}`,\n message: `Required input '${param.name}' is missing`,\n });\n }\n }\n\n // Validate input schemas\n for (const param of workflow.inputs) {\n if (param.name in inputs && param.schema) {\n const value = inputs[param.name];\n const valid = this.validateAgainstSchema(value, param.schema);\n if (!valid.valid) {\n errors.push({\n path: `inputs.${param.name}`,\n message: valid.error || 'Invalid input value',\n value,\n });\n }\n }\n }\n\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n };\n }\n\n /**\n * Load workflow content from file or URL\n */\n private async loadWorkflowContent(source: string, basePath?: string): Promise<string> {\n // Handle URLs\n if (source.startsWith('http://') || source.startsWith('https://')) {\n const response = await fetch(source);\n if (!response.ok) {\n throw new Error(`Failed to fetch workflow from ${source}: ${response.statusText}`);\n }\n return await response.text();\n }\n\n // Handle file paths\n const filePath = path.isAbsolute(source)\n ? source\n : path.resolve(basePath || process.cwd(), source);\n return await fs.readFile(filePath, 'utf-8');\n }\n\n /**\n * Parse workflow content (YAML or JSON)\n */\n private parseWorkflowContent(content: string, source: string): any {\n // Try JSON first\n try {\n return JSON.parse(content);\n } catch {\n // Try YAML\n try {\n return yaml.load(content);\n } catch (error) {\n throw new Error(\n `Failed to parse workflow file ${source}: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n }\n\n /**\n * Detect circular dependencies in workflow steps using DependencyResolver\n */\n private detectCircularDependencies(workflow: WorkflowDefinition): string[] {\n // Build dependency map\n const dependencies: Record<string, string[]> = {};\n for (const [stepId, step] of Object.entries(workflow.steps || {})) {\n // Normalize depends_on to array (supports string | string[])\n const rawDeps = step.depends_on;\n dependencies[stepId] = Array.isArray(rawDeps) ? rawDeps : rawDeps ? [rawDeps] : [];\n }\n\n try {\n // Use DependencyResolver to check for cycles\n const graph = DependencyResolver.buildDependencyGraph(dependencies);\n\n if (graph.hasCycles && graph.cycleNodes) {\n return graph.cycleNodes;\n }\n\n return [];\n } catch {\n // DependencyResolver throws error for non-existent dependencies\n // This should be caught by the dependency validation in validateWorkflow\n // Return empty array here and let the validation handle it\n return [];\n }\n }\n\n /**\n * Validate a value against a JSON schema\n */\n private validateAgainstSchema(\n value: unknown,\n schema: JsonSchema\n ): { valid: boolean; error?: string } {\n try {\n const validate = this.ajv.compile(schema as any);\n const valid = validate(value);\n if (!valid) {\n const errors = validate.errors\n ?.map(e => `${e.instancePath || '/'}: ${e.message}`)\n .join(', ');\n return { valid: false, error: errors };\n }\n return { valid: true };\n } catch (error) {\n return { valid: false, error: error instanceof Error ? error.message : String(error) };\n }\n }\n}\n"],"mappings":";;;;;;;;;AAAA,IAyBa;AAzBb;AAAA;AAAA;AAyBO,IAAM,qBAAN,MAAyB;AAAA;AAAA;AAAA;AAAA,MAI9B,OAAO,qBAAqB,mBAA8D;AACxF,cAAM,QAAQ,oBAAI,IAAuB;AAGzC,mBAAW,WAAW,OAAO,KAAK,iBAAiB,GAAG;AACpD,gBAAM,IAAI,SAAS;AAAA,YACjB,IAAI;AAAA,YACJ,cAAc,kBAAkB,OA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/routing.ts"],"sourcesContent":["/*\n * Internal snapshot store for incremental adoption of snapshot+scope execution.\n * Phase 0: journal only — no behavior change, used for future visibility work.\n */\n\nimport type { ReviewSummary } from './reviewer';\nimport type { EventTrigger } from './types/config';\n\nexport type ScopePath = Array<{ check: string; index: number }>;\n\nexport interface JournalEntry {\n commitId: number;\n sessionId: string;\n scope: ScopePath;\n checkId: string;\n event: EventTrigger | undefined;\n result: ReviewSummary & { output?: unknown; content?: string };\n}\n\nexport class ExecutionJournal {\n private commit = 0;\n private entries: JournalEntry[] = [];\n\n beginSnapshot(): number {\n return this.commit;\n }\n\n commitEntry(entry: {\n sessionId: string;\n scope: ScopePath;\n checkId: string;\n result: ReviewSummary & { output?: unknown; content?: string };\n event?: EventTrigger;\n }): JournalEntry {\n const committed: JournalEntry = {\n sessionId: entry.sessionId,\n scope: entry.scope,\n checkId: entry.checkId,\n result: entry.result,\n event: entry.event,\n commitId: ++this.commit,\n };\n this.entries.push(committed);\n return committed;\n }\n\n readVisible(sessionId: string, commitMax: number, event?: EventTrigger): JournalEntry[] {\n return this.entries.filter(\n e =>\n e.sessionId === sessionId && e.commitId <= commitMax && (event ? e.event === event : true)\n );\n }\n\n // Lightweight helpers for debugging/metrics\n size(): number {\n return this.entries.length;\n }\n}\n\nexport class ContextView {\n constructor(\n private journal: ExecutionJournal,\n private sessionId: string,\n private snapshotId: number,\n private scope: ScopePath,\n private event?: EventTrigger\n ) {}\n\n /** Return the nearest result for a check in this scope (exact item → ancestor → latest). */\n get(checkId: string): (ReviewSummary & { output?: unknown; content?: string }) | undefined {\n const visible = this.journal\n .readVisible(this.sessionId, this.snapshotId, this.event)\n .filter(e => e.checkId === checkId);\n if (visible.length === 0) return undefined;\n\n // exact scope match: prefer the most recent commit for this scope\n const exactMatches = visible.filter(e => this.sameScope(e.scope, this.scope));\n if (exactMatches.length > 0) {\n return exactMatches[exactMatches.length - 1].result;\n }\n\n // nearest ancestor (shortest distance)\n let best: { entry: JournalEntry; dist: number } | undefined;\n for (const e of visible) {\n const dist = this.ancestorDistance(e.scope, this.scope);\n if (dist >= 0 && (best === undefined || dist < best.dist)) {\n best = { entry: e, dist };\n }\n }\n if (best) return best.entry.result;\n\n // fallback to latest committed result\n return visible[visible.length - 1]?.result;\n }\n\n /** Return an aggregate (raw) result – the shallowest scope for this check. */\n getRaw(checkId: string): (ReviewSummary & { output?: unknown; content?: string }) | undefined {\n const visible = this.journal\n .readVisible(this.sessionId, this.snapshotId, this.event)\n .filter(e => e.checkId === checkId);\n if (visible.length === 0) return undefined;\n let shallow = visible[0];\n for (const e of visible) {\n if (e.scope.length < shallow.scope.length) shallow = e;\n }\n return shallow.result;\n }\n\n /** All results for a check up to this snapshot. */\n getHistory(checkId: string): Array<ReviewSummary & { output?: unknown; content?: string }> {\n return this.journal\n .readVisible(this.sessionId, this.snapshotId, this.event)\n .filter(e => e.checkId === checkId)\n .map(e => e.result);\n }\n\n private sameScope(a: ScopePath, b: ScopePath): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i].check !== b[i].check || a[i].index !== b[i].index) return false;\n }\n return true;\n }\n\n // distance from ancestor to current; -1 if not ancestor\n private ancestorDistance(ancestor: ScopePath, current: ScopePath): number {\n if (ancestor.length > current.length) return -1;\n // Treat root scope ([]) as non-ancestor for unrelated branches\n if (ancestor.length === 0 && current.length > 0) return -1;\n for (let i = 0; i < ancestor.length; i++) {\n if (ancestor[i].check !== current[i].check || ancestor[i].index !== current[i].index)\n return -1;\n }\n return current.length - ancestor.length;\n }\n}\n","/**\n * Routing State Handler\n *\n * Responsibilities:\n * - Evaluate fail_if conditions after check execution\n * - Process on_success, on_fail, on_finish triggers\n * - Enqueue ForwardRunRequested events for goto\n * - Enqueue WaveRetry events for routing loops\n * - Transition back to WavePlanning or Completed\n *\n * M2: Core routing logic implementation\n */\n\nimport type { EngineContext, RunState, EngineState, EngineEvent } from '../../types/engine';\nimport type { ReviewSummary, ReviewIssue } from '../../reviewer';\nimport type { CheckConfig, OnFailConfig, TransitionRule } from '../../types/config';\nimport { logger } from '../../logger';\nimport { addEvent } from '../../telemetry/trace-helpers';\nimport { FailureConditionEvaluator } from '../../failure-condition-evaluator';\nimport { createSecureSandbox, compileAndRun } from '../../utils/sandbox';\nimport { MemoryStore } from '../../memory-store';\n\n/**\n * Check if any configured check depends (directly or via OR dependency) on the\n * given `checkId`. Used to decide whether a forEach parent has downstream\n * dependents, in which case its on_finish should defer to the LevelDispatch\n * post-children hook.\n */\n// hasDependents helper removed (unused)\n\n/**\n * Check if any dependent of `checkId` would execute with map fanout.\n * Used to decide whether a forEach parent's on_finish should be deferred to\n * the LevelDispatch post-children hook (only necessary when map-fanout children\n * will run per item).\n */\nfunction hasMapFanoutDependents(context: EngineContext, checkId: string): boolean {\n const checks = context.config.checks || {};\n const reduceProviders = new Set(['log', 'memory', 'script', 'workflow', 'noop']);\n\n for (const [cid, cfg] of Object.entries(checks)) {\n if (cid === checkId) continue;\n const rawDeps = (cfg as any).depends_on || [];\n const depList = Array.isArray(rawDeps) ? rawDeps : [rawDeps];\n // Does this check depend on our target?\n let depends = false;\n for (const dep of depList) {\n if (typeof dep !== 'string') continue;\n if (dep.includes('|')) {\n const opts = dep\n .split('|')\n .map(s => s.trim())\n .filter(Boolean);\n if (opts.includes(checkId)) {\n depends = true;\n break;\n }\n } else if (dep === checkId) {\n depends = true;\n break;\n }\n }\n if (!depends) continue;\n\n // Determine this dependent's fanout mode\n const explicit = (cfg as any).fanout as 'map' | 'reduce' | undefined;\n if (explicit === 'map') return true;\n if (explicit === 'reduce') continue;\n\n // Infer default based on provider type\n const providerType = context.checks[cid]?.providerType || (checks as any)[cid]?.type || '';\n const inferred: 'map' | 'reduce' = reduceProviders.has(providerType) ? 'reduce' : 'map';\n if (inferred === 'map') return true;\n }\n return false;\n}\n\n/** Classify failure type to inform retry policy mapping */\nfunction classifyFailure(result: ReviewSummary): 'none' | 'logical' | 'execution' {\n const issues = result?.issues || [];\n if (!issues || issues.length === 0) return 'none';\n // Heuristics:\n // - logical: fail_if, contract/guarantee_failed, explicit ruleIds ending with _fail_if\n // - execution: provider/command errors, forEach/execution_error, sandbox_runner_error\n let hasLogical = false;\n let hasExecution = false;\n for (const iss of issues) {\n const id = String((iss as any).ruleId || '');\n const msg = String((iss as any).message || '');\n if (\n id.endsWith('_fail_if') ||\n id.includes('contract/guarantee_failed') ||\n id.includes('contract/schema_validation_failed')\n )\n hasLogical = true;\n if (id.includes('/execution_error') || msg.includes('Command execution failed'))\n hasExecution = true;\n if (id.includes('forEach/execution_error') || msg.includes('sandbox_runner_error'))\n hasExecution = true;\n }\n if (hasLogical && !hasExecution) return 'logical';\n if (hasExecution && !hasLogical) return 'execution';\n // Mixed or unknown: treat as execution to avoid suppressing retries unexpectedly\n return hasExecution ? 'execution' : 'logical';\n}\n\nfunction getCriticality(context: EngineContext, checkId: string): CheckConfig['criticality'] {\n const cfg = context.config.checks?.[checkId];\n return (cfg && (cfg as any).criticality) || 'policy';\n}\n\n/**\n * Context for a check that just completed and needs routing evaluation\n */\ninterface RoutingContext {\n checkId: string;\n scope: Array<{ check: string; index: number }>;\n result: ReviewSummary;\n checkConfig: CheckConfig;\n success: boolean; // true if no fatal issues\n}\n\n/**\n * Create memory helpers for sandbox context\n */\nfunction createMemoryHelpers() {\n const memoryStore = MemoryStore.getInstance();\n return {\n get: (key: string, ns?: string) => memoryStore.get(key, ns),\n has: (key: string, ns?: string) => memoryStore.has(key, ns),\n getAll: (ns?: string) => memoryStore.getAll(ns),\n set: (key: string, value: unknown, ns?: string) => {\n const nsName = ns || memoryStore.getDefaultNamespace();\n const data: Map<string, Map<string, unknown>> = (memoryStore as any)['data'];\n if (!data.has(nsName)) data.set(nsName, new Map());\n data.get(nsName)!.set(key, value);\n },\n clear: (ns?: string) => {\n const data: Map<string, Map<string, unknown>> = (memoryStore as any)['data'];\n if (ns) data.delete(ns);\n else data.clear();\n },\n increment: (key: string, amount = 1, ns?: string) => {\n const nsName = ns || memoryStore.getDefaultNamespace();\n const data: Map<string, Map<string, unknown>> = (memoryStore as any)['data'];\n if (!data.has(nsName)) data.set(nsName, new Map());\n const nsMap = data.get(nsName)!;\n const current = nsMap.get(key);\n const numCurrent = typeof current === 'number' ? current : 0;\n const newValue = numCurrent + amount;\n nsMap.set(key, newValue);\n return newValue;\n },\n };\n}\n\nfunction getHistoryLimit(): number | undefined {\n const raw = process.env.VISOR_TEST_HISTORY_LIMIT || process.env.VISOR_OUTPUT_HISTORY_LIMIT;\n if (!raw) return undefined;\n const n = parseInt(raw, 10);\n return Number.isFinite(n) && n > 0 ? n : undefined;\n}\n\ntype RoutingTrigger = 'on_success' | 'on_fail' | 'on_finish';\ntype RoutingAction = 'run' | 'goto' | 'retry';\ntype RoutingSource = 'run' | 'run_js' | 'goto' | 'goto_js' | 'transitions' | 'retry';\n\nfunction formatScopeLabel(scope: Array<{ check: string; index: number }> | undefined): string {\n if (!scope || scope.length === 0) return '';\n return scope.map(item => `${item.check}:${item.index}`).join('|');\n}\n\nfunction recordRoutingEvent(args: {\n checkId: string;\n trigger: RoutingTrigger;\n action: RoutingAction;\n target?: string;\n source?: RoutingSource;\n scope?: Array<{ check: string; index: number }>;\n gotoEvent?: string;\n}): void {\n const attrs: Record<string, unknown> = {\n check_id: args.checkId,\n trigger: args.trigger,\n action: args.action,\n };\n if (args.target) attrs.target = args.target;\n if (args.source) attrs.source = args.source;\n const scopeLabel = formatScopeLabel(args.scope);\n if (scopeLabel) attrs.scope = scopeLabel;\n if (args.gotoEvent) attrs.goto_event = args.gotoEvent;\n addEvent('visor.routing', attrs);\n}\n\n/**\n * Handle routing state - evaluate conditions and decide next actions\n * @returns true if execution was halted (caller should stop processing)\n */\nexport async function handleRouting(\n context: EngineContext,\n state: RunState,\n transition: (newState: EngineState) => void,\n emitEvent: (event: EngineEvent) => void,\n routingContext: RoutingContext\n): Promise<boolean> {\n const { checkId, scope, result, checkConfig, success } = routingContext;\n\n // Always log routing entry for debugging E2E expectations\n logger.info(`[Routing] Evaluating routing for check: ${checkId}, success: ${success}`);\n\n // Step 1: Evaluate fail_if and failure_conditions\n const failureResult = await evaluateFailIf(checkId, result, checkConfig, context, state);\n\n // Step 1.5: Check if we need to halt execution immediately\n if (failureResult.haltExecution) {\n logger.error(\n `[Routing] HALTING EXECUTION due to critical failure in ${checkId}: ${failureResult.haltMessage}`\n );\n\n // Add halt issue to result for reporting\n const haltIssue: ReviewIssue = {\n file: 'system',\n line: 0,\n ruleId: `${checkId}_halt_execution`,\n message: `Execution halted: ${failureResult.haltMessage || 'Critical failure condition met'}`,\n severity: 'error',\n category: 'logic',\n };\n result.issues = [...(result.issues || []), haltIssue];\n\n // Emit Shutdown event to stop the workflow\n emitEvent({\n type: 'Shutdown',\n error: {\n message: failureResult.haltMessage || `Execution halted by check ${checkId}`,\n name: 'HaltExecution',\n },\n });\n\n // Transition to Error state\n transition('Error');\n return true; // Signal that execution was halted\n }\n\n if (failureResult.failed) {\n if (context.debug) {\n logger.info(`[Routing] fail_if/failure_conditions triggered for ${checkId}`);\n }\n\n // Treat as failure for routing purposes\n await processOnFail(checkId, scope, result, checkConfig, context, state, emitEvent);\n } else if (success) {\n // Step 2: Process on_success routing\n await processOnSuccess(checkId, scope, result, checkConfig, context, state, emitEvent);\n } else {\n // Step 3: Process on_fail routing\n await processOnFail(checkId, scope, result, checkConfig, context, state, emitEvent);\n }\n\n // Step 4: on_finish\n // Process on_finish here for:\n // - non-forEach checks\n // - forEach parents that do NOT have map-fanout dependents\n // (reduce-only dependents don't need the post-children barrier)\n const shouldProcessOnFinishHere =\n !!checkConfig.on_finish &&\n (checkConfig.forEach !== true || !hasMapFanoutDependents(context, checkId));\n if (checkConfig.on_finish) {\n logger.info(\n `[Routing] on_finish decision for ${checkId}: forEach=${!!checkConfig.forEach}, processHere=${shouldProcessOnFinishHere}`\n );\n }\n if (shouldProcessOnFinishHere) {\n await processOnFinish(checkId, scope, result, checkConfig, context, state, emitEvent);\n }\n\n // Transition back to WavePlanning to process queued events\n transition('WavePlanning');\n return false; // Execution continues normally\n}\n\n/**\n * Process on_finish routing\n */\nasync function processOnFinish(\n checkId: string,\n scope: Array<{ check: string; index: number }>,\n result: ReviewSummary,\n checkConfig: CheckConfig,\n context: EngineContext,\n state: RunState,\n emitEvent: (event: EngineEvent) => void\n): Promise<void> {\n const onFinish = checkConfig.on_finish;\n\n if (!onFinish) {\n return; // No on_finish configuration\n }\n\n // Log at info level so it's visible in test output\n logger.info(`Processing on_finish for ${checkId}`);\n let queuedForward = false;\n // Process on_finish.run\n if (onFinish.run && onFinish.run.length > 0) {\n // Check if current check is a forEach parent with items\n const currentCheckIsForEach = checkConfig.forEach === true;\n const forEachItems = currentCheckIsForEach ? (result as any).forEachItems : undefined;\n const hasForEachItems = Array.isArray(forEachItems) && forEachItems.length > 0;\n\n for (const targetCheck of onFinish.run) {\n // Check loop budget before scheduling\n if (checkLoopBudget(context, state, 'on_finish', 'run')) {\n const errorIssue: ReviewIssue = {\n file: 'system',\n line: 0,\n ruleId: `${checkId}/routing/loop_budget_exceeded`,\n message: `Routing loop budget exceeded (max_loops=${context.config.routing?.max_loops ?? DEFAULT_MAX_LOOPS}) during on_finish run`,\n severity: 'error',\n category: 'logic',\n };\n result.issues = [...(result.issues || []), errorIssue];\n return;\n }\n\n // Handle fanout: check if target has fanout configuration\n const targetConfig = context.config.checks?.[targetCheck];\n const fanoutMode = targetConfig?.fanout || 'reduce'; // default to reduce\n\n if (context.debug) {\n logger.info(\n `[Routing] on_finish.run: scheduling ${targetCheck} with fanout=${fanoutMode}, hasForEachItems=${hasForEachItems}`\n );\n }\n\n // If current check has forEach items and target is map fanout, emit one event per item\n if (fanoutMode === 'map' && hasForEachItems) {\n // Map fanout: emit one ForwardRunRequested per forEach item\n for (let itemIndex = 0; itemIndex < forEachItems!.length; itemIndex++) {\n // Increment loop count for each item\n state.routingLoopCount++;\n\n const itemScope: Array<{ check: string; index: number }> = [\n { check: checkId, index: itemIndex },\n ];\n\n recordRoutingEvent({\n checkId,\n trigger: 'on_finish',\n action: 'run',\n target: targetCheck,\n source: 'run',\n scope: itemScope,\n });\n emitEvent({\n type: 'ForwardRunRequested',\n target: targetCheck,\n scope: itemScope,\n origin: 'run',\n });\n queuedForward = true;\n }\n } else {\n // Reduce fanout (or no forEach context): emit with empty scope once\n // Increment loop count\n state.routingLoopCount++;\n\n recordRoutingEvent({\n checkId,\n trigger: 'on_finish',\n action: 'run',\n target: targetCheck,\n source: 'run',\n scope: [],\n });\n emitEvent({\n type: 'ForwardRunRequested',\n target: targetCheck,\n scope: [],\n origin: 'run',\n });\n queuedForward = true;\n }\n }\n }\n\n // Process on_finish.run_js\n if (onFinish.run_js) {\n const dynamicTargets = await evaluateRunJs(\n onFinish.run_js,\n checkId,\n checkConfig,\n result,\n context,\n state\n );\n\n for (const targetCheck of dynamicTargets) {\n // Check loop budget before scheduling\n if (checkLoopBudget(context, state, 'on_finish', 'run')) {\n const errorIssue: ReviewIssue = {\n file: 'system',\n line: 0,\n ruleId: `${checkId}/routing/loop_budget_exceeded`,\n message: `Routing loop budget exceeded (max_loops=${context.config.routing?.max_loops ?? DEFAULT_MAX_LOOPS}) during on_finish run`,\n severity: 'error',\n category: 'logic',\n };\n result.issues = [...(result.issues || []), errorIssue];\n return;\n }\n\n if (context.debug) {\n logger.info(`[Routing] on_finish.run_js: scheduling ${targetCheck}`);\n }\n\n // Increment loop count\n state.routingLoopCount++;\n\n recordRoutingEvent({\n checkId,\n trigger: 'on_finish',\n action: 'run',\n target: targetCheck,\n source: 'run_js',\n scope,\n });\n emitEvent({\n type: 'ForwardRunRequested',\n target: targetCheck,\n scope,\n origin: 'run_js',\n });\n queuedForward = true;\n }\n }\n\n // Declarative transitions (override goto/goto_js when present)\n const finishTransTarget = await evaluateTransitions(\n onFinish.transitions,\n checkId,\n checkConfig,\n result,\n context,\n state\n );\n if (finishTransTarget !== undefined) {\n if (finishTransTarget) {\n if (checkLoopBudget(context, state, 'on_finish', 'goto')) {\n const errorIssue: ReviewIssue = {\n file: 'system',\n line: 0,\n ruleId: `${checkId}/routing/loop_budget_exceeded`,\n message: `Routing loop budget exceeded (max_loops=${context.config.routing?.max_loops ?? DEFAULT_MAX_LOOPS}) during on_finish goto`,\n severity: 'error',\n category: 'logic',\n };\n result.issues = [...(result.issues || []), errorIssue];\n return;\n }\n state.routingLoopCount++;\n recordRoutingEvent({\n checkId,\n trigger: 'on_finish',\n action: 'goto',\n target: finishTransTarget.to,\n source: 'transitions',\n scope,\n gotoEvent: finishTransTarget.goto_event,\n });\n emitEvent({\n type: 'ForwardRunRequested',\n target: finishTransTarget.to,\n scope,\n origin: 'goto_js',\n gotoEvent: finishTransTarget.goto_event,\n });\n }\n return; // transitions override goto/goto_js\n }\n\n // Process on_finish.goto / goto_js\n const gotoTarget = await evaluateGoto(\n onFinish.goto_js,\n onFinish.goto,\n checkId,\n checkConfig,\n result,\n context,\n state\n );\n\n if (gotoTarget) {\n // Check loop budget before scheduling goto\n if (checkLoopBudget(context, state, 'on_finish', 'goto')) {\n const errorIssue: ReviewIssue = {\n file: 'system',\n line: 0,\n ruleId: `${checkId}/routing/loop_budget_exceeded`,\n message: `Routing loop budget exceeded (max_loops=${context.config.routing?.max_loops ?? DEFAULT_MAX_LOOPS}) during on_finish goto`,\n severity: 'error',\n category: 'logic',\n };\n result.issues = [...(result.issues || []), errorIssue];\n return;\n }\n\n if (context.debug) {\n logger.info(`[Routing] on_finish.goto: ${gotoTarget}`);\n }\n\n // Increment loop count\n state.routingLoopCount++;\n\n recordRoutingEvent({\n checkId,\n trigger: 'on_finish',\n action: 'goto',\n target: gotoTarget,\n source: onFinish.goto_js ? 'goto_js' : 'goto',\n scope,\n });\n // Enqueue forward run event\n emitEvent({\n type: 'ForwardRunRequested',\n target: gotoTarget,\n scope,\n origin: 'goto_js',\n });\n\n // Mark that we've seen a forward run\n state.flags.forwardRunRequested = true;\n }\n\n // If we scheduled any forward-run targets via on_finish, request a wave retry so\n // dependent checks (with if conditions) can re-evaluate after the forward-run completes.\n // Guard: only enqueue once per originating check per wave to avoid loops.\n if (queuedForward) {\n const guardKey = `waveRetry:on_finish:${checkId}:wave:${state.wave}`;\n if (!(state as any).forwardRunGuards?.has(guardKey)) {\n (state as any).forwardRunGuards?.add(guardKey);\n emitEvent({ type: 'WaveRetry', reason: 'on_finish' });\n }\n }\n}\n\n/**\n * Result of evaluating failure conditions\n */\ninterface FailureEvaluationResult {\n /** Whether any failure condition was triggered */\n failed: boolean;\n /** Whether execution should halt immediately */\n haltExecution: boolean;\n /** Message describing the halt reason (if haltExecution is true) */\n haltMessage?: string;\n}\n\n/**\n * Evaluate fail_if and failure_conditions for a check\n */\n// Returns { failed, haltExecution } to indicate if check failed and if execution should halt.\n// Global fail_if records an issue for summary/reporting but MUST NOT gate routing.\n// failure_conditions with halt_execution: true will trigger workflow halt.\nasync function evaluateFailIf(\n checkId: string,\n result: ReviewSummary,\n checkConfig: CheckConfig,\n context: EngineContext,\n state: RunState\n): Promise<FailureEvaluationResult> {\n const config = context.config;\n\n // Check for fail_if at global or check level\n const globalFailIf = config.fail_if;\n const checkFailIf = checkConfig.fail_if;\n const globalFailureConditions = config.failure_conditions;\n const checkFailureConditions = checkConfig.failure_conditions;\n\n if (!globalFailIf && !checkFailIf && !globalFailureConditions && !checkFailureConditions) {\n return { failed: false, haltExecution: false }; // No failure conditions\n }\n\n const evaluator = new FailureConditionEvaluator();\n\n // Build outputs record from state\n const outputsRecord: Record<string, ReviewSummary> = {};\n for (const [key] of state.stats.entries()) {\n // Try to get the actual result from context.journal if available\n try {\n const snapshotId = context.journal.beginSnapshot();\n const contextView = new (require('../../snapshot-store').ContextView)(\n context.journal,\n context.sessionId,\n snapshotId,\n [],\n context.event\n );\n const journalResult = contextView.get(key);\n if (journalResult) {\n outputsRecord[key] = journalResult as ReviewSummary;\n }\n } catch {\n // Fallback to empty result\n outputsRecord[key] = { issues: [] };\n }\n }\n\n const checkSchema = typeof checkConfig.schema === 'object' ? 'custom' : checkConfig.schema || '';\n const checkGroup = checkConfig.group || '';\n\n let anyFailed = false;\n let shouldHalt = false;\n let haltMessage: string | undefined;\n\n // Evaluate global fail_if (non-gating)\n if (globalFailIf) {\n try {\n const failed = await evaluator.evaluateSimpleCondition(\n checkId,\n checkSchema,\n checkGroup,\n result,\n globalFailIf,\n outputsRecord\n );\n\n if (failed) {\n logger.warn(`[Routing] Global fail_if triggered for ${checkId}: ${globalFailIf}`);\n\n // Add fail_if issue to result\n const failIssue: ReviewIssue = {\n file: 'system',\n line: 0,\n ruleId: 'global_fail_if',\n message: `Global failure condition met: ${globalFailIf}`,\n severity: 'error',\n category: 'logic',\n };\n\n result.issues = [...(result.issues || []), failIssue];\n // IMPORTANT: do not gate routing on global fail_if\n // This condition contributes to overall run status but should not\n // block dependents from executing when the producing check succeeded.\n // Continue evaluating check-level fail_if below.\n }\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n logger.error(`[Routing] Error evaluating global fail_if: ${msg}`);\n }\n }\n\n // Evaluate check-specific fail_if\n if (checkFailIf) {\n try {\n const failed = await evaluator.evaluateSimpleCondition(\n checkId,\n checkSchema,\n checkGroup,\n result,\n checkFailIf,\n outputsRecord\n );\n\n if (failed) {\n logger.warn(`[Routing] Check fail_if triggered for ${checkId}: ${checkFailIf}`);\n\n // Add fail_if issue to result\n const failIssue: ReviewIssue = {\n file: 'system',\n line: 0,\n ruleId: `${checkId}_fail_if`,\n message: `Check failure condition met: ${checkFailIf}`,\n severity: 'error',\n category: 'logic',\n };\n\n result.issues = [...(result.issues || []), failIssue];\n anyFailed = true;\n }\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n logger.error(`[Routing] Error evaluating check fail_if: ${msg}`);\n }\n }\n\n // Evaluate failure_conditions (both global and check-level)\n // These support halt_execution: true\n if (globalFailureConditions || checkFailureConditions) {\n try {\n const conditionResults = await evaluator.evaluateConditions(\n checkId,\n checkSchema,\n checkGroup,\n result,\n globalFailureConditions,\n checkFailureConditions,\n outputsRecord\n );\n\n // Check for triggered conditions\n for (const condResult of conditionResults) {\n if (condResult.failed) {\n logger.warn(\n `[Routing] Failure condition '${condResult.conditionName}' triggered for ${checkId}: ${condResult.expression}`\n );\n\n // Add issue to result\n const failIssue: ReviewIssue = {\n file: 'system',\n line: 0,\n ruleId: `${checkId}_${condResult.conditionName}`,\n message: condResult.message || `Failure condition met: ${condResult.expression}`,\n severity: condResult.severity || 'error',\n category: 'logic',\n };\n\n result.issues = [...(result.issues || []), failIssue];\n anyFailed = true;\n\n // Check if this condition requires halting execution\n if (condResult.haltExecution) {\n shouldHalt = true;\n haltMessage =\n condResult.message ||\n `Execution halted: condition '${condResult.conditionName}' triggered`;\n logger.error(\n `[Routing] HALT EXECUTION triggered by '${condResult.conditionName}' for ${checkId}`\n );\n }\n }\n }\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n logger.error(`[Routing] Error evaluating failure_conditions: ${msg}`);\n }\n }\n\n return { failed: anyFailed, haltExecution: shouldHalt, haltMessage };\n}\n\n/**\n * Check if routing loop budget is exceeded\n */\nexport function checkLoopBudget(\n context: EngineContext,\n state: RunState,\n origin: 'on_success' | 'on_fail' | 'on_finish',\n action: 'run' | 'goto'\n): boolean {\n const maxLoops = context.config.routing?.max_loops ?? DEFAULT_MAX_LOOPS;\n\n if (state.routingLoopCount >= maxLoops) {\n const msg = `Routing loop budget exceeded (max_loops=${maxLoops}) during ${origin} ${action}`;\n logger.error(`[Routing] ${msg}`);\n return true; // Budget exceeded\n }\n\n return false; // Budget OK\n}\n\n/**\n * Process on_success routing\n */\nasync function processOnSuccess(\n checkId: string,\n scope: Array<{ check: string; index: number }>,\n result: ReviewSummary,\n checkConfig: CheckConfig,\n context: EngineContext,\n state: RunState,\n emitEvent: (event: EngineEvent) => void\n): Promise<void> {\n const onSuccess = checkConfig.on_success;\n\n if (!onSuccess) {\n return; // No on_success configuration\n }\n\n if (context.debug) {\n logger.info(`[Routing] Processing on_success for ${checkId}`);\n }\n\n // Process on_success.run\n if (onSuccess.run && onSuccess.run.length > 0) {\n // Detect forEach context based on the actual result (aggregated map execution)\n const resForEachItems: any[] | undefined =\n (result && (result as any).forEachItems) || undefined;\n const hasForEachItems = Array.isArray(resForEachItems) && resForEachItems.length > 0;\n\n for (const targetCheck of onSuccess.run) {\n // Check loop budget before scheduling\n if (checkLoopBudget(context, state, 'on_success', 'run')) {\n // Add error issue to result\n const errorIssue: ReviewIssue = {\n file: 'system',\n line: 0,\n ruleId: `${checkId}/routing/loop_budget_exceeded`,\n message: `Routing loop budget exceeded (max_loops=${context.config.routing?.max_loops ?? DEFAULT_MAX_LOOPS}) during on_success run`,\n severity: 'error',\n category: 'logic',\n };\n result.issues = [...(result.issues || []), errorIssue];\n return; // Stop processing\n }\n\n // Handle fanout: check if target has fanout configuration\n const targetConfig = context.config.checks?.[targetCheck];\n const fanoutMode = targetConfig?.fanout || 'reduce'; // default to reduce\n\n if (context.debug) {\n logger.info(\n `[Routing] on_success.run: scheduling ${targetCheck} with fanout=${fanoutMode}, hasForEachItems=${hasForEachItems}`\n );\n }\n\n // If current check has forEach items and target is map fanout, emit one event per item\n if (fanoutMode === 'map' && hasForEachItems) {\n // Map fanout: emit one ForwardRunRequested per forEach item\n for (let itemIndex = 0; itemIndex < resForEachItems!.length; itemIndex++) {\n // Increment loop count for each item\n state.routingLoopCount++;\n\n const itemScope: Array<{ check: string; index: number }> = [\n { check: checkId, index: itemIndex },\n ];\n\n recordRoutingEvent({\n checkId,\n trigger: 'on_success',\n action: 'run',\n target: targetCheck,\n source: 'run',\n scope: itemScope,\n });\n emitEvent({\n type: 'ForwardRunRequested',\n target: targetCheck,\n scope: itemScope,\n origin: 'run',\n });\n }\n } else {\n // Reduce fanout (or no forEach context): emit with empty scope once\n // Increment loop count\n state.routingLoopCount++;\n\n recordRoutingEvent({\n checkId,\n trigger: 'on_success',\n action: 'run',\n target: targetCheck,\n source: 'run',\n scope,\n });\n emitEvent({\n type: 'ForwardRunRequested',\n target: targetCheck,\n scope,\n origin: 'run',\n });\n }\n }\n }\n\n // Process on_success.run_js\n if (onSuccess.run_js) {\n const dynamicTargets = await evaluateRunJs(\n onSuccess.run_js,\n checkId,\n checkConfig,\n result,\n context,\n state\n );\n\n for (const targetCheck of dynamicTargets) {\n // Check loop budget before scheduling\n if (checkLoopBudget(context, state, 'on_success', 'run')) {\n const errorIssue: ReviewIssue = {\n file: 'system',\n line: 0,\n ruleId: `${checkId}/routing/loop_budget_exceeded`,\n message: `Routing loop budget exceeded (max_loops=${context.config.routing?.max_loops ?? 10}) during on_success run`,\n severity: 'error',\n category: 'logic',\n };\n result.issues = [...(result.issues || []), errorIssue];\n return;\n }\n\n if (context.debug) {\n logger.info(`[Routing] on_success.run_js: scheduling ${targetCheck}`);\n }\n\n // Increment loop count\n state.routingLoopCount++;\n\n recordRoutingEvent({\n checkId,\n trigger: 'on_success',\n action: 'run',\n target: targetCheck,\n source: 'run_js',\n scope,\n });\n emitEvent({\n type: 'ForwardRunRequested',\n target: targetCheck,\n scope,\n origin: 'run_js',\n });\n }\n }\n\n // Declarative transitions for on_success (override goto/goto_js when present)\n const successTransTarget = await evaluateTransitions(\n onSuccess.transitions,\n checkId,\n checkConfig,\n result,\n context,\n state\n );\n if (successTransTarget !== undefined) {\n if (successTransTarget) {\n if (checkLoopBudget(context, state, 'on_success', 'goto')) {\n const errorIssue: ReviewIssue = {\n file: 'system',\n line: 0,\n ruleId: `${checkId}/routing/loop_budget_exceeded`,\n message: `Routing loop budget exceeded (max_loops=${context.config.routing?.max_loops ?? DEFAULT_MAX_LOOPS}) during on_success goto`,\n severity: 'error',\n category: 'logic',\n };\n result.issues = [...(result.issues || []), errorIssue];\n return;\n }\n state.routingLoopCount++;\n recordRoutingEvent({\n checkId,\n trigger: 'on_success',\n action: 'goto',\n target: successTransTarget.to,\n source: 'transitions',\n scope,\n gotoEvent: successTransTarget.goto_event,\n });\n emitEvent({\n type: 'ForwardRunRequested',\n target: successTransTarget.to,\n scope,\n origin: 'goto_js',\n gotoEvent: successTransTarget.goto_event,\n });\n state.flags.forwardRunRequested = true;\n }\n return;\n }\n\n // Process on_success.goto / goto_js\n const gotoTarget = await evaluateGoto(\n onSuccess.goto_js,\n onSuccess.goto,\n checkId,\n checkConfig,\n result,\n context,\n state\n );\n\n if (gotoTarget) {\n // Check loop budget before scheduling goto\n if (checkLoopBudget(context, state, 'on_success', 'goto')) {\n const errorIssue: ReviewIssue = {\n file: 'system',\n line: 0,\n ruleId: `${checkId}/routing/loop_budget_exceeded`,\n message: `Routing loop budget exceeded (max_loops=${context.config.routing?.max_loops ?? 10}) during on_success goto`,\n severity: 'error',\n category: 'logic',\n };\n result.issues = [...(result.issues || []), errorIssue];\n return;\n }\n\n if (context.debug) {\n logger.info(`[Routing] on_success.goto: ${gotoTarget}`);\n }\n\n // Increment loop count\n state.routingLoopCount++;\n\n recordRoutingEvent({\n checkId,\n trigger: 'on_success',\n action: 'goto',\n target: gotoTarget,\n source: onSuccess.goto_js ? 'goto_js' : 'goto',\n scope,\n gotoEvent: onSuccess.goto_event,\n });\n // Enqueue forward run event with optional event override\n emitEvent({\n type: 'ForwardRunRequested',\n target: gotoTarget,\n gotoEvent: onSuccess.goto_event,\n scope,\n origin: 'goto_js',\n });\n\n // Mark that we've seen a forward run\n state.flags.forwardRunRequested = true;\n }\n}\n\n/**\n * Process on_fail routing\n */\nasync function processOnFail(\n checkId: string,\n scope: Array<{ check: string; index: number }>,\n result: ReviewSummary,\n checkConfig: CheckConfig,\n context: EngineContext,\n state: RunState,\n emitEvent: (event: EngineEvent) => void\n): Promise<void> {\n // Merge defaults with check-specific on_fail\n const defaults = context.config.routing?.defaults?.on_fail || {};\n const onFail: OnFailConfig | undefined = checkConfig.on_fail\n ? { ...defaults, ...checkConfig.on_fail }\n : undefined;\n\n if (!onFail) {\n return; // No on_fail configuration\n }\n\n if (context.debug) {\n logger.info(`[Routing] Processing on_fail for ${checkId}`);\n }\n\n // Process on_fail.run\n if (onFail.run && onFail.run.length > 0) {\n // Detect forEach context based on the actual aggregated result\n const resForEachItems: any[] | undefined =\n (result && (result as any).forEachItems) || undefined;\n const hasForEachItems = Array.isArray(resForEachItems) && resForEachItems.length > 0;\n\n for (const targetCheck of onFail.run) {\n // Check loop budget before scheduling\n if (checkLoopBudget(context, state, 'on_fail', 'run')) {\n const errorIssue: ReviewIssue = {\n file: 'system',\n line: 0,\n ruleId: `${checkId}/routing/loop_budget_exceeded`,\n message: `Routing loop budget exceeded (max_loops=${context.config.routing?.max_loops ?? 10}) during on_fail run`,\n severity: 'error',\n category: 'logic',\n };\n result.issues = [...(result.issues || []), errorIssue];\n return;\n }\n\n // Handle fanout: check if target has fanout configuration\n const targetConfig = context.config.checks?.[targetCheck];\n const fanoutMode = targetConfig?.fanout || 'reduce'; // default to reduce\n\n if (context.debug) {\n logger.info(\n `[Routing] on_fail.run: scheduling ${targetCheck} with fanout=${fanoutMode}, hasForEachItems=${hasForEachItems}`\n );\n }\n\n // If current check ran in forEach context, schedule remediation per item\n if (hasForEachItems) {\n for (let itemIndex = 0; itemIndex < resForEachItems!.length; itemIndex++) {\n const itemOut = resForEachItems![itemIndex] as any;\n // Only remediate failed iterations if __failed is present; otherwise run for all\n if (\n itemOut &&\n typeof itemOut === 'object' &&\n itemOut.__failed !== true &&\n fanoutMode !== 'map'\n ) {\n // For reduce targets, skip successful iterations to avoid redundant runs\n continue;\n }\n\n state.routingLoopCount++;\n const itemScope: Array<{ check: string; index: number }> = [\n { check: checkId, index: itemIndex },\n ];\n recordRoutingEvent({\n checkId,\n trigger: 'on_fail',\n action: 'run',\n target: targetCheck,\n source: 'run',\n scope: itemScope,\n });\n emitEvent({\n type: 'ForwardRunRequested',\n target: targetCheck,\n scope: itemScope,\n origin: 'run',\n sourceCheck: checkId, // The failed check that triggered on_fail.run\n });\n }\n } else {\n // No forEach context: preserve current scope (if any)\n state.routingLoopCount++;\n recordRoutingEvent({\n checkId,\n trigger: 'on_fail',\n action: 'run',\n target: targetCheck,\n source: 'run',\n scope,\n });\n emitEvent({\n type: 'ForwardRunRequested',\n target: targetCheck,\n scope,\n origin: 'run',\n sourceCheck: checkId, // The failed check that triggered on_fail.run\n });\n }\n }\n }\n\n // Process on_fail.run_js\n if (onFail.run_js) {\n const dynamicTargets = await evaluateRunJs(\n onFail.run_js,\n checkId,\n checkConfig,\n result,\n context,\n state\n );\n\n for (const targetCheck of dynamicTargets) {\n // Check loop budget before scheduling\n if (checkLoopBudget(context, state, 'on_fail', 'run')) {\n const errorIssue: ReviewIssue = {\n file: 'system',\n line: 0,\n ruleId: `${checkId}/routing/loop_budget_exceeded`,\n message: `Routing loop budget exceeded (max_loops=${context.config.routing?.max_loops ?? 10}) during on_fail run`,\n severity: 'error',\n category: 'logic',\n };\n result.issues = [...(result.issues || []), errorIssue];\n return;\n }\n\n if (context.debug) {\n logger.info(`[Routing] on_fail.run_js: scheduling ${targetCheck}`);\n }\n\n // Increment loop count\n state.routingLoopCount++;\n\n recordRoutingEvent({\n checkId,\n trigger: 'on_fail',\n action: 'run',\n target: targetCheck,\n source: 'run_js',\n scope,\n });\n emitEvent({\n type: 'ForwardRunRequested',\n target: targetCheck,\n scope,\n origin: 'run_js',\n sourceCheck: checkId, // The failed check that triggered on_fail.run_js\n });\n }\n }\n\n // Process on_fail.retry (schedule retry of the current check)\n if (onFail.retry && typeof onFail.retry.max === 'number' && onFail.retry.max > 0) {\n // Criticality mapping: for 'external' and 'internal', avoid automatic\n // retries for logical failures (fail_if/guarantee violations).\n const crit = getCriticality(context, checkId);\n const failureKind = classifyFailure(result);\n if ((crit === 'external' || crit === 'internal') && failureKind === 'logical') {\n if (context.debug) {\n logger.info(\n `[Routing] on_fail.retry suppressed for ${checkId} (criticality=${crit}, failure=logical)`\n );\n }\n // Skip retry scheduling\n } else {\n const max = Math.max(0, onFail.retry.max || 0);\n // Initialize retry attempt map on state\n if (!(state as any).retryAttempts) (state as any).retryAttempts = new Map<string, number>();\n const attemptsMap: Map<string, number> = (state as any).retryAttempts;\n\n const makeKey = (sc: Array<{ check: string; index: number }> | undefined) => {\n const keyScope = sc && sc.length > 0 ? JSON.stringify(sc) : 'root';\n return `${checkId}::${keyScope}`;\n };\n\n const scheduleRetryForScope = (sc: Array<{ check: string; index: number }> | undefined) => {\n const key = makeKey(sc);\n const used = attemptsMap.get(key) || 0;\n if (used >= max) return; // budget exhausted\n attemptsMap.set(key, used + 1);\n\n // Increment loop count and schedule forward run for the same check\n state.routingLoopCount++;\n recordRoutingEvent({\n checkId,\n trigger: 'on_fail',\n action: 'retry',\n source: 'retry',\n scope: sc || [],\n });\n emitEvent({\n type: 'ForwardRunRequested',\n target: checkId,\n scope: sc || [],\n origin: 'run',\n });\n };\n\n const resForEachItems: any[] | undefined =\n (result && (result as any).forEachItems) || undefined;\n const hasForEachItems = Array.isArray(resForEachItems) && resForEachItems.length > 0;\n\n if (hasForEachItems) {\n for (let i = 0; i < resForEachItems!.length; i++) {\n const itemOut = resForEachItems![i] as any;\n // Only retry failed iterations (marked by __failed)\n if (itemOut && typeof itemOut === 'object' && itemOut.__failed === true) {\n const sc: Array<{ check: string; index: number }> = [{ check: checkId, index: i }];\n scheduleRetryForScope(sc);\n }\n }\n } else {\n scheduleRetryForScope(scope);\n }\n\n // Note: backoff.delay_ms and mode are intentionally not awaited here; the\n // state-machine processes retries as subsequent waves. If needed later, we\n // can insert a timed wait in the orchestrator layer.\n }\n }\n\n // Declarative transitions for on_fail (override goto/goto_js when present)\n const failTransTarget = await evaluateTransitions(\n onFail.transitions,\n checkId,\n checkConfig,\n result,\n context,\n state\n );\n if (failTransTarget !== undefined) {\n if (failTransTarget) {\n if (checkLoopBudget(context, state, 'on_fail', 'goto')) {\n const errorIssue: ReviewIssue = {\n file: 'system',\n line: 0,\n ruleId: `${checkId}/routing/loop_budget_exceeded`,\n message: `Routing loop budget exceeded (max_loops=${context.config.routing?.max_loops ?? DEFAULT_MAX_LOOPS}) during on_fail goto`,\n severity: 'error',\n category: 'logic',\n };\n result.issues = [...(result.issues || []), errorIssue];\n return;\n }\n state.routingLoopCount++;\n recordRoutingEvent({\n checkId,\n trigger: 'on_fail',\n action: 'goto',\n target: failTransTarget.to,\n source: 'transitions',\n scope,\n gotoEvent: failTransTarget.goto_event,\n });\n emitEvent({\n type: 'ForwardRunRequested',\n target: failTransTarget.to,\n scope,\n origin: 'goto_js',\n gotoEvent: failTransTarget.goto_event,\n });\n state.flags.forwardRunRequested = true;\n }\n return;\n }\n\n // Process on_fail.goto / goto_js\n const gotoTarget = await evaluateGoto(\n onFail.goto_js,\n onFail.goto,\n checkId,\n checkConfig,\n result,\n context,\n state\n );\n\n if (gotoTarget) {\n // Check loop budget before scheduling goto\n if (checkLoopBudget(context, state, 'on_fail', 'goto')) {\n const errorIssue: ReviewIssue = {\n file: 'system',\n line: 0,\n ruleId: `${checkId}/routing/loop_budget_exceeded`,\n message: `Routing loop budget exceeded (max_loops=${context.config.routing?.max_loops ?? 10}) during on_fail goto`,\n severity: 'error',\n category: 'logic',\n };\n result.issues = [...(result.issues || []), errorIssue];\n return;\n }\n\n if (context.debug) {\n logger.info(`[Routing] on_fail.goto: ${gotoTarget}`);\n }\n\n // Increment loop count\n state.routingLoopCount++;\n\n recordRoutingEvent({\n checkId,\n trigger: 'on_fail',\n action: 'goto',\n target: gotoTarget,\n source: onFail.goto_js ? 'goto_js' : 'goto',\n scope,\n gotoEvent: onFail.goto_event,\n });\n // Enqueue forward run event with optional event override\n emitEvent({\n type: 'ForwardRunRequested',\n target: gotoTarget,\n gotoEvent: onFail.goto_event,\n scope,\n origin: 'goto_js',\n });\n\n // Mark that we've seen a forward run\n state.flags.forwardRunRequested = true;\n }\n}\n\n/**\n * Evaluate run_js expression to get dynamic check targets\n */\nasync function evaluateRunJs(\n runJs: string,\n checkId: string,\n checkConfig: CheckConfig,\n result: ReviewSummary,\n context: EngineContext,\n _state: RunState\n): Promise<string[]> {\n try {\n const sandbox = createSecureSandbox();\n const historyLimit = getHistoryLimit();\n\n // Build outputs record and outputs_history\n const snapshotId = context.journal.beginSnapshot();\n const contextView = new (require('../../snapshot-store').ContextView)(\n context.journal,\n context.sessionId,\n snapshotId,\n [],\n context.event\n );\n\n const outputsRecord: Record<string, any> = {};\n const outputsHistory: Record<string, any[]> = {};\n\n // Get all visible journal entries to build complete history\n const allEntries = context.journal.readVisible(context.sessionId, snapshotId, context.event);\n const uniqueCheckIds = new Set(allEntries.map(e => e.checkId));\n\n for (const checkIdFromJournal of uniqueCheckIds) {\n try {\n // Get current output for this check\n const journalResult = contextView.get(checkIdFromJournal);\n if (journalResult) {\n // Prefer the output field if present, otherwise use the full result\n outputsRecord[checkIdFromJournal] =\n journalResult.output !== undefined ? journalResult.output : journalResult;\n }\n } catch {\n outputsRecord[checkIdFromJournal] = { issues: [] };\n }\n\n // Build history for this check\n try {\n const history = contextView.getHistory(checkIdFromJournal);\n if (history && history.length > 0) {\n const trimmed =\n historyLimit && history.length > historyLimit\n ? history.slice(history.length - historyLimit)\n : history;\n // Extract outputs from history (prefer output field if available)\n outputsHistory[checkIdFromJournal] = trimmed.map((r: any) =>\n r.output !== undefined ? r.output : r\n );\n }\n } catch {\n // Ignore history errors\n }\n }\n\n // Add history as a property on outputs object for convenient access\n outputsRecord.history = outputsHistory;\n\n // Compute minimal forEach metadata for run_js parity\n let forEachMeta: any = undefined;\n try {\n const hist = outputsHistory[checkId] || [];\n const lastArr = (hist as any[])\n .slice()\n .reverse()\n .find((x: any) => Array.isArray(x));\n if (checkConfig.forEach === true && Array.isArray(lastArr)) {\n forEachMeta = {\n is_parent: true,\n last_wave_size: lastArr.length,\n last_items: lastArr,\n };\n }\n } catch {}\n\n const scopeObj: any = {\n step: {\n id: checkId,\n tags: checkConfig.tags || [],\n group: checkConfig.group,\n },\n outputs: outputsRecord,\n outputs_history: outputsHistory,\n output: (result as any)?.output,\n memory: createMemoryHelpers(),\n event: {\n name: context.event || 'manual',\n },\n forEach: forEachMeta,\n };\n\n const code = `\n const step = scope.step;\n const outputs = scope.outputs;\n const outputs_history = scope.outputs_history;\n const output = scope.output;\n const memory = scope.memory;\n const event = scope.event;\n const forEach = scope.forEach;\n const log = (...args) => console.log('🔍 Debug:', ...args);\n const __fn = () => {\n ${runJs}\n };\n const __res = __fn();\n return Array.isArray(__res) ? __res.filter(x => typeof x === 'string' && x) : [];\n `;\n\n try {\n const evalResult = compileAndRun<string[]>(\n sandbox,\n code,\n { scope: scopeObj },\n { injectLog: false, wrapFunction: false }\n );\n return Array.isArray(evalResult) ? evalResult.filter(Boolean) : [];\n } catch (_e) {\n // Fallback to VM for modern syntax used inside run_js\n try {\n const vm = require('node:vm');\n const context = vm.createContext({ scope: scopeObj, console: { log: () => {} } });\n const src = `(() => { ${runJs}\\n })()`;\n const val = new vm.Script(src).runInContext(context, { timeout: 100 });\n return Array.isArray(val) ? val.filter((x: any) => typeof x === 'string' && x) : [];\n } catch (_vmErr) {\n return [];\n }\n }\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n logger.error(`[Routing] Error evaluating run_js: ${msg}`);\n return [];\n }\n}\n\n/**\n * Evaluate goto_js or return static goto target\n */\nexport async function evaluateGoto(\n gotoJs: string | undefined,\n gotoStatic: string | undefined,\n checkId: string,\n checkConfig: CheckConfig,\n result: ReviewSummary,\n context: EngineContext,\n _state: RunState\n): Promise<string | null> {\n // Evaluate goto_js first\n if (gotoJs) {\n try {\n const sandbox = createSecureSandbox();\n const historyLimit = getHistoryLimit();\n\n // Build outputs record and outputs_history from the full session snapshot.\n // Do not filter by event here — on_finish (especially forEach post-children) may\n // need to see results committed under different event triggers within the same run.\n const snapshotId = context.journal.beginSnapshot();\n const contextView = new (require('../../snapshot-store').ContextView)(\n context.journal,\n context.sessionId,\n snapshotId,\n [],\n undefined\n );\n\n const outputsRecord: Record<string, any> = {};\n const outputsHistory: Record<string, any[]> = {};\n\n // Get all visible journal entries to build complete history\n const allEntries = context.journal.readVisible(context.sessionId, snapshotId, undefined);\n const uniqueCheckIds = new Set(allEntries.map(e => e.checkId));\n\n for (const checkIdFromJournal of uniqueCheckIds) {\n try {\n // Get current output for this check\n const journalResult = contextView.get(checkIdFromJournal);\n if (journalResult) {\n // Prefer the output field if present, otherwise use the full result\n outputsRecord[checkIdFromJournal] =\n journalResult.output !== undefined ? journalResult.output : journalResult;\n }\n } catch {\n outputsRecord[checkIdFromJournal] = { issues: [] };\n }\n\n // Build history for this check\n try {\n const history = contextView.getHistory(checkIdFromJournal);\n if (history && history.length > 0) {\n const trimmed =\n historyLimit && history.length > historyLimit\n ? history.slice(history.length - historyLimit)\n : history;\n // Extract outputs from history (prefer output field if available)\n outputsHistory[checkIdFromJournal] = trimmed.map((r: any) =>\n r.output !== undefined ? r.output : r\n );\n }\n } catch {\n // Ignore history errors\n }\n }\n\n // Add history as a property on outputs object for convenient access\n outputsRecord.history = outputsHistory;\n\n // Compute minimal forEach metadata for convenience in goto_js\n // - last_wave_size: number of items in the latest root-scope array output\n // - last_items: the latest array output itself (if available)\n let forEachMeta: any = undefined;\n try {\n const hist = outputsHistory[checkId] || [];\n const lastArr = (hist as any[])\n .slice()\n .reverse()\n .find((x: any) => Array.isArray(x));\n if (checkConfig.forEach === true && Array.isArray(lastArr)) {\n forEachMeta = {\n is_parent: true,\n last_wave_size: lastArr.length,\n last_items: lastArr,\n };\n }\n } catch {}\n\n const scopeObj: any = {\n step: {\n id: checkId,\n tags: checkConfig.tags || [],\n group: checkConfig.group,\n },\n outputs: outputsRecord,\n outputs_history: outputsHistory,\n output: (result as any)?.output,\n memory: createMemoryHelpers(),\n event: {\n name: context.event || 'manual',\n },\n forEach: forEachMeta,\n };\n\n // Debug: Log outputs_history\n if (context.debug) {\n logger.info(\n `[Routing] evaluateGoto: checkId=${checkId}, outputs_history keys=${Object.keys(outputsHistory).join(',')}`\n );\n for (const [key, values] of Object.entries(outputsHistory)) {\n logger.info(`[Routing] ${key}: ${values.length} items`);\n }\n }\n\n const code = `\n const step = scope.step;\n const outputs = scope.outputs;\n const outputs_history = scope.outputs_history;\n const output = scope.output;\n const memory = scope.memory;\n const event = scope.event;\n const forEach = scope.forEach;\n const log = (...args) => console.log('🔍 Debug:', ...args);\n ${gotoJs}\n `;\n\n try {\n const evalResult = compileAndRun<string | null>(\n sandbox,\n code,\n { scope: scopeObj },\n { injectLog: false, wrapFunction: true }\n );\n\n if (context.debug) {\n logger.info(`[Routing] evaluateGoto result: ${evalResult}`);\n }\n\n if (typeof evalResult === 'string' && evalResult) {\n return evalResult;\n }\n } catch (_e) {\n // Fallback to VM for modern syntax in goto_js\n try {\n const vm = require('node:vm');\n const contextObj = {\n step: scopeObj.step,\n outputs: scopeObj.outputs,\n outputs_history: scopeObj.outputs_history,\n output: scopeObj.output,\n memory: scopeObj.memory,\n event: scopeObj.event,\n forEach: (scopeObj as any).forEach,\n };\n const vmctx = vm.createContext(contextObj);\n const src = `(() => { ${gotoJs}\\n })()`;\n const res = new vm.Script(src).runInContext(vmctx, { timeout: 100 });\n if (typeof res === 'string' && res) return res;\n } catch (_vmErr) {\n // ignore; fall through to static goto\n }\n }\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n logger.error(`[Routing] Error evaluating goto_js: ${msg}`);\n\n // Fall back to static goto if available\n if (gotoStatic) {\n logger.info(`[Routing] Falling back to static goto: ${gotoStatic}`);\n return gotoStatic;\n }\n }\n }\n\n // Return static goto\n return gotoStatic || null;\n}\n// Default values (used only when config is absent)\nconst DEFAULT_MAX_LOOPS = 10;\n\n/**\n * Evaluate declarative transitions. Returns:\n * - { to, goto_event } when a rule matches,\n * - null (explicit) when a rule matches with to=null,\n * - undefined when no rule matched or transitions is empty.\n */\nexport async function evaluateTransitions(\n transitions: TransitionRule[] | undefined,\n checkId: string,\n checkConfig: CheckConfig,\n result: ReviewSummary,\n context: EngineContext,\n _state: RunState\n): Promise<\n { to: string; goto_event?: import('../../types/config').EventTrigger } | null | undefined\n> {\n if (!transitions || transitions.length === 0) return undefined;\n try {\n const sandbox = createSecureSandbox();\n const historyLimit = getHistoryLimit();\n\n // Build outputs record and outputs_history from the full session snapshot\n const snapshotId = context.journal.beginSnapshot();\n const ContextView = (require('../../snapshot-store') as any).ContextView;\n const view = new ContextView(context.journal, context.sessionId, snapshotId, [], undefined);\n\n const outputsRecord: Record<string, any> = {};\n const outputsHistory: Record<string, any[]> = {};\n const allEntries = context.journal.readVisible(context.sessionId, snapshotId, undefined);\n const uniqueCheckIds = new Set(allEntries.map((e: any) => e.checkId));\n for (const cid of uniqueCheckIds) {\n try {\n const jr = view.get(cid);\n if (jr) outputsRecord[cid] = jr.output !== undefined ? jr.output : jr;\n } catch {}\n try {\n const hist = view.getHistory(cid);\n if (hist && hist.length > 0) {\n const trimmed =\n historyLimit && hist.length > historyLimit\n ? hist.slice(hist.length - historyLimit)\n : hist;\n outputsHistory[cid] = trimmed.map((r: any) => (r.output !== undefined ? r.output : r));\n }\n } catch {}\n }\n outputsRecord.history = outputsHistory;\n\n const scopeObj: any = {\n step: { id: checkId, tags: checkConfig.tags || [], group: checkConfig.group },\n outputs: outputsRecord,\n outputs_history: outputsHistory,\n output: (result as any)?.output,\n memory: createMemoryHelpers(),\n event: { name: context.event || 'manual' },\n };\n\n for (const rule of transitions) {\n const helpers = `\n const any = (arr, pred) => Array.isArray(arr) && arr.some(x => pred(x));\n const all = (arr, pred) => Array.isArray(arr) && arr.every(x => pred(x));\n const none = (arr, pred) => Array.isArray(arr) && !arr.some(x => pred(x));\n const count = (arr, pred) => Array.isArray(arr) ? arr.filter(x => pred(x)).length : 0;\n `;\n // Mirror the variable exposure pattern used in goto_js/run_js so that\n // `when:` expressions can reference `outputs`, `outputs_history`, `event`, etc.\n const code = `\n ${helpers}\n const step = scope.step;\n const outputs = scope.outputs;\n const outputs_history = scope.outputs_history;\n const output = scope.output;\n const memory = scope.memory;\n const event = scope.event;\n const __eval = () => { return (${rule.when}); };\n return __eval();\n `;\n let matched: boolean | undefined;\n try {\n matched = compileAndRun<boolean>(\n sandbox,\n code,\n { scope: scopeObj },\n { injectLog: false, wrapFunction: false }\n );\n } catch (_e) {\n // Fallback: Node VM for modern syntax like optional chaining and ??\n try {\n const vm = require('node:vm');\n const helpersFns = {\n any: (arr: any[], pred: (x: any) => boolean) => Array.isArray(arr) && arr.some(pred),\n all: (arr: any[], pred: (x: any) => boolean) => Array.isArray(arr) && arr.every(pred),\n none: (arr: any[], pred: (x: any) => boolean) => Array.isArray(arr) && !arr.some(pred),\n count: (arr: any[], pred: (x: any) => boolean) =>\n Array.isArray(arr) ? arr.filter(pred).length : 0,\n };\n const context = vm.createContext({\n step: scopeObj.step,\n outputs: scopeObj.outputs,\n outputs_history: scopeObj.outputs_history,\n output: scopeObj.output,\n memory: scopeObj.memory,\n event: scopeObj.event,\n ...helpersFns,\n });\n const res = new vm.Script(`(${rule.when})`).runInContext(context, { timeout: 50 });\n matched = !!res;\n } catch (_vmErr) {\n matched = false;\n }\n }\n if (matched) {\n if (rule.to === null) return null;\n if (typeof rule.to === 'string' && rule.to.length > 0) {\n return { to: rule.to, goto_event: (rule as any).goto_event };\n }\n return null;\n }\n }\n return undefined;\n } catch (err) {\n logger.error(\n `[Routing] Error evaluating transitions: ${err instanceof Error ? err.message : String(err)}`\n );\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAmBa,kBAwCA;AA3Db;AAAA;AAAA;AAmBO,IAAM,mBAAN,MAAuB;AAAA,MACpB,SAAS;AAAA,MACT,UAA0B,CAAC;AAAA,MAEnC,gBAAwB;AACtB,eAAO,KAAK;AAAA,MACd;AAAA,MAEA,YAAY,OAMK;AACf,cAAM,YAA0B;AAAA,UAC9B,WAAW,MAAM;AAAA,UACjB,OAAO,MAAM;AAAA,UACb,SAAS,MAAM;AAAA,UACf,QAAQ,MAAM;AAAA,UACd,OAAO,MAAM;AAAA,UACb,UAAU,EAAE,KAAK;AAAA,QACnB;AACA,aAAK,QAAQ,KAAK,SAAS;AAC3B,eAAO;AAAA,MACT;AAAA,MAEA,YAAY,WAAmB,WAAmB,OAAsC;AACtF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