pidsmaker 5.0.0__py3-none-any.whl

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.
Files changed (339) hide show
  1. pidsmaker/__init__.py +1 -0
  2. pidsmaker/cli.py +81 -0
  3. pidsmaker/config/__init__.py +2 -0
  4. pidsmaker/config/config.py +2100 -0
  5. pidsmaker/config/pipeline.py +1824 -0
  6. pidsmaker/config/schemas.py +1032 -0
  7. pidsmaker/datasets.py +323 -0
  8. pidsmaker/debug_tests.py +30 -0
  9. pidsmaker/decoders/__init__.py +5 -0
  10. pidsmaker/decoders/custom_edge_mlp_decoder.py +17 -0
  11. pidsmaker/decoders/custom_mlp_decoder.py +10 -0
  12. pidsmaker/decoders/edge_linear_decoder.py +16 -0
  13. pidsmaker/decoders/inner_product_decoder.py +18 -0
  14. pidsmaker/decoders/nodlink_decoder.py +56 -0
  15. pidsmaker/detection/__init__.py +0 -0
  16. pidsmaker/detection/evaluation_methods/__init__.py +9 -0
  17. pidsmaker/detection/evaluation_methods/edge_evaluation.py +255 -0
  18. pidsmaker/detection/evaluation_methods/evaluation_utils.py +1788 -0
  19. pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
  20. pidsmaker/detection/evaluation_methods/node_evaluation.py +459 -0
  21. pidsmaker/detection/evaluation_methods/node_tw_evaluation.py +196 -0
  22. pidsmaker/detection/evaluation_methods/plot.py +192 -0
  23. pidsmaker/detection/evaluation_methods/queue_evaluation.py +456 -0
  24. pidsmaker/detection/evaluation_methods/tw_evaluation.py +93 -0
  25. pidsmaker/detection/flash_detection.py +162 -0
  26. pidsmaker/detection/magic_knn.py +190 -0
  27. pidsmaker/detection/node_scoring.py +52 -0
  28. pidsmaker/detection/threatrace_detection.py +65 -0
  29. pidsmaker/detection/training_methods/__init__.py +1 -0
  30. pidsmaker/detection/training_methods/inference_loop.py +287 -0
  31. pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
  32. pidsmaker/detection/training_methods/threatrace_training.py +168 -0
  33. pidsmaker/detection/training_methods/training_loop.py +383 -0
  34. pidsmaker/encoders/__init__.py +22 -0
  35. pidsmaker/encoders/argus_encoder.py +69 -0
  36. pidsmaker/encoders/custom_mlp.py +75 -0
  37. pidsmaker/encoders/custom_mlp_encoder.py +10 -0
  38. pidsmaker/encoders/egraphsage_encoder.py +56 -0
  39. pidsmaker/encoders/gat.py +67 -0
  40. pidsmaker/encoders/gcn.py +27 -0
  41. pidsmaker/encoders/gin.py +48 -0
  42. pidsmaker/encoders/glstm.py +298 -0
  43. pidsmaker/encoders/graph_attention.py +63 -0
  44. pidsmaker/encoders/gru.py +29 -0
  45. pidsmaker/encoders/hetero/__init__.py +4 -0
  46. pidsmaker/encoders/hetero/ancestor_encoder.py +98 -0
  47. pidsmaker/encoders/hetero/entity_encoder.py +33 -0
  48. pidsmaker/encoders/hetero/event_encoder.py +81 -0
  49. pidsmaker/encoders/hetero/hetero_graph_transformer.py +40 -0
  50. pidsmaker/encoders/lares_encoder.py +68 -0
  51. pidsmaker/encoders/linear_encoder.py +16 -0
  52. pidsmaker/encoders/magic_encoder.py +161 -0
  53. pidsmaker/encoders/rcaid_encoder.py +81 -0
  54. pidsmaker/encoders/rgcn.py +75 -0
  55. pidsmaker/encoders/sage.py +51 -0
  56. pidsmaker/encoders/shadewatcher_encoder.py +149 -0
  57. pidsmaker/encoders/sum_aggregation.py +20 -0
  58. pidsmaker/encoders/temporal_wrappers.py +80 -0
  59. pidsmaker/encoders/textrcnn.py +82 -0
  60. pidsmaker/encoders/tgn_encoder.py +193 -0
  61. pidsmaker/experiments/tuning.py +102 -0
  62. pidsmaker/experiments/uncertainty.py +261 -0
  63. pidsmaker/factory.py +1456 -0
  64. pidsmaker/featurization/__init__.py +0 -0
  65. pidsmaker/featurization/feat_inference_methods/__init__.py +7 -0
  66. pidsmaker/featurization/feat_inference_methods/feat_inference_HFH.py +30 -0
  67. pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +65 -0
  68. pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +14 -0
  69. pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +53 -0
  70. pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +37 -0
  71. pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +69 -0
  72. pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +84 -0
  73. pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
  74. pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1728 -0
  75. pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +55 -0
  76. pidsmaker/featurization/featurization_methods/__init__.py +0 -0
  77. pidsmaker/featurization/featurization_methods/build_trw.py +66 -0
  78. pidsmaker/featurization/featurization_methods/featurization_alacarte.py +747 -0
  79. pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +98 -0
  80. pidsmaker/featurization/featurization_methods/featurization_fasttext.py +74 -0
  81. pidsmaker/featurization/featurization_methods/featurization_flash.py +201 -0
  82. pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +242 -0
  83. pidsmaker/featurization/featurization_methods/featurization_trw.py +114 -0
  84. pidsmaker/featurization/featurization_methods/featurization_word2vec.py +89 -0
  85. pidsmaker/featurization/featurization_utils.py +275 -0
  86. pidsmaker/featurization/utils/build_random_walks.py +66 -0
  87. pidsmaker/featurization/utils/trw.py +203 -0
  88. pidsmaker/hetero.py +81 -0
  89. pidsmaker/losses.py +170 -0
  90. pidsmaker/main.py +478 -0
  91. pidsmaker/mimicry.py +284 -0
  92. pidsmaker/model.py +382 -0
  93. pidsmaker/objectives/__init__.py +16 -0
  94. pidsmaker/objectives/autoencode_edge_emb.py +43 -0
  95. pidsmaker/objectives/deep_graph_infomax.py +94 -0
  96. pidsmaker/objectives/detect_few_shot.py +21 -0
  97. pidsmaker/objectives/one_class.py +75 -0
  98. pidsmaker/objectives/predict_edge_contrastive.py +165 -0
  99. pidsmaker/objectives/predict_edge_supervised.py +77 -0
  100. pidsmaker/objectives/predict_edge_type.py +28 -0
  101. pidsmaker/objectives/predict_masked_struct.py +49 -0
  102. pidsmaker/objectives/predict_node_type.py +36 -0
  103. pidsmaker/objectives/predict_process_tag.py +169 -0
  104. pidsmaker/objectives/predict_snapshot_embedding.py +97 -0
  105. pidsmaker/objectives/reconstruct_edge_emb.py +16 -0
  106. pidsmaker/objectives/reconstruct_masked_feat.py +51 -0
  107. pidsmaker/objectives/reconstruct_node_emb.py +13 -0
  108. pidsmaker/objectives/reconstruct_node_feat.py +13 -0
  109. pidsmaker/objectives/validation_wrapper.py +55 -0
  110. pidsmaker/preprocessing/__init__.py +0 -0
  111. pidsmaker/preprocessing/build_graph_methods/__init__.py +1 -0
  112. pidsmaker/preprocessing/build_graph_methods/build_default_graphs.py +825 -0
  113. pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +216 -0
  114. pidsmaker/preprocessing/cleaning.py +258 -0
  115. pidsmaker/preprocessing/transformation_methods/__init__.py +2 -0
  116. pidsmaker/preprocessing/transformation_methods/attack_generation/synthetic_attack_naive.py +194 -0
  117. pidsmaker/preprocessing/transformation_methods/transformation_dag.py +28 -0
  118. pidsmaker/preprocessing/transformation_methods/transformation_merge_edges.py +136 -0
  119. pidsmaker/preprocessing/transformation_methods/transformation_rcaid_pseudo_graph.py +510 -0
  120. pidsmaker/preprocessing/transformation_methods/transformation_undirected.py +24 -0
  121. pidsmaker/preprocessing/transformation_methods/transformation_utils.py +36 -0
  122. pidsmaker/pretrained/__init__.py +5 -0
  123. pidsmaker/pretrained/data/__init__.py +4 -0
  124. pidsmaker/pretrained/data/behavior_signatures.py +548 -0
  125. pidsmaker/pretrained/data/canonical_tokens.py +1035 -0
  126. pidsmaker/pretrained/data/edge_filter.py +381 -0
  127. pidsmaker/pretrained/data/entity_classes.py +476 -0
  128. pidsmaker/pretrained/data/sampler.py +926 -0
  129. pidsmaker/pretrained/data/tokenizer_bpe.py +1659 -0
  130. pidsmaker/pretrained/detect.py +1427 -0
  131. pidsmaker/pretrained/embedding_generator.py +252 -0
  132. pidsmaker/pretrained/finetune.py +1434 -0
  133. pidsmaker/pretrained/models/__init__.py +20 -0
  134. pidsmaker/pretrained/models/behavior.py +348 -0
  135. pidsmaker/pretrained/models/bert.py +286 -0
  136. pidsmaker/pretrained/models/deepwalk.py +128 -0
  137. pidsmaker/pretrained/models/dgi.py +120 -0
  138. pidsmaker/pretrained/models/gae.py +114 -0
  139. pidsmaker/pretrained/models/gnn_distill.py +475 -0
  140. pidsmaker/pretrained/models/graphmae.py +373 -0
  141. pidsmaker/pretrained/models/hf_pretrained.py +213 -0
  142. pidsmaker/pretrained/models/llama.py +110 -0
  143. pidsmaker/pretrained/models/modernbert.py +567 -0
  144. pidsmaker/pretrained/models/roberta.py +147 -0
  145. pidsmaker/pretrained/models/rope_utils.py +99 -0
  146. pidsmaker/pretrained/models/ropebert.py +322 -0
  147. pidsmaker/pretrained/models/spider.py +204 -0
  148. pidsmaker/pretrained/models/tgn.py +770 -0
  149. pidsmaker/pretrained/pretrain/__init__.py +3 -0
  150. pidsmaker/pretrained/pretrain/pretrain_behavior_cluster.py +513 -0
  151. pidsmaker/pretrained/pretrain/pretrain_common.py +585 -0
  152. pidsmaker/pretrained/pretrain/pretrain_deepwalk.py +31 -0
  153. pidsmaker/pretrained/pretrain/pretrain_dgi.py +143 -0
  154. pidsmaker/pretrained/pretrain/pretrain_gae.py +143 -0
  155. pidsmaker/pretrained/pretrain/pretrain_gnn_distill.py +438 -0
  156. pidsmaker/pretrained/pretrain/pretrain_graphmae.py +151 -0
  157. pidsmaker/pretrained/pretrain/pretrain_hf.py +169 -0
  158. pidsmaker/pretrained/pretrain/pretrain_main.py +275 -0
  159. pidsmaker/pretrained/pretrain/pretrain_mlm.py +491 -0
  160. pidsmaker/pretrained/pretrain/pretrain_spider.py +502 -0
  161. pidsmaker/pretrained/training_utils.py +157 -0
  162. pidsmaker/process_reapr_gt.py +101 -0
  163. pidsmaker/resources/config/anomal_e.yml +25 -0
  164. pidsmaker/resources/config/argus.yml +56 -0
  165. pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
  166. pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
  167. pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
  168. pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
  169. pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
  170. pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
  171. pidsmaker/resources/config/default.yml +315 -0
  172. pidsmaker/resources/config/egraphsage.yml +95 -0
  173. pidsmaker/resources/config/euler.yml +104 -0
  174. pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
  175. pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
  176. pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
  177. pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
  178. pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
  179. pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
  180. pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
  181. pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
  182. pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
  183. pidsmaker/resources/config/flash.yml +79 -0
  184. pidsmaker/resources/config/jbeil.yml +65 -0
  185. pidsmaker/resources/config/kairos.yml +121 -0
  186. pidsmaker/resources/config/lares.yml +115 -0
  187. pidsmaker/resources/config/magic.yml +86 -0
  188. pidsmaker/resources/config/nodlink.yml +79 -0
  189. pidsmaker/resources/config/ocrapt.yml +91 -0
  190. pidsmaker/resources/config/orthrus.yml +126 -0
  191. pidsmaker/resources/config/orthrus_fixed.yml +17 -0
  192. pidsmaker/resources/config/pretrained/README.md +101 -0
  193. pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
  194. pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
  195. pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
  196. pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
  197. pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
  198. pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
  199. pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
  200. pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
  201. pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
  202. pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
  203. pidsmaker/resources/config/prographer.yml +136 -0
  204. pidsmaker/resources/config/rcaid.yml +88 -0
  205. pidsmaker/resources/config/shadewatcher.yml +146 -0
  206. pidsmaker/resources/config/tests.yml +10 -0
  207. pidsmaker/resources/config/threatrace.yml +73 -0
  208. pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
  209. pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
  210. pidsmaker/resources/config/velox.yml +10 -0
  211. pidsmaker/resources/config/viz_config.yml +10 -0
  212. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
  213. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
  214. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
  215. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
  216. pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
  217. pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
  218. pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
  219. pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
  220. pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
  221. pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
  222. pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
  223. pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
  224. pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
  225. pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
  226. pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
  227. pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
  228. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
  229. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
  230. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
  231. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
  232. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
  233. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
  234. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
  235. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
  236. pidsmaker/resources/ground_truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
  237. pidsmaker/resources/ground_truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
  238. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
  239. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
  240. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
  241. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
  242. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
  243. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
  244. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
  245. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
  246. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
  247. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
  248. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
  249. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
  250. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
  251. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
  252. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
  253. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
  254. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
  255. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
  256. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
  257. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
  258. pidsmaker/resources/ground_truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
  259. pidsmaker/resources/ground_truth/orthrus/h051/node_h051_0925.csv +114 -0
  260. pidsmaker/resources/ground_truth/orthrus/h201/node_h201_0923.csv +2905 -0
  261. pidsmaker/resources/ground_truth/orthrus/h501/node_h501_0924.csv +749 -0
  262. pidsmaker/resources/ground_truth/orthrus/readme.md +98 -0
  263. pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
  264. pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
  265. pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
  266. pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
  267. pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
  268. pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
  269. pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
  270. pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
  271. pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
  272. pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
  273. pidsmaker/resources/ground_truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
  274. pidsmaker/resources/ground_truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
  275. pidsmaker/resources/ground_truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
  276. pidsmaker/resources/ground_truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
  277. pidsmaker/resources/ground_truth/threatrace/README.md +123 -0
  278. pidsmaker/tasks/__init__.py +10 -0
  279. pidsmaker/tasks/batching.py +47 -0
  280. pidsmaker/tasks/construction.py +31 -0
  281. pidsmaker/tasks/evaluation.py +241 -0
  282. pidsmaker/tasks/feat_inference.py +413 -0
  283. pidsmaker/tasks/featurization.py +43 -0
  284. pidsmaker/tasks/training.py +17 -0
  285. pidsmaker/tasks/transformation.py +306 -0
  286. pidsmaker/tasks/triage.py +143 -0
  287. pidsmaker/tgn.py +635 -0
  288. pidsmaker/tokenization/__init__.py +112 -0
  289. pidsmaker/tokenization/base.py +58 -0
  290. pidsmaker/tokenization/bpe_tokenizer.py +83 -0
  291. pidsmaker/tokenization/hf_tokenizer.py +61 -0
  292. pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
  293. pidsmaker/tokenization/label_tokenizer.py +24 -0
  294. pidsmaker/tokenization/nltk_tokenizer.py +84 -0
  295. pidsmaker/tokenization/substitution.py +295 -0
  296. pidsmaker/triage/__init__.py +0 -0
  297. pidsmaker/triage/tracing_methods/__init__.py +1 -0
  298. pidsmaker/triage/tracing_methods/depimpact.py +213 -0
  299. pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
  300. pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
  301. pidsmaker/utils/__init__.py +0 -0
  302. pidsmaker/utils/cache_utils.py +256 -0
  303. pidsmaker/utils/console.py +282 -0
  304. pidsmaker/utils/data_utils.py +1742 -0
  305. pidsmaker/utils/database.py +150 -0
  306. pidsmaker/utils/dataset_utils.py +413 -0
  307. pidsmaker/utils/dataset_writer.py +570 -0
  308. pidsmaker/utils/graph_store.py +634 -0
  309. pidsmaker/utils/labelling.py +445 -0
  310. pidsmaker/utils/loss_files.py +193 -0
  311. pidsmaker/utils/process_tags.py +44 -0
  312. pidsmaker/utils/utils.py +712 -0
  313. pidsmaker/vizgen/__init__.py +1 -0
  314. pidsmaker/vizgen/backfill_manifests.py +100 -0
  315. pidsmaker/vizgen/dimensionality_reduction.py +249 -0
  316. pidsmaker/vizgen/embed_exporter.py +467 -0
  317. pidsmaker/vizgen/exporter.py +493 -0
  318. pidsmaker/vizgen/html_builder.py +936 -0
  319. pidsmaker/vizgen/web/__init__.py +1 -0
  320. pidsmaker/vizgen/web/export.py +62 -0
  321. pidsmaker/vizgen/web/static/css/app.css +250 -0
  322. pidsmaker/vizgen/web/static/index.html +182 -0
  323. pidsmaker/vizgen/web/static/js/app.js +627 -0
  324. pidsmaker/vizgen/web/static/js/campaign.js +123 -0
  325. pidsmaker/vizgen/web/static/js/data.js +119 -0
  326. pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
  327. pidsmaker/vizgen/web/static/js/jobs.js +75 -0
  328. pidsmaker/vizgen/web/static/js/scene.js +651 -0
  329. pidsmaker/vizgen/web/static/js/ui.js +370 -0
  330. pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
  331. pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
  332. pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
  333. pidsmaker/vizgen/web/viz_server.py +2176 -0
  334. pidsmaker-5.0.0.dist-info/METADATA +597 -0
  335. pidsmaker-5.0.0.dist-info/RECORD +339 -0
  336. pidsmaker-5.0.0.dist-info/WHEEL +5 -0
  337. pidsmaker-5.0.0.dist-info/entry_points.txt +2 -0
  338. pidsmaker-5.0.0.dist-info/licenses/LICENSE +201 -0
  339. pidsmaker-5.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,936 @@
