bada-terminal / scripts /validate_workflow.py
VanyaJ's picture
Release BADA Terminal v2.1.0 (Enterprise Ontology, NVIDIA auto-ontology, Release Preflight)
d739b1b verified
Raw History Blame Contribute Delete
11.1 kB
#!/usr/bin/env python3
"""
BADA Terminal μ›Œν¬ν”Œλ‘œμš° 정적 무결성 Linter (scripts/validate_workflow.py)
κΈ°λŠ₯:
1. 둜컬 SQLite (~/.claude/knowledge.db) λ˜λŠ” JSON (~/.claude/knowledge.json) DBμ—μ„œ μ›Œν¬ν”Œλ‘œμš° λͺ©λ‘ λ‘œλ“œ.
2. 각 μ›Œν¬ν”Œλ‘œμš° λ‚΄ DAG의 정적 무결성 점검:
- 쀑볡/잘λͺ»λœ λ…Έλ“œ 속성 검증
- loopback: trueκ°€ μ•„λ‹Œ edges κΈ°μ€€ μˆœν™˜ μ°Έμ‘°(Circular Loop) κ²€μΆœ
- 병렬 λ…Έλ“œ(parallel) config 검증 (config.nodeIds ν•„μˆ˜, μ‹€μ œ λ…Έλ“œ 쑴재 μ—¬λΆ€)
- 루프 λ…Έλ“œ(loop) νƒ€κ²Ÿ λ…Έλ“œ 검증 (config.loopTargetNodeId ν•„μˆ˜ 및 쑴재 μ—¬λΆ€)
- μ—μ΄μ „νŠΈ λ…Έλ“œ(agent / pty_agent) agentProfileId 검증
- 쑰건 λ…Έλ“œ(condition) config.expression 쑴재 μ—¬λΆ€ 검사
3. κ·œμ•½ μœ„λ°˜ μ‹œ μ—λŸ¬ λ©”μ‹œμ§€μ™€ ν•¨κ»˜ exit 1을 λ°˜ν™˜.
"""
import os
import sys
import json
import sqlite3
from collections import defaultdict, deque
# ν—ˆμš©λœ λ…Έλ“œ νƒ€μž… λͺ©λ‘
VALID_NODE_TYPES = {
'input', 'validator', 'orchestrator', 'agent', 'pty_agent',
'reviewer', 'harness', 'parallel', 'loop', 'hitl',
'condition', 'switch', 'report', 'note', 'call_workflow'
}
# κΈ°λ³Έ λ‚΄μž₯ μ—μ΄μ „νŠΈ ν”„λ‘œν•„ ID λͺ©λ‘
BUILTIN_PROFILE_IDS = {
'default', 'token-optimizer', 'wiki-ontology', 'workflow-designer',
'omc-autopilot', 'omc-team', 'cell_gen'
}
def load_agent_profiles():
profiles_path = os.path.expanduser('~/.claude/agent-profiles.json')
profile_ids = set(BUILTIN_PROFILE_IDS)
if os.path.exists(profiles_path):
try:
with open(profiles_path, 'r', encoding='utf-8') as f:
data = json.load(f)
if 'profiles' in data:
profile_ids.update(data['profiles'].keys())
except Exception as e:
print(f"⚠️ Warning: Failed to load agent-profiles.json: {e}", file=sys.stderr)
return profile_ids
def load_workflows_from_db(db_path):
workflows = []
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# ν…Œμ΄λΈ” 쑴재 μ—¬λΆ€ 확인
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='workflows'")
if not cursor.fetchone():
conn.close()
return workflows
cursor.execute("SELECT id, name, graph_json FROM workflows")
rows = cursor.fetchall()
for row in rows:
workflows.append({
'id': row[0],
'name': row[1],
'graph_json': row[2]
})
conn.close()
except Exception as e:
print(f"⚠️ SQLite read failed for {db_path}: {e}", file=sys.stderr)
return workflows
def load_workflows_from_json(json_path):
workflows = []
try:
with open(json_path, 'r', encoding='utf-8') as f:
data = json.load(f)
if 'workflows' in data:
for wf in data['workflows']:
workflows.append({
'id': wf.get('id'),
'name': wf.get('name'),
'graph_json': wf.get('graph_json')
})
except Exception as e:
print(f"⚠️ JSON read failed for {json_path}: {e}", file=sys.stderr)
return workflows
def validate_workflow(wf, profile_ids):
wf_id = wf.get('id', 'Unknown ID')
wf_name = wf.get('name', 'Unknown Name')
graph_json = wf.get('graph_json', '{}')
wf_errors = []
wf_warnings = []
try:
graph = json.loads(graph_json) if isinstance(graph_json, str) else graph_json
except Exception as e:
return [f"graph_json νŒŒμ‹± μ‹€νŒ¨: {e}"], []
if not isinstance(graph, dict):
return [f"graph 데이터가 객체 ν˜•μ‹μ΄ μ•„λ‹˜"], []
nodes = graph.get('nodes', [])
edges = graph.get('edges', [])
if not isinstance(nodes, list):
return [f"'nodes'κ°€ 리슀트 ν˜•μ‹μ΄ μ•„λ‹˜"], []
if not isinstance(edges, list):
return [f"'edges'κ°€ 리슀트 ν˜•μ‹μ΄ μ•„λ‹˜"], []
node_map = {}
for node in nodes:
node_id = node.get('id')
if not node_id:
wf_errors.append("IDκ°€ λˆ„λ½λœ λ…Έλ“œκ°€ μ‘΄μž¬ν•©λ‹ˆλ‹€.")
continue
if node_id in node_map:
wf_errors.append(f"λ…Έλ“œ ID 쀑볡 감지: {node_id}")
node_map[node_id] = node
node_name = node.get('name', 'Unnamed')
node_type = node.get('type')
if not node_type:
wf_errors.append(f"λ…Έλ“œ '{node_name}' ({node_id}): type ν•„λ“œκ°€ λˆ„λ½λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
continue
if node_type not in VALID_NODE_TYPES:
wf_errors.append(f"λ…Έλ“œ '{node_name}' ({node_id}): μ•Œ 수 μ—†λŠ” λ…Έλ“œ νƒ€μž… '{node_type}'")
config = node.get('config', {})
if not isinstance(config, dict):
wf_errors.append(f"λ…Έλ“œ '{node_name}' ({node_id}): config ν•„λ“œκ°€ 객체 ν˜•μ‹μ΄ μ•„λ‹˜")
config = {}
# νƒ€μž…λ³„ μ„ΈλΆ€ κ·œμΉ™ 검증
if node_type in ('agent', 'pty_agent'):
profile_id = config.get('agentProfileId') or config.get('agentId')
if not profile_id:
wf_errors.append(f"μ—μ΄μ „νŠΈ λ…Έλ“œ '{node_name}' ({node_id}): agentProfileIdκ°€ config에 λˆ„λ½λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
elif profile_id not in profile_ids:
wf_warnings.append(f"μ—μ΄μ „νŠΈ λ…Έλ“œ '{node_name}' ({node_id}): μ •μ˜λ˜μ§€ μ•Šμ€ ν”„λ‘œν•„ ID '{profile_id}'λ₯Ό μ°Έμ‘°ν•˜κ³  μžˆμŠ΅λ‹ˆλ‹€.")
elif node_type == 'parallel':
child_ids = config.get('nodeIds', [])
if not isinstance(child_ids, list) or not child_ids:
wf_errors.append(f"병렬 λ…Έλ“œ '{node_name}' ({node_id}): config.nodeIdsκ°€ λΉ„μ–΄μžˆκ±°λ‚˜ μ˜¬λ°”λ₯Έ 리슀트 ν˜•μ‹μ΄ μ•„λ‹™λ‹ˆλ‹€.")
else:
for cid in child_ids:
if cid not in node_map:
wf_errors.append(f"병렬 λ…Έλ“œ '{node_name}' ({node_id}): μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” μžμ‹ λ…Έλ“œ ID '{cid}'λ₯Ό μ°Έμ‘°ν•˜κ³  μžˆμŠ΅λ‹ˆλ‹€.")
elif node_type == 'loop':
loop_target = config.get('loopTargetNodeId')
if loop_target and loop_target not in node_map:
wf_errors.append(f"루프 게이트 λ…Έλ“œ '{node_name}' ({node_id}): μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” 루프 λŒ€μƒ λ…Έλ“œ ID '{loop_target}'을 μ°Έμ‘°ν•˜κ³  μžˆμŠ΅λ‹ˆλ‹€.")
elif node_type == 'condition':
expr = config.get('expression')
if not expr:
wf_errors.append(f"쑰건 λ…Έλ“œ '{node_name}' ({node_id}): config.expression 쑰건식이 λˆ„λ½λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
# DAG μˆœν™˜ μ°Έμ‘° 검증
# loopback: true인 엣지듀을 μ œμ™Έν•œ 정적 DAG ꡬ성
adj_list = defaultdict(list)
in_degree = {nid: 0 for nid in node_map}
for edge in edges:
source = edge.get('source')
target = edge.get('target')
if not source or not target:
wf_errors.append("source λ˜λŠ” target이 λˆ„λ½λœ μ—£μ§€κ°€ μ‘΄μž¬ν•©λ‹ˆλ‹€.")
continue
if source not in node_map or target not in node_map:
wf_errors.append(f"μ—£μ§€ 였λ₯˜: μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” λ…Έλ“œλ₯Ό μ°Έμ‘°ν•©λ‹ˆλ‹€. ({source} -> {target})")
continue
# loopback μ—¬λΆ€ νŒλ‹¨ (workflow-manager.js와 둜직 싱크)
is_loopback = (
edge.get('loopback') == True or
edge.get('loopback') == 'true' or
edge.get('type') == 'loopback' or
edge.get('label') == 'loopback'
)
if is_loopback:
continue
adj_list[source].append(target)
in_degree[target] += 1
# Kahn's Algorithm
queue = deque([nid for nid in node_map if in_degree[nid] == 0])
visited_count = 0
while queue:
u = queue.popleft()
visited_count += 1
for v in adj_list[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
queue.append(v)
if visited_count < len(node_map):
cyclic_nodes = [nid for nid, deg in in_degree.items() if deg > 0]
wf_errors.append(
f"μ›Œν¬ν”Œλ‘œμš° 내에 μˆœν™˜ μ°Έμ‘°(Circular Loop)κ°€ μ‘΄μž¬ν•˜μ—¬ μœ„μƒ 정렬을 μˆ˜ν–‰ν•  수 μ—†μŠ΅λ‹ˆλ‹€. "
f"μˆœν™˜ κ΄€μ—¬ λ…Έλ“œ: {cyclic_nodes}. 루프백 엣지에 loopback: true 속성이 λΆ€μ—¬λ˜μ–΄ μžˆλŠ”μ§€ ν™•μΈν•˜μ‹­μ‹œμ˜€."
)
return wf_errors, wf_warnings
def main():
db_arg = sys.argv[1] if len(sys.argv) > 1 else None
# κΈ°λ³Έ 경둜 탐색
home_dir = os.path.expanduser('~')
default_db = os.path.join(home_dir, '.claude', 'knowledge.db')
default_json = os.path.join(home_dir, '.claude', 'knowledge.json')
workflows = []
source_path = ""
if db_arg:
source_path = db_arg
if db_arg.endswith('.json'):
workflows = load_workflows_from_json(db_arg)
else:
workflows = load_workflows_from_db(db_arg)
else:
# SQLite μš°μ„  λ‘œλ“œ
if os.path.exists(default_db):
source_path = default_db
workflows = load_workflows_from_db(default_db)
# JSON λ‘œλ“œ
if not workflows and os.path.exists(default_json):
source_path = default_json
workflows = load_workflows_from_json(default_json)
if not workflows:
print(f"🚨 ERROR: BADA μ›Œν¬ν”Œλ‘œμš° 데이터λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€. (λŒ€μƒ 경둜: {source_path or default_db + ' / ' + default_json})")
return 1
print(f"πŸ” Starting BADA Workflow Lint on: {source_path}")
profile_ids = load_agent_profiles()
total_errors = 0
total_warnings = 0
for wf in workflows:
wf_id = wf.get('id')
wf_name = wf.get('name', 'Unnamed Workflow')
print(f"\nπŸ“‚ Checking Workflow: [{wf_name}] (ID: {wf_id})")
errors, warnings = validate_workflow(wf, profile_ids)
if errors:
print(" 🚨 ERRORS:")
for err in errors:
print(f" - {err}")
total_errors += len(errors)
if warnings:
print(" ⚠️ WARNINGS:")
for wrn in warnings:
print(f" - {wrn}")
total_warnings += len(warnings)
if not errors and not warnings:
print(" βœ… Workflow is clean and valid.")
print("\n=== Workflow Lint Summary ===")
print(f"Workflows scanned: {len(workflows)}")
print(f"Total Errors: {total_errors}")
print(f"Total Warnings: {total_warnings}")
if total_errors > 0:
print("\n🚨 Workflow static verification FAILED.")
return 1
print("\nβœ… Workflow static verification PASSED successfully!")
return 0
if __name__ == '__main__':
sys.exit(main())