techtools
Головна / proto / flow-old / server / validation.ts

validation.ts

TypeScript · 73 рядків

1// Перевірка workflow для редактора (live, збереження чернетки, публікація) — перенесено з index.js без змін логіки.
2// Нове (R-12.21): цикл — попередження (severity: 'warning'), а не помилка: публікацію не блокує; рушій зупинить
3// зациклений прохід лічильником і надішле повідомлення. Так само попередження — не з'єднаний вихід error в API_REQUEST.
4import { validateWorkflowDataFlow } from './data-flow.ts'
5import { validateStages } from '../shared/stages.ts'
6
7type Json = any
8export interface Issue { message: string; nodeId?: string; edgeId?: string; severity?: 'error' | 'warning' }
9
10export function validateWorkflow(workflow: Json, models: Json[], workflows: Json[]): { errors: string[]; issues: Issue[] } {
11  const issues: Issue[] = (workflow.edges || []).flatMap((edge) => {
12    const source = workflow.nodes?.find((node) => node.id === edge.source)
13    const target = workflow.nodes?.find((node) => node.id === edge.target)
14    const errors = []
15    if (!source) errors.push('source block not found')
16    else if (!source.outputs?.some((port) => port.id === edge.sourcePort)) errors.push('source port not found')
17    if (!target) errors.push('target block not found')
18    else if (!target.inputs?.some((port) => port.id === edge.targetPort)) errors.push('target port not found')
19    return errors.map((message) => ({ message: `Connector ${edge.id}: ${message}`, edgeId: edge.id }))
20  })
21
22  issues.push(...(workflow.nodes
23    ?.filter((node) => ['WAIT', 'NOTIFICATION', 'UPDATE_ENTITY'].includes(node.type))
24    .map((node) => ({ message: `${node.name}: ${node.type} block is no longer supported`, nodeId: node.id })) || []))
25
26  const tagged = structuredClone(workflow)
27  tagged.nodes ||= []
28  tagged.edges ||= []
29  const names = new Map(tagged.nodes.map((node) => [node.id, node.name]))
30  for (const node of tagged.nodes) node.name = `__FLOW_NODE_${node.id}__`
31  const allWorkflows = [...workflows.filter((item) => item.id !== workflow.id), tagged]
32
33  const taskedEdge = (text: string) => {
34    const found = text.match(/^Connector (\S+): (.*)$/s)
35    const edge = found && tagged.edges.find((item) => item.id === found[1])
36    return edge ? { edge, rest: found[2] } : null
37  }
38  for (const taggedMessage of validateWorkflowDataFlow(tagged, models, allWorkflows)) {
39    const match = taggedMessage.match(/^__FLOW_NODE_(.+?)__(:| .)/)
40    const cycle = taggedMessage.match(/^Cycle detected at node (.+)$/)
41    const nodeId = match?.[1] || cycle?.[1]
42    const connector = taskedEdge(taggedMessage)
43    if (connector) {
44      const edge = connector.edge
45      issues.push({ message: `Connector ${names.get(edge.source) ?? edge.source} → ${names.get(edge.target) ?? edge.target}: ${connector.rest}`, edgeId: edge.id })
46      continue
47    }
48    const message = cycle
49      ? `${names.get(nodeId) ?? nodeId}: loop in the graph — allowed; the engine stops a pass after the loop limit and sends a notification`
50      : match ? `${names.get(nodeId)}${taggedMessage.slice(match[0].length - match[2].length)}` : taggedMessage
51    issues.push({ message, ...(nodeId && names.has(nodeId) ? { nodeId } : {}), ...(cycle ? { severity: 'warning' as const } : {}) })
52  }
53
54  // P7 (R-23 §11): відмова сервісу без гілки error зупиняє прохід — це не помилка, але інженер має це бачити
55  const screens = workflow.nodes?.some((node) => node.type === 'SCREEN')
56  for (const node of workflow.nodes || []) {
57    if (node.type !== 'API_REQUEST' || !node.outputs?.some((port) => port.id === 'error')) continue
58    if ((workflow.edges || []).some((edge) => edge.source === node.id && edge.sourcePort === 'error')) continue
59    issues.push({
60      message: `${node.name}: error output is not connected — if the service fails, the pass stops${screens ? ' and the scanner gets the default error screen' : ''}`,
61      nodeId: node.id, severity: 'warning',
62    })
63  }
64
65  // етапи борду (R-30.12): область, модель контексту, TASK → етап
66  issues.push(...validateStages(workflow, models))
67
68  const unique = [...new Map(issues.map((issue) => [`${issue.nodeId || ''}|${issue.edgeId || ''}|${issue.message}`, issue])).values()]
69  return { errors: unique.map((issue) => issue.message), issues: unique }
70}
71
72export const blocking = (issues: Issue[]) => issues.filter((issue) => issue.severity !== 'warning')
73