1
+ """Interactive 2D HTML viewer with time slider for temporal embedding visualization.
2
+
3
+ Generates a self-contained HTML file with:
4
+ - Plotly.js scatter2d (X/Y = UMAP/t-SNE)
5
+ - Time window slider to scrub through temporal snapshots
6
+ - Click-to-highlight with node dimming
7
+ - Node inspector side panel
8
+ - Category toggles, search
9
+ - Fully offline (Plotly.js bundled inline)
10
+ """
11
+
12
+ import json
13
+ import os
14
+ import urllib.request
15
+
16
+ from pidsmaker.utils.utils import log
17
+
18
+
19
+ def _get_plotly_js():
20
+ """Return Plotly.js source, downloading and caching if needed."""
21
+ cache_dir = os.path.join(os.path.dirname(__file__), ".plotly_cache")
22
+ cache_path = os.path.join(cache_dir, "plotly.min.js")
23
+ if not os.path.exists(cache_path):
24
+ os.makedirs(cache_dir, exist_ok=True)
25
+ log("[html_builder] Downloading plotly.min.js for offline bundling...")
26
+ urllib.request.urlretrieve(
27
+ "https://cdn.plot.ly/plotly-2.27.0.min.js", cache_path
28
+ )
29
+ with open(cache_path, "r", encoding="utf-8") as f:
30
+ return f.read()
31
+
32
+
33
+ def build_html(points, edges, node_metadata, title="Embedding Visualization", default_hops=0, out_path=None, is_studio=False):
34
+ plotly_js = _get_plotly_js()
35
+
36
+ log(f"[html_builder] Filtering valid IDs for {len(points)} points...")
37
+ valid_ids = {p["node_id"] for p in points}
38
+ adj = {nid: [] for nid in valid_ids}
39
+
40
+ log("[html_builder] Building adjacency matrix...")
41
+ for edge in edges:
42
+ u, v, t = int(edge[0]), int(edge[1]), int(edge[2])
43
+ # edge relation is a string label (e.g. "EVENT_RECVMSG"). When edges come
44
+ # in as numpy rows the element is a numpy scalar (numpy.str_/int64) — call
45
+ # .item() to get a native Python str/int that json.dump can serialise.
46
+ et = edge[3] if len(edge) > 3 else "" # edge relation code
47
+ if hasattr(et, "item"):
48
+ et = et.item()
49
+ if u in valid_ids and v in valid_ids:
50
+ adj[u].append({"nb": v, "t": t, "dir": "out", "et": et})
51
+ adj[v].append({"nb": u, "t": t, "dir": "in", "et": et})
52
+
53
+ log("[html_builder] Attaching node metadata...")
54
+ for p in points:
55
+ meta = node_metadata.get(p["node_id"], {})
56
+ path_val = str(meta.get("path", "Unknown")).replace('"', "'")
57
+ cmd_val = str(meta.get("cmd", "")).replace('"', "'")
58
+ type_val = str(meta.get("type", "Unknown")).replace('"', "'")
59
+
60
+ if path_val == "None":
61
+ if cmd_val and cmd_val != "None":
62
+ path_val = cmd_val
63
+ elif type_val == "file":
64
+ path_val = "<Anonymous File/Pipe>"
65
+
66
+ p["path"] = path_val
67
+ p["type"] = type_val
68
+ p["cmd"] = cmd_val
69
+
70
+ if not out_path:
71
+ raise ValueError("out_path must be provided to build_html to save decoupled data files.")
72
+
73
+ points_file = out_path.replace('.html', '_points.json')
74
+ adj_file = out_path.replace('.html', '_adj.json')
75
+
76
+ max_tw = max((p.get("tw_idx", 0) for p in points), default=0)
77
+
78
+ # Compact serialization: round floats, strip empty fields
79
+ log(f"[html_builder] Serializing {len(points)} points to {os.path.basename(points_file)}...")
80
+ compact_points = []
81
+ for p in points:
82
+ cp = {
83
+ "node_id": p["node_id"],
84
+ "coords_hops": [[round(c, 3) for c in hop] for hop in p.get("coords_hops", [[0,0,0]])],
85
+ "tw_idx": p["tw_idx"],
86
+ "tw_label": p["tw_label"],
87
+ "label": p["label"],
88
+ "detection_status": p["detection_status"],
89
+ "anomaly_score": p.get("anomaly_score", 0.0),
90
+ "top_edge": p.get("top_edge", ""),
91
+ "path": p["path"],
92
+ "type": p["type"],
93
+ }
94
+ if p.get("cmd") and p["cmd"] != p["path"]:
95
+ cp["cmd"] = p["cmd"]
96
+ compact_points.append(cp)
97
+ with open(points_file, "w", encoding="utf-8") as f:
98
+ json.dump(compact_points, f, separators=(',', ':'))
99
+ log(f"[html_builder] Points file: {os.path.getsize(points_file) / (1024*1024):.1f} MB")
100
+
101
+ # Pre-build the web viewer's binary point cache now, from the in-memory
102
+ # records, so the server never parses this (100s of MB) points.json on first
103
+ # open — the single biggest cold-open cost at scale.
104
+ try:
105
+ from pidsmaker.vizgen.web import viz_server as _vs
106
+ _vs.build_point_cache(compact_points, points_file)
107
+ log("[html_builder] Pre-built binary point cache (instant first open).")
108
+ except Exception as e:
109
+ log(f"[html_builder] point cache pre-build skipped ({type(e).__name__}: {e})")
110
+
111
+ # Export a CSV file for offline analysis (Pandas/Excel)
112
+ csv_file = out_path.replace('.html', '_nodes.csv')
113
+ log(f"[html_builder] Exporting nodes to CSV for analysis: {os.path.basename(csv_file)}...")
114
+ import csv as _csv
115
+ with open(csv_file, "w", encoding="utf-8", newline='') as f:
116
+ writer = _csv.writer(f)
117
+ writer.writerow([
118
+ "node_id", "node_type", "path", "cmd",
119
+ "ground_truth_malicious", "detection_status",
120
+ "anomaly_score", "top_edge", "umap_x", "umap_y", "umap_z"
121
+ ])
122
+ for p in compact_points:
123
+ coords = p.get("coords_hops", [[0.0, 0.0, 0.0]])[0]
124
+ x = coords[0] if len(coords) > 0 else 0.0
125
+ y = coords[1] if len(coords) > 1 else 0.0
126
+ z = coords[2] if len(coords) > 2 else 0.0
127
+
128
+ writer.writerow([
129
+ p["node_id"],
130
+ p.get("type", ""),
131
+ p.get("path", ""),
132
+ p.get("cmd", ""),
133
+ p.get("label", 0),
134
+ p.get("detection_status", 0),
135
+ p.get("anomaly_score", 0.0),
136
+ p.get("top_edge", ""),
137
+ x, y, z
138
+ ])
139
+ log(f"[html_builder] CSV file: {os.path.getsize(csv_file) / (1024*1024):.1f} MB")
140
+
141
+ # Free memory
142
+ del compact_points
143
+
144
+ log(f"[html_builder] Serializing adjacency list to {os.path.basename(adj_file)}...")
145
+ with open(adj_file, "w", encoding="utf-8") as f:
146
+ json.dump(adj, f, separators=(',', ':'))
147
+ log(f"[html_builder] Adj file: {os.path.getsize(adj_file) / (1024*1024):.1f} MB")
148
+
149
+ # Pre-build the CSR adjacency index too, so See Edges / causal / attack /
150
+ # campaign are instant on first open without parsing this adj.json.
151
+ try:
152
+ from pidsmaker.vizgen.web import viz_server as _vs
153
+ _, _npz, _vocab = _vs._adj_index_paths(points_file)
154
+ _vs.build_adj_index_from_dict(adj, adj_file, _npz, _vocab)
155
+ log("[html_builder] Pre-built CSR adjacency index (instant graph tools).")
156
+ except Exception as e:
157
+ log(f"[html_builder] adj index pre-build skipped ({type(e).__name__}: {e})")
158
+
159
+ # Free memory
160
+ del adj
161
+
162
+ log(f"[html_builder] Formatting HTML template...")
163
+ html = _HTML_TEMPLATE.format(
164
+ title=title,
165
+ plotly_js=plotly_js,
166
+ points_url=os.path.basename(points_file),
167
+ adj_url=os.path.basename(adj_file),
168
+ max_tw=max_tw,
169
+ num_points=len(points),
170
+ default_hops=default_hops,
171
+ studio_css="block" if is_studio else "none",
172
+ is_studio=str(is_studio).lower(),
173
+ )
174
+
175
+ log("[html_builder] HTML template formatting complete.")
176
+ return html
177
+
178
+
179
+ _HTML_TEMPLATE = """<!DOCTYPE html>
180
+ <html lang="en">
181
+ <head>
182
+ <meta charset="UTF-8">
183
+ <title>{title}</title>
184
+ <style>
185
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
186
+ *{{margin:0;padding:0;box-sizing:border-box}}
187
+ body{{font-family:'Inter',system-ui,sans-serif;background:#000000;color:#e0e0e8;display:flex;height:100vh;overflow:hidden}}
188
+ #plot-container{{flex:3;position:relative;height:100%;display:flex;flex-direction:column}}
189
+ #plotly-div{{flex:1;width:100%}}
190
+ #slider-bar{{padding:10px 20px;background:rgba(15,15,25,0.95);border-top:1px solid rgba(100,180,255,0.1);display:flex;align-items:center;gap:14px}}
191
+ #slider-bar label{{font-size:12px;color:rgba(255,255,255,0.6);white-space:nowrap}}
192
+ #tw-slider{{flex:1;accent-color:#64b4ff}}
193
+ #tw-display{{font-size:13px;font-weight:600;color:#64b4ff;min-width:80px;text-align:center}}
194
+ #side-panel{{flex:0 0 340px;background:rgba(15,15,25,0.95);border-left:1px solid rgba(100,180,255,0.12);padding:20px;overflow-y:auto;display:flex;flex-direction:column;gap:16px;backdrop-filter:blur(12px)}}
195
+ h2{{font-size:18px;font-weight:600;color:#fff;letter-spacing:-0.3px}}
196
+ h3{{font-size:13px;font-weight:500;color:rgba(255,255,255,0.6);text-transform:uppercase;letter-spacing:0.8px;margin-bottom:8px}}
197
+ .card{{background:rgba(25,25,40,0.8);border:1px solid rgba(100,180,255,0.08);border-radius:10px;padding:14px}}
198
+ .control-row{{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;font-size:13px}}
199
+ .control-row:last-child{{margin-bottom:0}}
200
+ .control-row label{{color:rgba(255,255,255,0.7)}}
201
+ input[type="range"]{{width:100px;accent-color:#64b4ff}}
202
+ input[type="checkbox"]{{accent-color:#64b4ff;width:16px;height:16px}}
203
+ input[type="text"]{{background:rgba(255,255,255,0.06);border:1px solid rgba(100,180,255,0.15);border-radius:6px;padding:6px 10px;color:#e0e0e8;font-size:13px;width:100%;outline:none;font-family:inherit}}
204
+ input[type="text"]:focus{{border-color:rgba(100,180,255,0.4)}}
205
+ .node-info{{font-size:12px;line-height:1.7;word-break:break-all}}
206
+ .node-info b{{color:rgba(100,180,255,0.9);font-weight:500}}
207
+ .neighbor-item{{padding:6px 8px;margin-bottom:4px;background:rgba(255,255,255,0.03);border-radius:6px;font-size:11px;cursor:pointer;transition:background 0.15s}}
208
+ .neighbor-item:hover{{background:rgba(100,180,255,0.1)}}
209
+ .st-benign{{border-left:3px solid rgba(100,200,150,0.6)}}
210
+ .st-detected{{border-left:3px solid rgba(255,80,80,0.8)}}
211
+ .st-undetected{{border-left:3px solid rgba(255,165,0,0.8)}}
212
+ #header-bar{{position:absolute;top:12px;left:16px;z-index:10;font-size:12px;color:rgba(255,255,255,0.5);background:rgba(10,10,15,0.7);padding:6px 14px;border-radius:8px;backdrop-filter:blur(8px);pointer-events:none}}
213
+ .empty-state{{color:rgba(255,255,255,0.35);font-size:12px;font-style:italic}}
214
+ #inspector-scroll{{overflow-y:auto;flex-grow:1}}
215
+ .trajectory-info{{font-size:11px;color:rgba(100,180,255,0.7);margin-top:4px}}
216
+ .tw-btn{{background:rgba(100,180,255,0.15);border:1px solid rgba(100,180,255,0.25);color:#64b4ff;border-radius:6px;padding:4px 10px;font-size:11px;cursor:pointer;font-family:inherit}}
217
+ .tw-btn:hover{{background:rgba(100,180,255,0.25)}}
218
+ .tw-btn.active{{background:rgba(100,180,255,0.35);border-color:#64b4ff}}
219
+ #play-btn{{background:rgba(100,180,255,0.2);border:1px solid rgba(100,180,255,0.3);color:#64b4ff;border-radius:6px;padding:4px 12px;font-size:13px;cursor:pointer;font-family:inherit}}
220
+ #play-btn:hover{{background:rgba(100,180,255,0.3)}}
221
+ #floating-controls{{position:absolute;top:12px;right:16px;z-index:10;display:flex;gap:8px}}
222
+ .icon-btn{{background:rgba(15,15,25,0.85);border:1px solid rgba(100,180,255,0.2);color:#e0e0e8;border-radius:6px;padding:6px 12px;font-size:12px;cursor:pointer;backdrop-filter:blur(8px);transition:all 0.2s}}
223
+ .icon-btn:hover{{background:rgba(100,180,255,0.2);border-color:#64b4ff}}
224
+ .toggle-switch{{display:flex;align-items:center;gap:8px;font-size:13px;color:rgba(255,255,255,0.7)}}
225
+ #loading-overlay{{position:absolute;top:0;left:0;right:0;bottom:0;background:#000000;z-index:999;display:flex;flex-direction:column;align-items:center;justify-content:center;color:#64b4ff;font-size:18px;font-weight:600;gap:12px}}
226
+ .spinner{{width:30px;height:30px;border:3px solid rgba(100,180,255,0.2);border-top-color:#64b4ff;border-radius:50%;animation:spin 1s linear infinite}}
227
+ @keyframes spin {{ to {{ transform: rotate(360deg); }} }}
228
+ </style>
229
+ </head>
230
+ <body>
231
+ <div id="plot-container">
232
+ <div id="loading-overlay"><div class="spinner"></div><div id="loading-text">Loading WebGL Visualization Engine...</div></div>
233
+ <div id="header-bar">{title} &mdash; <span id="point-count">{num_points}</span> points &bull; <span id="tw-count">{max_tw}+1</span> time windows</div>
234
+ <div id="floating-controls">
235
+ <button class="icon-btn" onclick="resetView()" title="Reset Camera View">&#8635; Reset View</button>
236
+ </div>
237
+ <div id="plotly-div"></div>
238
+ <div id="slider-bar">
239
+ <button id="play-btn" onclick="togglePlay()">&#9654;</button>
240
+ <label>Time Window:</label>
241
+ <input type="range" id="tw-slider" min="-1" max="{max_tw}" value="-1" step="1">
242
+ <span id="tw-display">All</span>
243
+ </div>
244
+ </div>
245
+ <div id="side-panel">
246
+ <h2>Node Inspector</h2>
247
+ <div class="card">
248
+ <h3>Controls</h3>
249
+ <div class="control-row">
250
+ <label for="hop-slider">Hops (<span id="hop-val">{default_hops}</span>):</label>
251
+ <input type="range" id="hop-slider" min="0" max="3" value="{default_hops}">
252
+ </div>
253
+ <div class="control-row" style="margin-top: 12px; padding-top: 12px; border-top: 1px solid rgba(255,255,255,0.1);">
254
+ <label class="toggle-switch">
255
+ <input type="checkbox" id="mode-toggle" onchange="toggleMode()" checked>
256
+ <span>3D Temporal Mode</span>
257
+ </label>
258
+ </div>
259
+ </div>
260
+ <div class="card" id="umap-settings" style="display:{studio_css}">
261
+ <h3>UMAP Settings (Studio)</h3>
262
+ <div class="control-row">
263
+ <label>Neighbors:</label>
264
+ <input type="range" id="studio-knn" min="5" max="50" value="15" oninput="document.getElementById('knn-val').innerText=this.value">
265
+ <span id="knn-val" style="color:#64b4ff">15</span>
266
+ </div>
267
+ <div class="control-row">
268
+ <label>Min Dist:</label>
269
+ <input type="range" id="studio-md" min="0" max="1" step="0.05" value="0.1" oninput="document.getElementById('md-val').innerText=this.value">
270
+ <span id="md-val" style="color:#64b4ff">0.1</span>
271
+ </div>
272
+ <button id="recalc-btn" class="icon-btn" style="width:100%;margin-top:10px;background:#1d4ed8;border:none" onclick="recalcUmap()">Recalculate UMAP</button>
273
+ </div>
274
+ <div class="card">
275
+ <h3>Filter</h3>
276
+ <div class="control-row"><label><input type="checkbox" id="cb-benign" checked> Benign</label></div>
277
+ <div class="control-row"><label><input type="checkbox" id="cb-detected" checked> Detected</label></div>
278
+ <div class="control-row"><label><input type="checkbox" id="cb-undetected" checked> Undetected</label></div>
279
+ </div>
280
+ <div class="card">
281
+ <h3>Search</h3>
282
+ <input type="text" id="search-box" placeholder="Node ID or path...">
283
+ </div>
284
+ <div id="inspector-scroll">
285
+ <div id="inspector-content"></div>
286
+ </div>
287
+ </div>
288
+ <script>{plotly_js}</script>
289
+ <script>
290
+ let points = [];
291
+ let adj = {{}};
292
+ const maxTW = {max_tw};
293
+
294
+ // Index: node_id -> list of point indices
295
+ const nodeIndex = {{}};
296
+ let allTWs = [];
297
+
298
+ async function _loadData() {{
299
+ const txt = document.getElementById('loading-text');
300
+ try {{
301
+ txt.innerText = "Downloading point data...";
302
+ const pRes = await fetch('{points_url}');
303
+ const pTotal = parseInt(pRes.headers.get('content-length') || '0');
304
+ if (pTotal > 0) {{
305
+ const reader = pRes.body.getReader();
306
+ const chunks = [];
307
+ let received = 0;
308
+ while (true) {{
309
+ const {{done, value}} = await reader.read();
310
+ if (done) break;
311
+ chunks.push(value);
312
+ received += value.length;
313
+ txt.innerText = `Downloading points: ${{(received/1024/1024).toFixed(1)}} / ${{(pTotal/1024/1024).toFixed(1)}} MB`;
314
+ }}
315
+ const blob = new Blob(chunks);
316
+ const text = await blob.text();
317
+ txt.innerText = "Parsing point data...";
318
+ points = JSON.parse(text);
319
+ }} else {{
320
+ points = await pRes.json();
321
+ }}
322
+ // Ensure cmd field exists on all points and unpack coords_hops into p.x/p.y/p.z
323
+ points.forEach(p => {{
324
+ if (!p.cmd) p.cmd = '';
325
+ const c = (p.coords_hops && p.coords_hops[0]) || [0,0,0];
326
+ p.x = c[0]; p.y = c[1]; p.z = c[2];
327
+ }});
328
+
329
+ txt.innerText = "Downloading graph topology...";
330
+ const aRes = await fetch('{adj_url}');
331
+ adj = await aRes.json();
332
+
333
+ txt.innerText = `Indexing ${{points.length.toLocaleString()}} nodes...`;
334
+
335
+ points.forEach((p,i) => {{
336
+ if (!nodeIndex[p.node_id]) nodeIndex[p.node_id] = [];
337
+ nodeIndex[p.node_id].push(i);
338
+ }});
339
+
340
+ allTWs = [...new Set(points.map(p => p.tw_idx))].sort((a,b) => a-b);
341
+ document.getElementById('tw-count').textContent = allTWs.length;
342
+
343
+ txt.innerText = "Rendering...";
344
+ // Use requestAnimationFrame to let the browser paint the status before heavy render
345
+ requestAnimationFrame(() => {{
346
+ _initApp();
347
+ document.getElementById('loading-overlay').style.display = 'none';
348
+ }});
349
+ }} catch (e) {{
350
+ txt.innerText = "Failed to load data: " + e.message;
351
+ console.error(e);
352
+ }}
353
+ }}
354
+
355
+ async function recalcUmap() {{
356
+ const knn = document.getElementById('studio-knn').value;
357
+ const md = document.getElementById('studio-md').value;
358
+ const btn = document.getElementById('recalc-btn');
359
+ const overlay = document.getElementById('loading-overlay');
360
+ const txt = document.getElementById('loading-text');
361
+
362
+ btn.disabled = true;
363
+ overlay.style.display = 'flex';
364
+ txt.innerText = "Sending recalculation request...";
365
+
366
+ try {{
367
+ const res = await fetch('/api/recalculate', {{
368
+ method: 'POST',
369
+ headers: {{ 'Content-Type': 'application/json' }},
370
+ body: JSON.stringify({{ n_neighbors: parseInt(knn), min_dist: parseFloat(md) }})
371
+ }});
372
+
373
+ if (res.ok) {{
374
+ pollStudioStatus();
375
+ }} else {{
376
+ txt.innerText = "Error starting recalculation.";
377
+ setTimeout(() => overlay.style.display = 'none', 2000);
378
+ btn.disabled = false;
379
+ }}
380
+ }} catch(e) {{
381
+ txt.innerText = "Connection error.";
382
+ setTimeout(() => overlay.style.display = 'none', 2000);
383
+ btn.disabled = false;
384
+ }}
385
+ }}
386
+
387
+ function pollStudioStatus() {{
388
+ const txt = document.getElementById('loading-text');
389
+ const overlay = document.getElementById('loading-overlay');
390
+ const btn = document.getElementById('recalc-btn');
391
+
392
+ fetch('/api/status').then(r => r.json()).then(data => {{
393
+ if (data.status === 'running') {{
394
+ txt.innerText = data.progress || "Calculating UMAP...";
395
+ setTimeout(pollStudioStatus, 500);
396
+ }} else if (data.status === 'idle') {{
397
+ txt.innerText = "Reloading new data...";
398
+ // Reload points dynamically
399
+ fetch('{points_url}').then(r => r.json()).then(newPoints => {{
400
+ points = newPoints;
401
+ points.forEach(p => {{
402
+ if (!p.cmd) p.cmd = '';
403
+ const c = (p.coords_hops && p.coords_hops[0]) || [0,0,0];
404
+ p.x = c[0]; p.y = c[1]; p.z = c[2];
405
+ }});
406
+ nodeIndex = {{}};
407
+ points.forEach((p,i) => {{
408
+ if (!nodeIndex[p.node_id]) nodeIndex[p.node_id] = [];
409
+ nodeIndex[p.node_id].push(i);
410
+ }});
411
+ requestAnimationFrame(() => {{
412
+ _initApp();
413
+ overlay.style.display = 'none';
414
+ btn.disabled = false;
415
+ }});
416
+ }});
417
+ }} else {{
418
+ txt.innerText = "Error: " + data.progress;
419
+ setTimeout(() => overlay.style.display = 'none', 3000);
420
+ btn.disabled = false;
421
+ }}
422
+ }});
423
+ }}
424
+
425
+ // We wrap the remaining synchronous initialization code into _initApp
426
+ function _initApp() {{
427
+
428
+
429
+ const C = {{
430
+ benign: 'rgba(50, 200, 100, 0.25)', // Green, transparent
431
+ det_process: 'rgba(255, 51, 51, 0.7)', // Red
432
+ det_netflow: 'rgba(51, 102, 255, 0.7)', // Blue
433
+ det_file: 'rgba(255, 204, 0, 0.7)', // Yellow
434
+ undet_process: 'rgba(255, 153, 51, 0.7)', // Orange
435
+ undet_netflow: 'rgba(51, 204, 255, 0.7)', // Cyan
436
+ undet_file: 'rgba(255, 255, 102, 0.7)', // Light Yellow
437
+ benignHi: 'rgba(51, 204, 102, 0.9)',
438
+ dimmed: 'rgba(40, 45, 50, 0.05)',
439
+ selected: 'rgba(255, 255, 255, 1.0)',
440
+ }};
441
+
442
+ function getColor(p) {{
443
+ if (p.label === 1) {{
444
+ const t = (p.type || '').toLowerCase();
445
+ if (p.detection_status === 1 || p.detection_status === 0) {{ // Detected or W2V GT
446
+ if (t.includes('process') || t.includes('subject')) return C.det_process;
447
+ if (t.includes('netflow')) return C.det_netflow;
448
+ if (t.includes('file')) return C.det_file;
449
+ return C.det_process; // fallback
450
+ }} else {{ // Undetected
451
+ if (t.includes('process') || t.includes('subject')) return C.undet_process;
452
+ if (t.includes('netflow')) return C.undet_netflow;
453
+ if (t.includes('file')) return C.undet_file;
454
+ return C.undet_process; // fallback
455
+ }}
456
+ }}
457
+ return C.benign;
458
+ }}
459
+ function getSize(p) {{
460
+ return 5;
461
+ }}
462
+
463
+ let currentTW = -1; // -1 = all
464
+ let selectedNodeId = null;
465
+ let activeTraceNodes = null;
466
+ let playing = false;
467
+ let playTimer = null;
468
+ let is3D = true;
469
+
470
+ function getVisiblePoints() {{
471
+ return points.filter(p => {{
472
+ if (currentTW >= 0 && p.tw_idx !== currentTW) return false;
473
+ return true;
474
+ }});
475
+ }}
476
+
477
+ function buildTraces(dimNodeId) {{
478
+ const vis = getVisiblePoints();
479
+ const cats = [
480
+ {{name:'Benign', color: C.benign, filter: p => p.label===0, show: document.getElementById('cb-benign').checked}},
481
+ {{name:'Det. Process', color: C.det_process, filter: p => p.label===1 && (p.detection_status===1||p.detection_status===0) && ((p.type || '').toLowerCase().includes('process') || (p.type || '').toLowerCase().includes('subject')), show: document.getElementById('cb-detected').checked}},
482
+ {{name:'Det. Netflow', color: C.det_netflow, filter: p => p.label===1 && (p.detection_status===1||p.detection_status===0) && (p.type || '').toLowerCase().includes('netflow'), show: document.getElementById('cb-detected').checked}},
483
+ {{name:'Det. File', color: C.det_file, filter: p => p.label===1 && (p.detection_status===1||p.detection_status===0) && (p.type || '').toLowerCase().includes('file'), show: document.getElementById('cb-detected').checked}},
484
+ {{name:'Undet. Process', color: C.undet_process, filter: p => p.label===1 && p.detection_status===2 && ((p.type || '').toLowerCase().includes('process') || (p.type || '').toLowerCase().includes('subject')), show: document.getElementById('cb-undetected').checked}},
485
+ {{name:'Undet. Netflow', color: C.undet_netflow, filter: p => p.label===1 && p.detection_status===2 && (p.type || '').toLowerCase().includes('netflow'), show: document.getElementById('cb-undetected').checked}},
486
+ {{name:'Undet. File', color: C.undet_file, filter: p => p.label===1 && p.detection_status===2 && (p.type || '').toLowerCase().includes('file'), show: document.getElementById('cb-undetected').checked}},
487
+ ];
488
+ const traces = [];
489
+ const isDimmed = dimNodeId !== null;
490
+ const traceType = is3D ? 'scatter3d' : 'scattergl';
491
+
492
+ const hops = parseInt(document.getElementById('hop-slider').value) || 0;
493
+ const activeNeighbors = isDimmed && hops > 0 ? getKHopNeighbors(dimNodeId, hops) : [];
494
+
495
+ cats.forEach(cat => {{
496
+ const pts = vis.filter(cat.filter);
497
+ if (pts.length === 0) return;
498
+
499
+ const colors = pts.map(p => {{
500
+ if (activeTraceNodes) {{
501
+ return activeTraceNodes.has(p.node_id) ? cat.color : C.dimmed;
502
+ }}
503
+ return cat.color;
504
+ }});
505
+
506
+ const opacities = pts.map(p => {{
507
+ if (activeTraceNodes) {{
508
+ return activeTraceNodes.has(p.node_id) ? 1.0 : 0.05;
509
+ }}
510
+ return cat.name === 'Benign' ? (is3D ? 0.25 : 0.3) : (is3D ? 0.7 : 0.75);
511
+ }});
512
+
513
+ const trace = {{
514
+ x: pts.map(p=>p.x), y: pts.map(p=>p.y),
515
+ customdata: pts.map(p => p.node_id),
516
+ mode:'markers', type: traceType, name:cat.name,
517
+ visible: cat.show ? true : 'legendonly',
518
+ hoverinfo:'text',
519
+ marker: {{
520
+ size: cat.name === 'Benign' ? (is3D ? 2 : 2.5) : (is3D ? 3.5 : 4),
521
+ color: colors,
522
+ line: {{width:0}},
523
+ opacity: opacities,
524
+ }},
525
+ }};
526
+ // Only generate hover text for small traces or malicious — saves huge memory for benign
527
+ if (pts.length < 50000 || cat.name !== 'Benign') {{
528
+ trace.text = pts.map(p => `ID:${{p.node_id}} | ${{p.type}} | ${{(p.path||'').substring(0,40)}}<br>TW:${{p.tw_label}}`);
529
+ }} else {{
530
+ trace.hoverinfo = 'skip'; // Skip hover for huge benign traces
531
+ }}
532
+ if (is3D) trace.z = pts.map(p=>p.z);
533
+ traces.push(trace);
534
+ }});
535
+
536
+ // If a node is selected, add ghost markers for ALL its TW appearances (even filtered ones)
537
+ if (dimNodeId !== null) {{
538
+ const allAppearances = (nodeIndex[dimNodeId] || []).map(i => points[i]);
539
+ if (allAppearances.length > 1) {{
540
+ const sorted = allAppearances.sort((a,b) => a.tw_idx - b.tw_idx);
541
+ // Ghost trail dots
542
+ const lineTrace = {{
543
+ x: sorted.map(p=>p.x), y: sorted.map(p=>p.y),
544
+ text: sorted.map(p => `TW:${{p.tw_label}} pos(${{p.x.toFixed(3)}}, ${{p.y.toFixed(3)}})`),
545
+ mode:'markers+lines', type: traceType, name:'Trajectory',
546
+ showlegend:false, hoverinfo:'text',
547
+ line: {{color:'rgba(100,180,255,0.4)', width:2, dash:'dot'}},
548
+ marker: {{size:is3D?5:8, color:'rgba(100,180,255,0.8)', symbol:'diamond', line:{{width:0}}}},
549
+ }};
550
+ if (is3D) lineTrace.z = sorted.map(p=>p.z);
551
+ traces.push(lineTrace);
552
+ }}
553
+ }}
554
+
555
+
556
+ // Subtle XYZ axis lines at the origin for 3D spatial reference
557
+ if (is3D) {{
558
+ const axLen = 15;
559
+ traces.push({{ x: [-axLen, axLen], y: [0, 0], z: [0, 0], mode: 'lines', line: {{color: 'rgba(255,80,80,0.25)', width: 1.5}}, showlegend: false, hoverinfo: 'skip', type: 'scatter3d' }});
560
+ traces.push({{ x: [0, 0], y: [-axLen, axLen], z: [0, 0], mode: 'lines', line: {{color: 'rgba(80,255,80,0.25)', width: 1.5}}, showlegend: false, hoverinfo: 'skip', type: 'scatter3d' }});
561
+ traces.push({{ x: [0, 0], y: [0, 0], z: [-axLen, axLen], mode: 'lines', line: {{color: 'rgba(80,80,255,0.25)', width: 1.5}}, showlegend: false, hoverinfo: 'skip', type: 'scatter3d' }});
562
+ }}
563
+
564
+ // Mother Node Star
565
+ if (dimNodeId !== null && vis.length > 0) {{
566
+ const motherPt = vis.find(p => p.node_id === dimNodeId);
567
+ if (motherPt) {{
568
+ const starTrace = {{
569
+ x: [motherPt.x], y: [motherPt.y],
570
+ text: [`<b>[INITIAL STATE]</b><br>ID:${{motherPt.node_id}} | ${{motherPt.type}} | ${{motherPt.path.substring(0,40)}}`],
571
+ mode: 'markers', type: traceType, name: 'Selected Node',
572
+ showlegend: false, hoverinfo: 'text',
573
+ marker: {{ size: is3D ? 10 : 15, color: '#00ffff', symbol: is3D ? 'diamond' : 'star', line: {{color: 'white', width: 1}} }}
574
+ }};
575
+ if (is3D) starTrace.z = [motherPt.z];
576
+ traces.push(starTrace);
577
+ }}
578
+ }}
579
+
580
+ return traces;
581
+ }}
582
+
583
+ function getLayout() {{
584
+ if (is3D) {{
585
+ return {{
586
+ scene: {{
587
+ xaxis: {{visible: false, showgrid: false, zeroline: false}},
588
+ yaxis: {{visible: false, showgrid: false, zeroline: false}},
589
+ zaxis: {{visible: false, showgrid: false, zeroline: false}},
590
+ bgcolor: '#000000',
591
+ camera: typeof cameraState !== 'undefined' ? cameraState : {{eye: {{x: 1.25, y: 1.25, z: 1.25}}}}
592
+ }},
593
+ plot_bgcolor:'#000000',
594
+ paper_bgcolor:'#000000',
595
+ font: {{color:'#e0e0e8', family:'Inter'}},
596
+ showlegend:true,
597
+ legend: {{x:0.01, y:0.99, bgcolor:'rgba(15,15,25,0.7)', bordercolor:'rgba(100,180,255,0.1)', borderwidth:1, font:{{size:11}}}},
598
+ margin: {{l:0,r:0,t:0,b:0}},
599
+ dragmode: 'turntable'
600
+ }};
601
+ }} else {{
602
+ return {{
603
+ xaxis: {{visible: false, showgrid: false, zeroline: false}},
604
+ yaxis: {{visible: false, showgrid: false, zeroline: false, scaleanchor:'x'}},
605
+ plot_bgcolor:'#000000',
606
+ paper_bgcolor:'#000000',
607
+ font: {{color:'#e0e0e8', family:'Inter'}},
608
+ showlegend:true,
609
+ legend: {{x:0.01, y:0.99, bgcolor:'rgba(15,15,25,0.7)', bordercolor:'rgba(100,180,255,0.1)', borderwidth:1, font:{{size:11}}}},
610
+ margin: {{l:0,r:0,t:0,b:0}},
611
+ dragmode:'pan',
612
+ }};
613
+ }}
614
+ }}
615
+
616
+ const config = {{scrollZoom:true, responsive:true, displaylogo:false, modeBarButtonsToRemove:['toImage','lasso2d','select2d','resetCameraDefault3d','hoverClosest3d']}};
617
+ let cameraState = {{eye: {{x: 1.5, y: 1.5, z: 0.5}}, center: {{x:0, y:0, z:0}}, up: {{x:0, y:0, z:1}}}};
618
+ let autoRotateTimer = null;
619
+ let isInteracting = false;
620
+
621
+ // Precompute Global Stats
622
+ const uniqueNodes = new Map();
623
+ points.forEach(p => {{
624
+ if (!uniqueNodes.has(p.node_id)) {{
625
+ uniqueNodes.set(p.node_id, p);
626
+ }}
627
+ }});
628
+ const uNodes = Array.from(uniqueNodes.values());
629
+ const globalStats = {{
630
+ total: uNodes.length,
631
+ benign: uNodes.filter(p => p.label === 0).length,
632
+ malicious: uNodes.filter(p => p.label === 1).length,
633
+ mal_process: uNodes.filter(p => p.label === 1 && ((p.type||'').toLowerCase().includes('process') || (p.type||'').toLowerCase().includes('subject'))).length,
634
+ mal_netflow: uNodes.filter(p => p.label === 1 && (p.type||'').toLowerCase().includes('netflow')).length,
635
+ mal_file: uNodes.filter(p => p.label === 1 && (p.type||'').toLowerCase().includes('file')).length,
636
+ }};
637
+
638
+ function getGlobalStatsHtml() {{
639
+ let html = '<div class="card">';
640
+ html += `<h3>Global Statistics</h3>`;
641
+ html += `<p style="margin-top:0;font-size:13px;color:#aaa;">Overall unique nodes present in this dataset projection.</p>`;
642
+ html += `<div style="display:flex; justify-content:space-between; margin-bottom:4px"><span>Total Nodes:</span> <b>${{globalStats.total}}</b></div>`;
643
+ html += `<div style="display:flex; justify-content:space-between; margin-bottom:4px; color:${{C.benign}}"><span>Benign Nodes:</span> <b>${{globalStats.benign}}</b></div>`;
644
+ html += `<div style="display:flex; justify-content:space-between; margin-bottom:12px; color:${{C.det_process}}"><span>Malicious Nodes:</span> <b>${{globalStats.malicious}}</b></div>`;
645
+ if (globalStats.malicious > 0) {{
646
+ html += `<div style="font-size:12px; margin-left:12px; border-left:2px solid #555; padding-left:8px;">`;
647
+ html += `<div style="display:flex; justify-content:space-between; margin-bottom:4px; color:${{C.det_process}}"><span>Processes:</span> <span>${{globalStats.mal_process}}</span></div>`;
648
+ html += `<div style="display:flex; justify-content:space-between; margin-bottom:4px; color:${{C.det_netflow}}"><span>Netflows:</span> <span>${{globalStats.mal_netflow}}</span></div>`;
649
+ html += `<div style="display:flex; justify-content:space-between; margin-bottom:4px; color:${{C.det_file}}"><span>Files:</span> <span>${{globalStats.mal_file}}</span></div>`;
650
+ html += `</div>`;
651
+ }}
652
+ html += '</div>';
653
+ return html;
654
+ }}
655
+
656
+ Plotly.newPlot('plotly-div', buildTraces(null), getLayout(), config);
657
+ const plotDiv = document.getElementById('plotly-div');
658
+ document.getElementById('inspector-content').innerHTML = getGlobalStatsHtml();
659
+
660
+ function startAutoRotate() {{
661
+ if (autoRotateTimer) clearInterval(autoRotateTimer);
662
+ autoRotateTimer = setInterval(() => {{
663
+ if (!is3D || isInteracting) return;
664
+ const angle = 0.003;
665
+ const cx = cameraState.eye.x;
666
+ const cy = cameraState.eye.y;
667
+ cameraState = {{
668
+ ...cameraState,
669
+ eye: {{
670
+ x: cx * Math.cos(angle) - cy * Math.sin(angle),
671
+ y: cx * Math.sin(angle) + cy * Math.cos(angle),
672
+ z: cameraState.eye.z
673
+ }}
674
+ }};
675
+ Plotly.relayout('plotly-div', {{'scene.camera': cameraState}});
676
+ }}, 50);
677
+ }}
678
+
679
+ function stopAutoRotate() {{
680
+ if (autoRotateTimer) {{
681
+ clearInterval(autoRotateTimer);
682
+ autoRotateTimer = null;
683
+ }}
684
+ }}
685
+
686
+ plotDiv.on('plotly_relayout', function(eventData) {{
687
+ if (eventData['scene.camera']) {{
688
+ cameraState = eventData['scene.camera'];
689
+ }}
690
+ }});
691
+
692
+ plotDiv.addEventListener('mousedown', () => {{ isInteracting = true; stopAutoRotate(); }});
693
+ plotDiv.addEventListener('mouseup', () => {{ isInteracting = false; }});
694
+ plotDiv.addEventListener('wheel', () => {{ isInteracting = true; stopAutoRotate(); }});
695
+
696
+ plotDiv.on('plotly_click', function(data) {{
697
+ if (!data.points.length) return;
698
+ const nid = data.points[0].customdata;
699
+ if (nid === undefined || nid === null) return;
700
+ selectNode(nid);
701
+ }});
702
+
703
+ function selectNode(nid) {{
704
+ selectedNodeId = nid;
705
+ Plotly.react('plotly-div', buildTraces(nid), getLayout(), config);
706
+ updateInspector(nid);
707
+ }}
708
+
709
+ function clearSelection() {{
710
+ selectedNodeId = null;
711
+ activeTraceNodes = null;
712
+ Plotly.react('plotly-div', buildTraces(null), getLayout(), config);
713
+ document.getElementById('inspector-content').innerHTML = getGlobalStatsHtml();
714
+ }}
715
+
716
+ function refresh() {{
717
+ Plotly.react('plotly-div', buildTraces(selectedNodeId), getLayout(), config);
718
+ if (selectedNodeId !== null) updateInspector(selectedNodeId);
719
+ }}
720
+
721
+ function resetView() {{
722
+ if (is3D) {{
723
+ cameraState = {{eye: {{x: 1.5, y: 1.5, z: 0.5}}, center: {{x:0, y:0, z:0}}, up: {{x:0, y:0, z:1}}}};
724
+ Plotly.relayout('plotly-div', {{'scene.camera': cameraState}});
725
+ }} else {{
726
+ Plotly.relayout('plotly-div', {{
727
+ 'xaxis.autorange': true,
728
+ 'yaxis.autorange': true
729
+ }});
730
+ }}
731
+ }}
732
+
733
+ function toggleMode() {{
734
+ is3D = document.getElementById('mode-toggle').checked;
735
+ Plotly.newPlot('plotly-div', buildTraces(selectedNodeId), getLayout(), config);
736
+ if (is3D) {{
737
+ startAutoRotate();
738
+ }} else {{
739
+ stopAutoRotate();
740
+ }}
741
+ }}
742
+
743
+ // Time slider
744
+ const twSlider = document.getElementById('tw-slider');
745
+ const twDisplay = document.getElementById('tw-display');
746
+
747
+ twSlider.addEventListener('input', function() {{
748
+ currentTW = parseInt(this.value);
749
+ if (currentTW < 0) {{
750
+ twDisplay.textContent = 'All';
751
+ }} else {{
752
+ const twLabel = allTWs.includes(currentTW) ? points.find(p=>p.tw_idx===currentTW)?.tw_label || ('TW '+currentTW) : 'TW '+currentTW;
753
+ twDisplay.textContent = twLabel;
754
+ }}
755
+ refresh();
756
+ }});
757
+
758
+ // Play/pause
759
+ function togglePlay() {{
760
+ playing = !playing;
761
+ document.getElementById('play-btn').textContent = playing ? '⏸' : '▶';
762
+ if (playing) {{
763
+ let idx = allTWs.indexOf(currentTW);
764
+ if (idx < 0) idx = 0;
765
+ playTimer = setInterval(() => {{
766
+ idx = (idx + 1) % allTWs.length;
767
+ currentTW = allTWs[idx];
768
+ twSlider.value = currentTW;
769
+ const twLabel = points.find(p=>p.tw_idx===currentTW)?.tw_label || ('TW '+currentTW);
770
+ twDisplay.textContent = twLabel;
771
+ refresh();
772
+ }}, 1000);
773
+ }} else {{
774
+ clearInterval(playTimer);
775
+ }}
776
+ }}
777
+
778
+ // Inspector
779
+ function updateInspector(nid) {{
780
+ const idxs = nodeIndex[nid] || [];
781
+ const p0 = idxs.length ? points[idxs[0]] : null;
782
+ if (!p0) return;
783
+ const tws = idxs.map(i => points[i]).sort((a,b) => a.tw_idx - b.tw_idx);
784
+
785
+ let html = '<div class="card node-info">';
786
+ html += `<button class="icon-btn" onclick="clearSelection()" style="float:right; padding:4px 8px; margin-top:-4px;">&times; Deselect</button>`;
787
+ html += `<b>ID:</b> ${{nid}}<br>`;
788
+ html += `<b>Type:</b> ${{p0.type}}<br>`;
789
+ html += `<b>Path:</b> ${{p0.path}}<br>`;
790
+ if (p0.cmd) html += `<b>Cmd:</b> ${{p0.cmd}}<br>`;
791
+ html += `<b>Label:</b> ${{p0.label === 1 ? '<span style="color:'+getColor(p0)+'">Malicious</span>' : 'Benign'}}<br>`;
792
+ if (p0.detection_status === 1) html += `<b>Detection:</b> <span style="color:${{getColor(p0)}}">Detected</span><br>`;
793
+ else if (p0.detection_status === 2) html += `<b>Detection:</b> <span style="color:${{getColor(p0)}}">Undetected</span><br>`;
794
+ html += `<b>Appearances:</b> ${{tws.length}} time windows<br>`;
795
+ html += '</div>';
796
+
797
+ html += `<div class="card"><h3>Causal Tracing</h3>`;
798
+ html += `<p style="font-size:11px;color:#aaa;margin-bottom:8px">Isolate the temporal impact (forward) and origin (backward) of this node.</p>`;
799
+ if (activeTraceNodes) {{
800
+ html += `<button class="icon-btn" style="width:100%;background:rgba(255,80,80,0.2)" onclick="activeTraceNodes=null;refresh();updateInspector(${{nid}})">Clear Causal Trace</button>`;
801
+ html += `<div style="margin-top:8px;font-size:12px;color:#64b4ff">Isolated ${{activeTraceNodes.size}} causally linked nodes.</div>`;
802
+ }} else {{
803
+ html += `<button class="icon-btn" style="width:100%;background:rgba(100,180,255,0.2)" onclick="performCausalTrace(${{nid}})">Trace Causal Chain</button>`;
804
+ }}
805
+ html += `</div>`;
806
+
807
+ // Temporal trajectory with clickable TW buttons
808
+ html += '<div class="card"><h3>Temporal Trajectory</h3>';
809
+ html += '<div style="display:flex;flex-wrap:wrap;gap:4px;margin-bottom:8px">';
810
+ html += `<button class="tw-btn ${{currentTW<0?'active':''}}" onclick="twSlider.value=-1;twSlider.dispatchEvent(new Event('input'))">All</button>`;
811
+ tws.forEach(tw => {{
812
+ html += `<button class="tw-btn ${{currentTW===tw.tw_idx?'active':''}}" onclick="twSlider.value=${{tw.tw_idx}};twSlider.dispatchEvent(new Event('input'))">TW ${{tw.tw_idx}}</button>`;
813
+ }});
814
+ html += '</div>';
815
+ tws.forEach(tw => {{
816
+ html += `<div class="trajectory-info">TW ${{tw.tw_idx}} &mdash; ${{tw.tw_label}} &bull; (${{tw.x.toFixed(3)}}, ${{tw.y.toFixed(3)}})</div>`;
817
+ }});
818
+ html += '</div>';
819
+
820
+ // Neighbors
821
+ const hops = parseInt(document.getElementById('hop-slider').value);
822
+ if (hops > 0) {{
823
+ const neighbors = getKHopNeighbors(nid, hops);
824
+ html += '<div class="card"><h3>Neighbors (' + hops + '-hop, ' + neighbors.length + ' nodes)</h3>';
825
+ neighbors.slice(0, 50).forEach(nbr => {{
826
+ const nbr_pts = nodeIndex[nbr] || [];
827
+ if (!nbr_pts.length) return;
828
+ const np0 = points[nbr_pts[0]];
829
+ html += `<div class="neighbor-item" style="border-left:3px solid ${{getColor(np0)}}" onclick="selectNode(${{nbr}})">${{np0.type}}: ${{np0.path.substring(0,30)}} (ID:${{nbr}})</div>`;
830
+ }});
831
+ if (neighbors.length > 50) html += `<div class="empty-state">... and ${{neighbors.length - 50}} more</div>`;
832
+ html += '</div>';
833
+ }}
834
+
835
+ document.getElementById('inspector-content').innerHTML = html;
836
+ }}
837
+
838
+ function getKHopNeighbors(nid, k) {{
839
+ const visited = new Set([nid]);
840
+ let frontier = [nid];
841
+ for (let h = 0; h < k; h++) {{
842
+ const next = [];
843
+ frontier.forEach(n => {{
844
+ (adj[String(n)] || []).forEach(edge => {{
845
+ if (!visited.has(edge.nb)) {{ visited.add(edge.nb); next.push(edge.nb); }}
846
+ }});
847
+ }});
848
+ frontier = next;
849
+ }}
850
+ visited.delete(nid);
851
+ return [...visited];
852
+ }}
853
+
854
+ function getCausalTrace(nid) {{
855
+ const traceNodes = new Set([nid]);
856
+
857
+ // Forward BFS
858
+ let forwardQ = [];
859
+ (adj[String(nid)] || []).forEach(edge => {{
860
+ if (edge.dir === 'out') forwardQ.push({{node: edge.nb, time: edge.t}});
861
+ }});
862
+ const visitedFwd = new Set();
863
+
864
+ while(forwardQ.length > 0) {{
865
+ const curr = forwardQ.shift();
866
+ const stateKey = `${{curr.node}}-${{curr.time}}`;
867
+ if (visitedFwd.has(stateKey)) continue;
868
+ visitedFwd.add(stateKey);
869
+ traceNodes.add(curr.node);
870
+
871
+ (adj[String(curr.node)] || []).forEach(edge => {{
872
+ if (edge.dir === 'out' && edge.t >= curr.time) {{
873
+ forwardQ.push({{node: edge.nb, time: edge.t}});
874
+ }}
875
+ }});
876
+ }}
877
+
878
+ // Backward BFS
879
+ let backwardQ = [];
880
+ (adj[String(nid)] || []).forEach(edge => {{
881
+ if (edge.dir === 'in') backwardQ.push({{node: edge.nb, time: edge.t}});
882
+ }});
883
+ const visitedBwd = new Set();
884
+
885
+ while(backwardQ.length > 0) {{
886
+ const curr = backwardQ.shift();
887
+ const stateKey = `${{curr.node}}-${{curr.time}}`;
888
+ if (visitedBwd.has(stateKey)) continue;
889
+ visitedBwd.add(stateKey);
890
+ traceNodes.add(curr.node);
891
+
892
+ (adj[String(curr.node)] || []).forEach(edge => {{
893
+ if (edge.dir === 'in' && edge.t <= curr.time) {{
894
+ backwardQ.push({{node: edge.nb, time: edge.t}});
895
+ }}
896
+ }});
897
+ }}
898
+
899
+ return traceNodes;
900
+ }}
901
+
902
+ function performCausalTrace(nid) {{
903
+ activeTraceNodes = getCausalTrace(nid);
904
+ refresh();
905
+ updateInspector(nid);
906
+ }}
907
+
908
+ // Controls
909
+ document.getElementById('hop-slider').addEventListener('input', e => {{
910
+ document.getElementById('hop-val').textContent = e.target.value;
911
+ if (selectedNodeId !== null) updateInspector(selectedNodeId);
912
+ }});
913
+ ['cb-benign','cb-detected','cb-undetected'].forEach(id => {{
914
+ document.getElementById(id).addEventListener('change', refresh);
915
+ }});
916
+
917
+ // Search
918
+ document.getElementById('search-box').addEventListener('input', function() {{
919
+ const q = this.value.trim().toLowerCase();
920
+ if (!q) {{ clearSelection(); return; }}
921
+ const numId = parseInt(q);
922
+ if (!isNaN(numId) && nodeIndex[numId]) {{ selectNode(numId); return; }}
923
+ for (const p of points) {{
924
+ if (p.path.toLowerCase().includes(q) || p.cmd.toLowerCase().includes(q)) {{
925
+ selectNode(p.node_id); return;
926
+ }}
927
+ }}
928
+ }});
929
+
930
+ document.addEventListener('keydown', e => {{ if (e.key === 'Escape') clearSelection(); }});
931
+
932
+ }} // end _initApp()
933
+ _loadData();
934
+ </script>
935
+ </body>
936
+ </html>"""