-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.py
More file actions
1568 lines (1366 loc) · 68.9 KB
/
Copy pathworker.py
File metadata and controls
1568 lines (1366 loc) · 68.9 KB
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import hashlib
import time
import tempfile
from concurrent.futures import ThreadPoolExecutor
import urllib.request
import urllib.error
from datetime import datetime
from pathlib import Path
from sqlalchemy import text
from sqlalchemy.exc import OperationalError
from utils.db import DATABASE_URL, SyncSessionLocal, sync_engine
from tavro_agent_card import TavroAgentCard
API_URL = os.getenv("API_URL", "http://tavro-api:8000/api/v1/risk/classify-risk")
API_DISPATCH_MAX_WORKERS = int(os.getenv("API_DISPATCH_MAX_WORKERS", "20"))
# Default tenant assigned to all agents loaded via the worker / connectors.
# Set TENANT_ID in the container environment (docker-compose or .env).
TENANT_ID = os.getenv("TENANT_ID", "")
WAIT_FOR_API_DISPATCH = os.getenv("WAIT_FOR_API_DISPATCH", "false").strip().lower() == "true"
_api_dispatch_pool = ThreadPoolExecutor(max_workers=API_DISPATCH_MAX_WORKERS)
_api_dispatch_futures = []
# ── Connection pool ───────────────────────────────────────────────────────────
# SQLAlchemy manages the pool via sync_engine (defined in utils/db.py).
# init_pool() is kept as a public API so connectors can call it before
# processing cards — it now verifies connectivity with the same retry logic.
_MAX_RETRIES = 10
_RETRY_DELAY = 3
def init_pool():
for attempt in range(1, _MAX_RETRIES + 1):
try:
with sync_engine.connect() as conn:
conn.execute(text("SELECT 1"))
print("DB pool initialised.")
return
except OperationalError as e:
print(f"DB not ready (attempt {attempt}/{_MAX_RETRIES}): {e}")
if attempt < _MAX_RETRIES:
print(f"Retrying in {_RETRY_DELAY}s ...")
time.sleep(_RETRY_DELAY)
else:
raise RuntimeError("Could not connect to DB after maximum retries.")
def close_pool():
sync_engine.dispose()
print("DB pool closed.")
# ══════════════════════════════════════════════════════════════════════════════
# DB helpers (replace Athena start/poll/fetch)
# ══════════════════════════════════════════════════════════════════════════════
def execute_query(sql: str) -> list:
"""Execute a SELECT and return rows as a list of dicts."""
with SyncSessionLocal() as session:
result = session.execute(text(sql))
return [dict(row) for row in result.mappings()]
def execute_dml(sql: str, label: str = ""):
"""Execute a DML statement (INSERT / UPDATE / DELETE)."""
with SyncSessionLocal() as session:
session.execute(text(sql))
session.commit()
print(f" ✓ {label} succeeded")
# ══════════════════════════════════════════════════════════════════════════════
# SQL value helpers (unchanged from Lambda)
# ══════════════════════════════════════════════════════════════════════════════
def _hash(obj) -> str:
raw = json.dumps(obj, sort_keys=True, default=str) if obj is not None else ""
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def _sq(val) -> str:
if val is None:
return "NULL"
return "'" + str(val).replace("'", "''") + "'"
def _bool(val) -> str:
if val is None:
return "NULL"
return "true" if val else "false"
def _array_str(lst) -> str:
# Postgres needs an explicit cast on an empty array literal
if not lst:
return "ARRAY[]::text[]"
items = ", ".join(f"'{str(i).replace(chr(39), chr(39)+chr(39))}'" for i in lst)
return f"ARRAY[{items}]"
# ══════════════════════════════════════════════════════════════════════════════
# SKIP EMPTY PAYLOAD (unchanged)
# ══════════════════════════════════════════════════════════════════════════════
def has_meaningful_data(data) -> bool:
def is_meaningful(value):
if value is None:
return False
if isinstance(value, str) and value.strip() == "":
return False
if isinstance(value, (list, dict)) and len(value) == 0:
return False
return True
if isinstance(data, dict):
return any(is_meaningful(v) for v in data.values())
if isinstance(data, list):
for item in data:
if isinstance(item, dict):
if any(is_meaningful(v) for v in item.values()):
return True
return False
return False
# ══════════════════════════════════════════════════════════════════════════════
# SOURCE HASH CHECK (unchanged logic — SQL is identical Postgres / Athena)
# ══════════════════════════════════════════════════════════════════════════════
def get_current_agent_source_hash(agent_id: str):
sql = f"""
SELECT source_hash
FROM core.agents
WHERE agent_id = {_sq(agent_id)}
AND is_current = true
ORDER BY updated_ts DESC
LIMIT 1
"""
result = execute_query(sql)
return result[0].get("source_hash") if result else None
# ══════════════════════════════════════════════════════════════════════════════
# UPSERTS — same logic as Lambda; MERGE INTO → INSERT … ON CONFLICT DO UPDATE
#
# Required unique indexes (add to init.sql):
#
# CREATE UNIQUE INDEX ON core.agents (agent_id, agent_name) WHERE is_current = true;
# CREATE UNIQUE INDEX ON core.agent_configurations (agent_internal_id) WHERE is_current = true;
# CREATE UNIQUE INDEX ON core.agent_identifications (agent_internal_id) WHERE is_current = true;
# CREATE UNIQUE INDEX ON core.agent_tools (agent_internal_id, tool_id);
# CREATE UNIQUE INDEX ON core.agent_controls (agent_internal_id, name);
# CREATE UNIQUE INDEX ON core.agent_knowledge_sources (agent_internal_id);
# CREATE UNIQUE INDEX ON core.agent_llm_models (agent_internal_id, name);
# CREATE UNIQUE INDEX ON core.agent_ai_use_cases (tenant_id, ai_use_case_id, agent_id);
# CREATE UNIQUE INDEX ON core.agent_business_processes (agent_internal_id, business_process_id);
# CREATE UNIQUE INDEX ON core.agent_business_applications (agent_internal_id, business_application_id);
# CREATE UNIQUE INDEX ON core.agent_guardrails (agent_internal_id, name);
# CREATE UNIQUE INDEX ON core.agent_mcp_servers (agent_internal_id);
# CREATE UNIQUE INDEX ON core.agent_memories (agent_internal_id);
# CREATE UNIQUE INDEX ON core.agent_physical_ai (agent_internal_id, name);
# CREATE UNIQUE INDEX ON core.agent_prompt_templates (agent_internal_id);
# CREATE UNIQUE INDEX ON core.agent_regulations_or_frameworks (agent_internal_id);
# CREATE UNIQUE INDEX ON core.agent_ai_models (agent_internal_id, model_name);
# CREATE UNIQUE INDEX ON core.agent_data_sources (agent_internal_id, source_object_id, target_object_id);
# ══════════════════════════════════════════════════════════════════════════════
def upsert_agent(card: dict, now_str: str, incoming_source_hash: str = None) -> str:
ident = card.get("identification", {})
agent_id = ident.get("agent_id")
incoming_internal_id = ident.get("agent_internal_id")
tenant_id = ident.get("tenant_id") or TENANT_ID or None
tenant_id_sql = "NULL" if not tenant_id else _sq(tenant_id)
row = {
"agent_name": card.get("name"),
"agent_description": card.get("description"),
"protocol_version": card.get("protocol_version"),
"preferred_transport": card.get("preferredTransport"),
"supports_auth_ext_card": card.get("supports_authenticated_extended_card"),
"card_version": card.get("version"),
"source_system": card.get("provider", {}).get("organization"),
}
source_hash = incoming_source_hash or _hash(card)
record_hash = _hash(row)
# Look up existing agent_internal_id
lookup_sql = f"""
SELECT agent_internal_id
FROM core.agents
WHERE agent_id = {_sq(agent_id)}
LIMIT 1
"""
print(" Looking up existing agent_internal_id …")
result = execute_query(lookup_sql)
if result:
agent_internal_id = result[0]["agent_internal_id"]
print(f" Found existing agent_internal_id={agent_internal_id} → UPDATE")
else:
agent_internal_id = incoming_internal_id
print(f" No match → INSERT with agent_internal_id={agent_internal_id}")
sql = f"""
INSERT INTO core.agents (
agent_id, agent_internal_id, agent_name, agent_description,
protocol_version, preferred_transport, supports_auth_ext_card,
card_version, source_hash, source_system, record_hash,
tenant_id,
valid_from_ts, valid_to_ts, is_current, created_ts, updated_ts
) VALUES (
{_sq(agent_id)}, {_sq(agent_internal_id)}, {_sq(row['agent_name'])},
{_sq(row['agent_description'])}, {_sq(row['protocol_version'])},
{_sq(row['preferred_transport'])}, {_bool(row['supports_auth_ext_card'])},
{_sq(row['card_version'])}, {_sq(source_hash)}, {_sq(row['source_system'])},
{_sq(record_hash)},
{tenant_id_sql},
TIMESTAMP '{now_str}', NULL, true,
TIMESTAMP '{now_str}', TIMESTAMP '{now_str}'
)
ON CONFLICT (agent_id, agent_name) WHERE is_current = true
DO UPDATE SET
agent_internal_id = EXCLUDED.agent_internal_id,
agent_description = EXCLUDED.agent_description,
protocol_version = EXCLUDED.protocol_version,
preferred_transport = EXCLUDED.preferred_transport,
supports_auth_ext_card = EXCLUDED.supports_auth_ext_card,
card_version = EXCLUDED.card_version,
source_hash = EXCLUDED.source_hash,
source_system = EXCLUDED.source_system,
record_hash = EXCLUDED.record_hash,
tenant_id = EXCLUDED.tenant_id,
updated_ts = EXCLUDED.updated_ts
"""
print(" Upserting agents …")
execute_dml(sql, label="agents INSERT ON CONFLICT")
return agent_internal_id
def upsert_agent_configuration(card: dict, agent_internal_id: str, now_str: str):
ident = card.get("identification", {})
cfg = card.get("configuration", {})
if not has_meaningful_data(cfg):
print("Skipping agent_configurations: all values are null/empty.")
return
caps = card.get("capabilities", {})
agent_id = ident.get("agent_id")
execution_mode = "streaming" if caps.get("streaming") else "batch"
row = {
"access_scope": cfg.get("access_scope"),
"memory_type": cfg.get("memory_type"),
"data_freshness_policy": cfg.get("data_freshness_policy"),
"autonomy_level": cfg.get("autonomy_level"),
"reasoning_model": cfg.get("reasoning_model"),
"human_in_the_loop_flag": None,
"execution_mode": execution_mode,
}
record_hash = _hash(row)
sql = f"""
INSERT INTO core.agent_configurations (
agent_internal_id, agent_id,
access_scope, memory_type, data_freshness_policy,
autonomy_level, reasoning_model, human_in_the_loop_flag,
execution_mode, record_hash,
valid_from_ts, valid_to_ts, is_current, created_ts, updated_ts
) VALUES (
{_sq(agent_internal_id)}, {_sq(agent_id)},
{_sq(row['access_scope'])}, {_sq(row['memory_type'])},
{_sq(row['data_freshness_policy'])}, {_sq(row['autonomy_level'])},
{_sq(row['reasoning_model'])}, {_bool(row['human_in_the_loop_flag'])},
{_sq(row['execution_mode'])}, {_sq(record_hash)},
TIMESTAMP '{now_str}', NULL, true,
TIMESTAMP '{now_str}', TIMESTAMP '{now_str}'
)
ON CONFLICT (agent_internal_id) WHERE is_current = true
DO UPDATE SET
agent_id = EXCLUDED.agent_id,
access_scope = EXCLUDED.access_scope,
memory_type = EXCLUDED.memory_type,
data_freshness_policy = EXCLUDED.data_freshness_policy,
autonomy_level = EXCLUDED.autonomy_level,
reasoning_model = EXCLUDED.reasoning_model,
human_in_the_loop_flag = EXCLUDED.human_in_the_loop_flag,
execution_mode = EXCLUDED.execution_mode,
record_hash = EXCLUDED.record_hash,
updated_ts = EXCLUDED.updated_ts
"""
print(" Upserting agent_configurations …")
execute_dml(sql, label="agent_configurations INSERT ON CONFLICT")
def upsert_agent_identification(card: dict, agent_internal_id: str, now_str: str):
ident = card.get("identification", {})
agent_id = ident.get("agent_id")
tags_raw = ident.get("tags")
tags = tags_raw if isinstance(tags_raw, list) else []
sql = f"""
INSERT INTO core.agent_identifications (
agent_internal_id, agent_id,
goal_orientation, role, instruction,
owner, environment, tags,
governance_status, reviewer, cost_center,
is_current, created_ts, updated_ts
) VALUES (
{_sq(agent_internal_id)}, {_sq(agent_id)},
{_sq(ident.get('goal_orientation'))}, {_sq(ident.get('role'))},
{_sq(ident.get('instruction'))}, {_sq(ident.get('owner'))},
{_sq(ident.get('environment'))}, {_array_str(tags)},
{_sq(ident.get('governance_status'))}, {_sq(ident.get('reviewer'))},
{_sq(ident.get('cost_center'))},
true, TIMESTAMP '{now_str}', TIMESTAMP '{now_str}'
)
ON CONFLICT (agent_internal_id) WHERE is_current = true
DO UPDATE SET
agent_id = EXCLUDED.agent_id,
goal_orientation = EXCLUDED.goal_orientation,
role = EXCLUDED.role,
instruction = EXCLUDED.instruction,
owner = EXCLUDED.owner,
environment = EXCLUDED.environment,
tags = EXCLUDED.tags,
governance_status= EXCLUDED.governance_status,
reviewer = EXCLUDED.reviewer,
cost_center = EXCLUDED.cost_center,
updated_ts = EXCLUDED.updated_ts
"""
print(" Upserting agent_identifications …")
execute_dml(sql, label="agent_identifications INSERT ON CONFLICT")
def upsert_agent_tools(card: dict, agent_internal_id: str, now_str: str):
ident = card.get("identification", {})
tools = card.get("tool", []) or []
if not has_meaningful_data(tools):
print("Skipping agent_tools: all tools are empty.")
return
agent_id = ident.get("agent_id")
select_rows = []
for tool in tools:
tool_id = tool.get("identifier")
delegation_possible = (
str(tool.get("delegation_possible")).lower() == "true"
if tool.get("delegation_possible") is not None else None
)
select_rows.append(f"""
SELECT
{_sq(agent_internal_id)} AS agent_internal_id,
{_sq(agent_id)} AS agent_id,
{_sq(tool_id)} AS tool_id,
{_sq(tool.get('name'))} AS tool_name,
{_sq(tool.get('description'))} AS tool_description,
{_bool(delegation_possible)}::boolean AS delegation_possible,
{_sq(tool.get('allowed_delegates'))} AS allowed_delegates,
{_sq(tool.get('input_schema'))} AS input_schema_json_text,
{_sq(tool.get('output_schema'))} AS output_schema_json_text,
{_sq(tool.get('default_value'))} AS default_config_json_text,
TIMESTAMP '{now_str}' AS now_ts
""".strip())
union_all = "\nUNION ALL\n".join(select_rows)
sql = f"""
INSERT INTO core.agent_tools (
agent_internal_id, agent_id, tool_id, tool_name, tool_description,
delegation_possible, allowed_delegates,
input_schema_json_text, output_schema_json_text, default_config_json_text,
created_ts, updated_ts
)
SELECT
agent_internal_id, agent_id, tool_id, tool_name, tool_description,
delegation_possible, allowed_delegates,
input_schema_json_text, output_schema_json_text, default_config_json_text,
now_ts, now_ts
FROM ({union_all}) AS s
ON CONFLICT (agent_internal_id, tool_id)
DO UPDATE SET
agent_id = EXCLUDED.agent_id,
tool_description = EXCLUDED.tool_description,
delegation_possible = EXCLUDED.delegation_possible,
allowed_delegates = EXCLUDED.allowed_delegates,
input_schema_json_text = EXCLUDED.input_schema_json_text,
output_schema_json_text = EXCLUDED.output_schema_json_text,
default_config_json_text = EXCLUDED.default_config_json_text,
updated_ts = EXCLUDED.updated_ts
"""
print(f" Upserting {len(tools)} tools …")
execute_dml(sql, label="agent_tools BULK INSERT ON CONFLICT")
def upsert_agent_controls(card: dict, agent_internal_id: str, now_str: str):
ident = card.get("identification", {})
controls = card.get("control", []) or []
if not has_meaningful_data(controls):
print("Skipping controls: all values are null/empty.")
return
agent_id = ident.get("agent_id")
select_rows = []
for control in controls:
select_rows.append(f"""
SELECT
{_sq(agent_internal_id)} AS agent_internal_id,
{_sq(agent_id)} AS agent_id,
{_sq(control.get('identifier'))} AS identifier,
{_sq(control.get('name'))} AS name,
{_sq(control.get('objective'))} AS objective,
{_sq(control.get('domain'))} AS domain,
TIMESTAMP '{now_str}' AS now_ts
""".strip())
union_all = "\nUNION ALL\n".join(select_rows)
sql = f"""
INSERT INTO core.agent_controls (
agent_internal_id, agent_id, identifier, name, objective, domain,
created_ts, updated_ts
)
SELECT
agent_internal_id, agent_id, identifier, name, objective, domain,
now_ts, now_ts
FROM ({union_all}) AS s
ON CONFLICT (agent_internal_id, name)
DO UPDATE SET
agent_id = EXCLUDED.agent_id,
identifier = EXCLUDED.identifier,
objective = EXCLUDED.objective,
domain = EXCLUDED.domain,
updated_ts = EXCLUDED.updated_ts
"""
print(f" Upserting {len(controls)} controls …")
execute_dml(sql, label="agent_controls BULK INSERT ON CONFLICT")
def upsert_agent_knowledge_source(card: dict, agent_internal_id: str, now_str: str):
ident = card.get("identification", {})
ks = card.get("knowledge_source", {}) or {}
if not has_meaningful_data(ks):
print("Skipping knowledge_source: all values are null/empty.")
return
agent_id = ident.get("agent_id")
sql = f"""
INSERT INTO core.agent_knowledge_sources (
agent_internal_id, agent_id, identifier, name, access_mechanism,
created_ts, updated_ts
) VALUES (
{_sq(agent_internal_id)}, {_sq(agent_id)},
{_sq(ks.get('identifier'))}, {_sq(ks.get('name'))},
{_sq(ks.get('access_mechanism'))},
TIMESTAMP '{now_str}', TIMESTAMP '{now_str}'
)
ON CONFLICT (agent_internal_id)
DO UPDATE SET
agent_id = EXCLUDED.agent_id,
identifier = EXCLUDED.identifier,
name = EXCLUDED.name,
access_mechanism = EXCLUDED.access_mechanism,
updated_ts = EXCLUDED.updated_ts
"""
print(" Upserting agent_knowledge_sources …")
execute_dml(sql, label="agent_knowledge_sources INSERT ON CONFLICT")
def upsert_agent_llm_models(card: dict, agent_internal_id: str, now_str: str):
ident = card.get("identification", {})
llm_models = card.get("llm_model", []) or []
if not has_meaningful_data(llm_models):
print("Skipping llm_model: all values are null/empty.")
return
agent_id = ident.get("agent_id")
select_rows = []
for model in llm_models:
select_rows.append(f"""
SELECT
{_sq(agent_internal_id)} AS agent_internal_id,
{_sq(agent_id)} AS agent_id,
{_sq(model.get('name'))} AS name,
{_sq(model.get('version'))} AS version_number,
TIMESTAMP '{now_str}' AS now_ts
""".strip())
union_all = "\nUNION ALL\n".join(select_rows)
sql = f"""
INSERT INTO core.agent_llm_models (
agent_internal_id, agent_id, name, version_number,
created_ts, updated_ts
)
SELECT agent_internal_id, agent_id, name, version_number, now_ts, now_ts
FROM ({union_all}) AS s
ON CONFLICT (agent_internal_id, name)
DO UPDATE SET
agent_id = EXCLUDED.agent_id,
version_number = EXCLUDED.version_number,
updated_ts = EXCLUDED.updated_ts
"""
print(f" Upserting {len(llm_models)} LLM models …")
execute_dml(sql, label="agent_llm_models BULK INSERT ON CONFLICT")
def upsert_agent_ai_use_cases(card: dict, agent_internal_id: str, now_str: str):
ident = card.get("identification", {})
ai_use_cases = card.get("ai_use_case", []) or []
if not has_meaningful_data(ai_use_cases):
print("Skipping ai_use_case: all values are null/empty.")
return
tenant_id = ident.get("tenant_id") or ""
agent_id = ident.get("agent_id")
agent_name = ident.get("agent_name") or card.get("name")
select_rows = []
for uc in ai_use_cases:
use_case_id = uc.get("identifier") or uc.get("ai_use_case_id")
if not _clean_text(use_case_id):
continue
select_rows.append(f"""
SELECT
{_sq(agent_internal_id)} AS agent_internal_id,
{_sq(tenant_id)} AS tenant_id,
{_sq(agent_id)} AS agent_id,
{_sq(agent_name)} AS agent_name,
{_sq(use_case_id)} AS ai_use_case_id,
{_sq(uc.get('name'))} AS ai_use_case_name,
{_sq(uc.get('description'))} AS description,
{_sq(uc.get('proposed_by'))} AS proposed_by,
{_sq(uc.get('owner'))} AS owner,
{_sq(uc.get('business_function'))} AS function,
{_sq(uc.get('problem_statement'))} AS problem_statement,
{_sq(uc.get('expected_benefits'))} AS expected_benefits,
{_sq(uc.get('priority'))} AS priority,
{_sq(uc.get('status'))} AS status,
NULLIF({_sq(uc.get('agent_risk_exposure_are'))}, '')::numeric(10,2) AS agent_risk_exposure_are,
NULLIF({_sq(uc.get('no_of_associated_agents'))}, '')::int AS no_of_associated_agents,
{_sq(uc.get('inherent_risk_classification'))} AS inherent_risk_classification,
{_sq(uc.get('residual_risk_classification'))} AS residual_risk_classification,
{_sq(uc.get('agent_risk_tier_art'))} AS agent_risk_tier_art,
NULLIF({_sq(uc.get('blended_risk_score'))}, '')::numeric(10,2) AS blended_risk_score,
NULLIF({_sq(uc.get('inherent_risk_classification_score'))}, '')::numeric(10,2) AS inherent_risk_classification_score,
NULLIF({_sq(uc.get('residual_risk_classification_score'))}, '')::numeric(10,2) AS residual_risk_classification_score,
{_sq(uc.get('solution_approach'))} AS solution_approach,
TIMESTAMP '{now_str}' AS now_ts
""".strip())
if not select_rows:
print("Skipping ai_use_case: missing identifiers.")
return
union_all = "\nUNION ALL\n".join(select_rows)
use_case_sql = f"""
INSERT INTO core.ai_use_cases (
tenant_id, ai_use_case_id, name, description, proposed_by, owner, function,
problem_statement, expected_benefits, priority, status,
agent_risk_exposure_are, no_of_associated_agents, inherent_risk_classification,
residual_risk_classification, agent_risk_tier_art, blended_risk_score,
inherent_risk_classification_score, residual_risk_classification_score,
solution_approach, created_ts, updated_ts
)
SELECT
tenant_id, ai_use_case_id, ai_use_case_name, description, proposed_by, owner, function,
problem_statement, expected_benefits, priority, status,
agent_risk_exposure_are, no_of_associated_agents, inherent_risk_classification,
residual_risk_classification, agent_risk_tier_art, blended_risk_score,
inherent_risk_classification_score, residual_risk_classification_score,
solution_approach, now_ts, now_ts
FROM ({union_all}) AS s
ON CONFLICT (tenant_id, ai_use_case_id)
DO UPDATE SET
name = EXCLUDED.name,
description = EXCLUDED.description,
proposed_by = EXCLUDED.proposed_by,
owner = EXCLUDED.owner,
function = EXCLUDED.function,
problem_statement = EXCLUDED.problem_statement,
expected_benefits = EXCLUDED.expected_benefits,
priority = EXCLUDED.priority,
status = EXCLUDED.status,
agent_risk_exposure_are = EXCLUDED.agent_risk_exposure_are,
no_of_associated_agents = EXCLUDED.no_of_associated_agents,
inherent_risk_classification = EXCLUDED.inherent_risk_classification,
residual_risk_classification = EXCLUDED.residual_risk_classification,
agent_risk_tier_art = EXCLUDED.agent_risk_tier_art,
blended_risk_score = EXCLUDED.blended_risk_score,
inherent_risk_classification_score = EXCLUDED.inherent_risk_classification_score,
residual_risk_classification_score = EXCLUDED.residual_risk_classification_score,
solution_approach = EXCLUDED.solution_approach,
updated_ts = EXCLUDED.updated_ts
"""
execute_dml(use_case_sql, label="ai_use_cases BULK INSERT ON CONFLICT")
relation_sql = f"""
INSERT INTO core.agent_ai_use_cases (
tenant_id, ai_use_case_id, ai_use_case_name, agent_id, agent_name, agent_internal_id, created_ts, updated_ts
)
SELECT
tenant_id, ai_use_case_id, ai_use_case_name, agent_id, agent_name, agent_internal_id, now_ts, now_ts
FROM ({union_all}) AS s
WHERE agent_id IS NOT NULL AND agent_id <> ''
ON CONFLICT (tenant_id, ai_use_case_id, agent_id)
DO UPDATE SET
ai_use_case_name = EXCLUDED.ai_use_case_name,
agent_name = EXCLUDED.agent_name,
agent_internal_id = EXCLUDED.agent_internal_id,
updated_ts = EXCLUDED.updated_ts
"""
execute_dml(relation_sql, label="agent_ai_use_cases BULK INSERT ON CONFLICT")
sync_count_sql = f"""
WITH affected AS (
SELECT DISTINCT tenant_id, ai_use_case_id
FROM ({union_all}) AS s
),
counts AS (
SELECT
a.tenant_id,
a.ai_use_case_id,
COUNT(DISTINCT rel.agent_id) AS associated_count
FROM affected a
LEFT JOIN core.agent_ai_use_cases rel
ON rel.ai_use_case_id = a.ai_use_case_id
AND COALESCE(rel.tenant_id, '') = COALESCE(a.tenant_id, '')
AND rel.agent_id IS NOT NULL
AND rel.agent_id <> ''
GROUP BY a.tenant_id, a.ai_use_case_id
)
UPDATE core.ai_use_cases uc
SET
no_of_associated_agents = c.associated_count,
updated_ts = TIMESTAMP '{now_str}'
FROM counts c
WHERE uc.ai_use_case_id = c.ai_use_case_id
AND COALESCE(uc.tenant_id, '') = COALESCE(c.tenant_id, '')
"""
execute_dml(sync_count_sql, label="ai_use_cases associated-count sync")
print(f" Upserting {len(select_rows)} AI use cases …")
def _clean_text(value):
if value is None:
return None
text = str(value).strip()
return text or None
def _canonical_entity_id(raw_identifier, raw_name):
return _clean_text(raw_identifier) or _clean_text(raw_name)
def upsert_business_processes(card: dict, agent_internal_id: str, now_str: str):
processes = card.get("business_process", []) or []
if not has_meaningful_data(processes):
print("Skipping core.business_processes: all values are null/empty.")
return
select_rows = []
inserted_ids = set()
referenced_ids = set()
for proc in processes:
business_process_id = _canonical_entity_id(proc.get("identifier"), proc.get("name"))
if not business_process_id or business_process_id in inserted_ids:
continue
inserted_ids.add(business_process_id)
referenced_ids.add(business_process_id)
process_number = _clean_text(proc.get("process_number")) or business_process_id
parent_process_id = _canonical_entity_id(
proc.get("parent_process_id"),
proc.get("parent_process_name"),
)
if parent_process_id:
referenced_ids.add(parent_process_id)
select_rows.append(f"""
SELECT
{_sq(business_process_id)} AS business_process_id,
{_sq(process_number)} AS process_number,
{_sq(proc.get('name'))} AS process_name,
{_sq(proc.get('description'))} AS process_description,
{_sq(parent_process_id)} AS parent_process_id,
{_sq(proc.get('business_criticality'))} AS business_criticality,
TIMESTAMP '{now_str}' AS now_ts
""".strip())
if not select_rows:
print("Skipping core.business_processes: no process identifiers found.")
return
process_seed_rows = "\nUNION ALL\n".join(
f"SELECT {_sq(pid)} AS business_process_id, TIMESTAMP '{now_str}' AS now_ts"
for pid in sorted(referenced_ids)
)
process_seed_sql = f"""
INSERT INTO core.business_processes (
business_process_id, process_number, created_ts, updated_ts
)
SELECT business_process_id, business_process_id, now_ts, now_ts
FROM ({process_seed_rows}) AS seed
ON CONFLICT (business_process_id)
DO UPDATE SET
updated_ts = EXCLUDED.updated_ts
"""
execute_dml(process_seed_sql, label="business_processes SEED FOR HIERARCHY")
union_all = "\nUNION ALL\n".join(select_rows)
sql = f"""
INSERT INTO core.business_processes (
business_process_id, process_number, process_name, process_description,
parent_process_id, business_criticality, created_ts, updated_ts
)
SELECT
business_process_id, process_number, process_name, process_description,
parent_process_id, business_criticality, now_ts, now_ts
FROM ({union_all}) AS s
ON CONFLICT (business_process_id)
DO UPDATE SET
process_number = COALESCE(EXCLUDED.process_number, core.business_processes.process_number),
process_name = COALESCE(EXCLUDED.process_name, core.business_processes.process_name),
process_description = COALESCE(EXCLUDED.process_description, core.business_processes.process_description),
parent_process_id = COALESCE(EXCLUDED.parent_process_id, core.business_processes.parent_process_id),
business_criticality = COALESCE(EXCLUDED.business_criticality, core.business_processes.business_criticality),
updated_ts = EXCLUDED.updated_ts
"""
print(f" Upserting {len(select_rows)} core business processes …")
execute_dml(sql, label="business_processes BULK INSERT ON CONFLICT")
def upsert_business_applications(card: dict, agent_internal_id: str, now_str: str):
applications = card.get("application", []) or []
if not has_meaningful_data(applications):
print("Skipping core.business_applications: all values are null/empty.")
return
select_rows = []
inserted_ids = set()
for app in applications:
business_application_id = _canonical_entity_id(app.get("identifier"), app.get("name"))
if not business_application_id or business_application_id in inserted_ids:
continue
inserted_ids.add(business_application_id)
select_rows.append(f"""
SELECT
{_sq(business_application_id)} AS business_application_id,
{_sq(app.get('name'))} AS application_name,
{_sq(app.get('business_criticality'))} AS business_criticality,
{_sq(app.get('emergency_tier'))} AS emergency_tier,
{_sq(app.get('description'))} AS application_description,
TIMESTAMP '{now_str}' AS now_ts
""".strip())
if not select_rows:
print("Skipping core.business_applications: no application identifiers found.")
return
union_all = "\nUNION ALL\n".join(select_rows)
sql = f"""
INSERT INTO core.business_applications (
business_application_id, application_name, business_criticality,
emergency_tier, application_description, created_ts, updated_ts
)
SELECT
business_application_id, application_name, business_criticality,
emergency_tier, application_description, now_ts, now_ts
FROM ({union_all}) AS s
ON CONFLICT (business_application_id)
DO UPDATE SET
application_name = COALESCE(EXCLUDED.application_name, core.business_applications.application_name),
business_criticality = COALESCE(EXCLUDED.business_criticality, core.business_applications.business_criticality),
emergency_tier = COALESCE(EXCLUDED.emergency_tier, core.business_applications.emergency_tier),
application_description = COALESCE(EXCLUDED.application_description, core.business_applications.application_description),
updated_ts = EXCLUDED.updated_ts
"""
print(f" Upserting {len(select_rows)} core business applications ...")
execute_dml(sql, label="business_applications BULK INSERT ON CONFLICT")
def upsert_agent_business_processes(card: dict, agent_internal_id: str, now_str: str):
ident = card.get("identification", {})
processes = card.get("business_process", []) or []
if not has_meaningful_data(processes):
print("Skipping business_process: all values are null/empty.")
return
agent_id = ident.get("agent_id")
select_rows = []
process_ids = []
for proc in processes:
business_process_id = _canonical_entity_id(proc.get("identifier"), proc.get("name"))
if not business_process_id:
continue
process_ids.append(business_process_id)
select_rows.append(f"""
SELECT
{_sq(agent_internal_id)} AS agent_internal_id,
{_sq(agent_id)} AS agent_id,
{_sq(business_process_id)} AS business_process_id,
{_sq(proc.get('name'))} AS process_name,
{_sq(proc.get('business_criticality'))} AS criticality,
TIMESTAMP '{now_str}' AS now_ts
""".strip())
if not select_rows:
print("Skipping business_process: no process identifiers found.")
return
union_all = "\nUNION ALL\n".join(select_rows)
sql = f"""
INSERT INTO core.agent_business_processes (
agent_internal_id, agent_id, business_process_id, process_name, criticality,
created_ts, updated_ts
)
SELECT
agent_internal_id, agent_id, business_process_id, process_name, criticality,
now_ts, now_ts
FROM ({union_all}) AS s
ON CONFLICT (agent_internal_id, business_process_id)
DO UPDATE SET
agent_id = EXCLUDED.agent_id,
process_name = EXCLUDED.process_name,
criticality = EXCLUDED.criticality,
updated_ts = EXCLUDED.updated_ts
"""
print(f" Upserting {len(select_rows)} business processes ...")
execute_dml(sql, label="agent_business_processes BULK INSERT ON CONFLICT")
unique_ids = list(dict.fromkeys(process_ids))
ids_sql = ", ".join(_sq(pid) for pid in unique_ids)
cleanup_sql = f"""
DELETE FROM core.agent_business_processes
WHERE agent_internal_id = {_sq(agent_internal_id)}
AND (business_process_id IS NULL OR business_process_id NOT IN ({ids_sql}))
"""
execute_dml(cleanup_sql, label="agent_business_processes DELETE STALE RELATIONS")
def upsert_agent_business_applications(card: dict, agent_internal_id: str, now_str: str):
ident = card.get("identification", {})
applications = card.get("application", []) or []
if not has_meaningful_data(applications):
print("Skipping application: all values are null/empty.")
return
agent_id = ident.get("agent_id")
select_rows = []
application_ids = []
for app in applications:
business_application_id = _canonical_entity_id(app.get("identifier"), app.get("name"))
if not business_application_id:
continue
application_ids.append(business_application_id)
select_rows.append(f"""
SELECT
{_sq(agent_internal_id)} AS agent_internal_id,
{_sq(agent_id)} AS agent_id,
{_sq(business_application_id)} AS business_application_id,
{_sq(app.get('name'))} AS application_name,
{_sq(app.get('business_criticality'))} AS criticality,
TIMESTAMP '{now_str}' AS now_ts
""".strip())
if not select_rows:
print("Skipping application: no application identifiers found.")
return
union_all = "\nUNION ALL\n".join(select_rows)
sql = f"""
INSERT INTO core.agent_business_applications (
agent_internal_id, agent_id, business_application_id, application_name, criticality,
created_ts, updated_ts
)
SELECT
agent_internal_id, agent_id, business_application_id, application_name, criticality,
now_ts, now_ts
FROM ({union_all}) AS s
ON CONFLICT (agent_internal_id, business_application_id)
DO UPDATE SET
agent_id = EXCLUDED.agent_id,
application_name = EXCLUDED.application_name,
criticality = EXCLUDED.criticality,
updated_ts = EXCLUDED.updated_ts
"""
print(f" Upserting {len(select_rows)} business applications ...")
execute_dml(sql, label="agent_business_applications BULK INSERT ON CONFLICT")
unique_ids = list(dict.fromkeys(application_ids))
ids_sql = ", ".join(_sq(app_id) for app_id in unique_ids)
cleanup_sql = f"""
DELETE FROM core.agent_business_applications
WHERE agent_internal_id = {_sq(agent_internal_id)}
AND (business_application_id IS NULL OR business_application_id NOT IN ({ids_sql}))
"""
execute_dml(cleanup_sql, label="agent_business_applications DELETE STALE RELATIONS")
def upsert_agent_guardrail(card: dict, agent_internal_id: str, now_str: str):
ident = card.get("identification", {})
guardrail = card.get("guardrail", {})
if not has_meaningful_data(guardrail):
print("Skipping guardrail: all values are null/empty.")
return
agent_id = ident.get("agent_id")
sql = f"""
INSERT INTO core.agent_guardrails (
agent_internal_id, agent_id, name, description, model,
created_ts, updated_ts
) VALUES (
{_sq(agent_internal_id)}, {_sq(agent_id)},
{_sq(guardrail.get('name'))}, {_sq(guardrail.get('description'))},
{_sq(guardrail.get('model'))},
TIMESTAMP '{now_str}', TIMESTAMP '{now_str}'
)
ON CONFLICT (agent_internal_id, name)
DO UPDATE SET
agent_id = EXCLUDED.agent_id,
description = EXCLUDED.description,
model = EXCLUDED.model,
updated_ts = EXCLUDED.updated_ts
"""
print(f" Upserting guardrail for agent {agent_id} …")
execute_dml(sql, label="agent_guardrails INSERT ON CONFLICT")
def upsert_agent_mcp_server(card: dict, agent_internal_id: str, now_str: str):
ident = card.get("identification", {})
mcp_server = card.get("mcp_server", {})
if not has_meaningful_data(mcp_server):
print("Skipping mcp_server: all values are null/empty.")
return
agent_id = ident.get("agent_id")
sql = f"""
INSERT INTO core.agent_mcp_servers (
agent_internal_id, agent_id, name, url, version_number,
last_updated_ts, created_ts, updated_ts
) VALUES (
{_sq(agent_internal_id)}, {_sq(agent_id)},
{_sq(mcp_server.get('name'))}, {_sq(mcp_server.get('url'))},
{_sq(mcp_server.get('version_number'))},
TIMESTAMP '{now_str}', TIMESTAMP '{now_str}', TIMESTAMP '{now_str}'
)
ON CONFLICT (agent_internal_id)
DO UPDATE SET
agent_id = EXCLUDED.agent_id,
name = EXCLUDED.name,
url = EXCLUDED.url,
version_number = EXCLUDED.version_number,
last_updated_ts = EXCLUDED.last_updated_ts,
updated_ts = EXCLUDED.updated_ts
"""
print(f" Upserting MCP server for agent {agent_id} …")
execute_dml(sql, label="agent_mcp_servers INSERT ON CONFLICT")
def upsert_agent_memory(card: dict, agent_internal_id: str, now_str: str):
ident = card.get("identification", {})
memory = card.get("memory", {})
if not has_meaningful_data(memory):
print("Skipping memory: all values are null/empty.")
return
agent_id = ident.get("agent_id")
sql = f"""
INSERT INTO core.agent_memories (
agent_internal_id, agent_id, identifier, name, type,
created_ts, updated_ts
) VALUES (
{_sq(agent_internal_id)}, {_sq(agent_id)},
{_sq(memory.get('identifier'))}, {_sq(memory.get('name'))},
{_sq(memory.get('type'))},