File size: 11,090 Bytes
d739b1b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | #!/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())
|