Skip to content

Environment API

parallel_env

NetForgeRLEnv

Bases: BaseNetForgeRLEnv, EpisodeMetricsMixin, ObservationMixin

PettingZoo-style MARL environment for the NetForge cybersecurity sim.

Source code in netforge_rl\environment\parallel_env.py
 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
class NetForgeRLEnv(BaseNetForgeRLEnv, EpisodeMetricsMixin, ObservationMixin):
    """PettingZoo-style MARL environment for the NetForge cybersecurity sim."""

    metadata = {'render_modes': ['ansi', 'rgb_array'], 'name': 'netforge_rl_v3'}

    def __init__(self, scenario_config: dict):
        cfg = scenario_config or {}
        self.network_generator = NetworkGenerator(
            config_path=cfg.get('topology_path'),
            max_active_hosts=cfg.get('max_active_hosts'),
            evaluation_mode=cfg.get('evaluation_mode', False),
        )
        self.log_latency = cfg.get('log_latency', 0)
        self.dhcp_interval = cfg.get('dhcp_interval', 40)
        self.record_siem = cfg.get('record_siem', False)
        self.green_agent = GreenAgent()
        self.possible_agents = [
            'red_operator',
            'blue_dmz',
            'blue_internal',
            'blue_restricted',
        ]
        self.agents = self.possible_agents[:]
        scenario_cls = get_scenario_class(cfg.get('scenario_type', 'ransomware'))
        self.scenario = scenario_cls(self.agents)

        self.global_state = self.network_generator.generate()
        self.resolution_engine = ConflictResolutionEngine()

        self.docker_bridge = DockerBridge(mode=cfg.get('docker_mode', 'sim'))
        self.global_state.docker_bridge = self.docker_bridge

        self.siem_logger = SIEMLogger()
        self.log_encoder = LogEncoder(backend=cfg.get('nlp_backend', 'tfidf'))
        self.topology_engine = TopologyEventEngine(
            churn_rate=cfg.get('topology_churn_rate', 0.0),
            migration_rate=cfg.get('topology_migration_rate', 0.0),
            arrival_rate=cfg.get('topology_arrival_rate', 0.0),
        )
        self.physics_engine = PLCPhysicsEngine()
        self.correlator = SIEMCorrelator()
        self.pcap_obs = cfg.get('pcap_obs', False)
        self.pcap_synthesizer = PcapSynthesizer() if self.pcap_obs else None
        if cfg.get('record_trajectory', False):
            from netforge_rl.render.trajectory import TrajectoryRecorder

            self.trajectory_recorder = TrajectoryRecorder()
        else:
            self.trajectory_recorder = None

        self.observation_spaces = build_observation_spaces(
            self.possible_agents, self.pcap_obs
        )
        self.action_spaces = build_action_spaces(self.possible_agents)
        self.max_ticks = cfg.get('max_ticks', 1000)
        self.current_tick = 0
        self.event_queue = []

    def reset(
        self, seed=None, options=None
    ) -> Tuple[Dict[str, np.ndarray], Dict[str, dict]]:
        """Reset the environment."""
        self.np_random = np.random.default_rng(seed)
        self._py_random = random.Random(seed)
        seed_events(seed)
        self.siem_logger = SIEMLogger(
            seed=seed, latency=self.log_latency, capture=self.record_siem
        )
        self.docker_bridge.teardown_all()
        self.docker_bridge.reseed(seed)
        self.global_state = self.network_generator.generate(seed=seed)
        self.global_state.docker_bridge = self.docker_bridge
        self.agents = self.possible_agents[:]
        self.ordered_hosts = sorted(self.global_state.all_hosts.keys())
        self._cached_action_masks = {
            agent: self.action_mask(agent) for agent in self.agents
        }
        self.global_state.agent_energy = {agent: 50 for agent in self.agents}
        self.global_state.agent_funds = {
            agent: 10000 if 'blue' in agent else 5000 for agent in self.agents
        }
        self.global_state.agent_compute = {agent: 1000 for agent in self.agents}
        self.global_state.business_downtime_score = 0.0
        # SIEM log buffer and research metrics
        self.global_state.siem_log_buffer = []
        self.episode_metrics = {
            'infection_times': {},  # IP -> tick
            'detection_times': {},  # IP -> tick (first SIEM alert)
            'isolation_times': {},  # IP -> tick
            'exfiltrated_data': 0.0,
            'sla_uptime_sum': 0.0,
            'steps_count': 0,
            'deception_hits': 0,  # red actions that struck a decoy/honeytoken
            'red_actions': 0,  # resolved red actions, for efficacy ratio
            'attack_techniques': set(),  # MITRE ATT&CK technique ids exercised
        }

        observations = {}
        for agent_id in self.agents:
            obs = BaseObservation(agent_id)
            obs.update_from_state(self.global_state, [])
            agent_obs = {
                'obs': obs.to_numpy(max_size=256),
                'action_mask': self._cached_action_masks[agent_id],
                'siem_embedding': np.zeros(EMBEDDING_DIM, dtype=np.float32),
                'adj_matrix': self.global_state.get_adjacency_matrix().flatten(),
                'delta_t': np.zeros(1, dtype=np.float32),
            }
            if 'blue' in agent_id:
                agent_obs['blue_comm'] = np.zeros(100, dtype=np.float32)
            if self.pcap_obs:
                agent_obs['pcap'] = np.zeros((N_PACKETS, PACKET_DIM), dtype=np.float32)
                agent_obs['node_features'] = np.zeros((100, NODE_DIM), dtype=np.float32)
            observations[agent_id] = agent_obs
        self.current_tick = 0
        self.event_queue = []
        self.topology_engine.reset(seed=seed)
        self.physics_engine.reset(seed=seed)
        self.correlator.reset()
        if self.trajectory_recorder is not None:
            self.trajectory_recorder.reset(
                scenario=self.scenario.__class__.__name__, seed=seed or 0
            )
        if self.pcap_synthesizer:
            self.pcap_synthesizer.reset(seed=seed)

        return observations, {agent: {} for agent in self.agents}

    def observation_space(self, agent):
        return self.observation_spaces[agent]

    def action_space(self, agent):
        return self.action_spaces[agent]

    def action_mask(self, agent: str) -> np.ndarray:
        """Generate a binary action mask of shape (132,) = (32 + 100)."""
        mask = np.zeros(132, dtype=np.int8)
        for action_id in action_registry._actions.get(team_of(agent), {}):
            if action_id < 32:
                mask[action_id] = 1
        ordered = sorted(self.global_state.all_hosts.keys())
        for i, ip in enumerate(ordered[:100]):
            host = self.global_state.all_hosts.get(ip)
            if host and host.status != 'isolated':
                mask[32 + i] = 1
        return mask

    def step(
        self, agent_actions: Dict[str, int]
    ) -> Tuple[
        Dict[str, BaseObservation],
        Dict[str, float],
        Dict[str, bool],
        Dict[str, bool],
        Dict[str, dict],
    ]:
        """Process actions and advance simulation."""

        per_agent_inflight: Dict[str, int] = {}
        for event in self.event_queue:
            per_agent_inflight[event['agent']] = (
                per_agent_inflight.get(event['agent'], 0) + 1
            )

        for agent, action_int in agent_actions.items():
            if self.current_tick < self.global_state.agent_locked_until.get(agent, 0):
                continue

            if isinstance(action_int, BaseAction):
                action = action_int
            else:
                self.ordered_hosts = sorted(self.global_state.all_hosts.keys())
                action = action_registry.instantiate_action(
                    agent, action_int, self.ordered_hosts
                )
                if action is None:
                    continue

            # Cap Blue agents at 2 in-flight actions.
            if 'blue' in agent.lower():
                if per_agent_inflight.get(agent, 0) >= 2:
                    continue
                per_agent_inflight[agent] = per_agent_inflight.get(agent, 0) + 1

            if self.global_state.agent_energy.get(agent, 0) < action.cost:
                continue
            if not action.validate(self.global_state):
                continue

            self.global_state.agent_energy[agent] -= action.cost

            eta = getattr(action, 'duration', 1)
            completion_tick = self.current_tick + eta
            effect = action.execute(self.global_state)
            effect.action = action

            self.global_state.agent_locked_until[agent] = completion_tick
            self.event_queue.append(
                {
                    'completion_tick': completion_tick,
                    'agent': agent,
                    'action': action,
                    'effect': effect,
                    'target_ip': getattr(action, 'target_ip', None),
                    'start_tick': self.current_tick,
                }
            )

        for event in list(self.event_queue):
            if (
                type(event['action']).__name__ == 'IsolateHost'
                and event['completion_tick'] <= self.current_tick
            ):
                target_to_isolate = event['target_ip']
                for red_event in list(self.event_queue):
                    if (
                        'red' in red_event['agent'].lower()
                        and red_event['target_ip'] == target_to_isolate
                    ):
                        if red_event in self.event_queue:
                            self.event_queue.remove(red_event)
                        self.global_state.agent_locked_until[red_event['agent']] = (
                            self.current_tick
                        )

        prev_tick = self.current_tick
        if self.event_queue:
            next_event_tick = min(e['completion_tick'] for e in self.event_queue)
            self.current_tick = max(self.current_tick + 1, next_event_tick)
        else:
            self.current_tick += 1

        delta_t = float(self.current_tick - prev_tick)
        delta_t_norm = delta_t / MAX_ACTION_DURATION

        self.global_state.current_tick = self.current_tick
        self.global_state.subnet_bandwidth.clear()

        noise_data = self.green_agent.generate_noise(
            self.current_tick, self.global_state, rng=self._py_random
        )
        for anomaly in noise_data.get('alerts', []):
            self.siem_logger._push_to_buffer(
                anomaly['data'], anomaly['subnet'], self.global_state
            )

        intended_effects = {}
        action_metadata = {}
        remaining_events = []
        for event in self.event_queue:
            if self.current_tick >= event['completion_tick']:
                agent = event['agent']
                intended_effects[agent] = event['effect']
                action_metadata[agent] = {
                    'name': type(event['action']).__name__,
                    'target_ip': event.get('target_ip'),
                }
            else:
                remaining_events.append(event)
        self.event_queue = remaining_events

        resolved_effects = self.resolution_engine.resolve(intended_effects)
        self._apply_state_deltas(resolved_effects)

        self._update_episode_metrics(resolved_effects)

        for res_agent, res_effect in resolved_effects.items():
            meta = action_metadata.get(res_agent, {})
            self.siem_logger.log_action(
                action_name=meta.get('name', 'UnknownAction'),
                effect=res_effect,
                global_state=self.global_state,
                agent_id=res_agent,
                target_ip=res_effect.observation_data.get('exploit'),
            )

        for res_agent, res_effect in resolved_effects.items():
            if 'red' not in res_agent or not res_effect.success:
                continue
            target_ip = res_effect.observation_data.get('exploit', 'unknown')
            host = self.global_state.all_hosts.get(target_ip)
            subnet = host.subnet_cidr if host else 'unknown'

            self.siem_logger._push_to_buffer(
                sysmon_1(
                    res_agent, process='exploit_payload', rng=self.siem_logger._rng
                ),
                subnet,
                self.global_state,
            )
            if host and getattr(host, 'contains_honeytokens', False):
                self.siem_logger._push_to_buffer(
                    {
                        'signature': 'HONEYTOKEN_TRIGGERED',
                        'target': target_ip,
                        'agent': res_agent,
                        'severity': 10,
                    },
                    subnet,
                    self.global_state,
                )

        self.siem_logger.log_background_noise(self.global_state)

        if self.dhcp_interval > 0 and self.current_tick % self.dhcp_interval == 0:
            self.global_state.reallocate_dhcp(rng=self._py_random)
            valid_ips = set(self.global_state.all_hosts.keys())
            self.event_queue = [
                e
                for e in self.event_queue
                if e.get('target_ip') is None or e['target_ip'] in valid_ips
            ]
            self._cached_action_masks = {
                agent: self.action_mask(agent) for agent in self.agents
            }

        physics_alerts, physics_deltas = self.physics_engine.tick(self.global_state)
        for delta_key, delta_val in physics_deltas:
            self.global_state.apply_delta(delta_key, delta_val)
        ot_subnet = '10.0.99.0/24'
        for alert in physics_alerts:
            self.siem_logger._push_to_buffer(alert, ot_subnet, self.global_state)

        for incident_log, incident_subnet in self.correlator.correlate(
            self.global_state
        ):
            self.global_state.siem_log_buffer.append((incident_log, incident_subnet))
            if len(self.global_state.siem_log_buffer) > 64:
                self.global_state.siem_log_buffer.pop(0)

        topo_events = self.topology_engine.tick(self.global_state)
        if topo_events:
            valid_ips = set(self.global_state.all_hosts.keys())
            self.event_queue = [
                e
                for e in self.event_queue
                if e.get('target_ip') is None or e['target_ip'] in valid_ips
            ]
            for ev in topo_events:
                self.siem_logger._push_to_buffer(
                    {
                        'signature': f'TOPOLOGY_{ev.kind.upper()}',
                        'detail': ev.detail,
                        'severity': 3,
                    },
                    ev.detail.get('subnet', ev.detail.get('new_subnet', 'unknown')),
                    self.global_state,
                )
            self._cached_action_masks = {
                agent: self.action_mask(agent) for agent in self.agents
            }

        observations = {}
        rewards = {}
        terminate = self.scenario.check_termination(self.global_state)
        is_truncated = self.current_tick >= self.max_ticks
        truncate = {agent: is_truncated for agent in self.agents}

        self.siem_logger.release(self.global_state)

        # Encode SIEM logs.
        agent_siem_vecs = {}
        for agent in self.agents:
            if 'blue' in agent.lower():
                subnet_tag = agent.split('_')[1] if '_' in agent else 'dmz'
                subset_logs = self.siem_logger.get_filtered_logs(
                    self.global_state, subnet_tag=subnet_tag, n=8
                )
                agent_siem_vecs[agent] = self.log_encoder.encode_buffer(
                    subset_logs, agg='mean'
                )

        pcap_snapshot = (
            self.pcap_synthesizer.synthesize(
                self.global_state, self.current_tick, self.max_ticks
            )
            if self.pcap_synthesizer
            else None
        )
        node_feat_snapshot = (
            self.pcap_synthesizer.node_features(self.global_state)
            if self.pcap_synthesizer
            else None
        )

        blue_comm = self._build_blue_comm()

        for agent in self.agents:
            obs = BaseObservation(agent)
            obs.update_from_state(self.global_state, resolved_effects)

            obs_array = obs.to_numpy(max_size=256)

            if 'blue' in agent.lower():
                agent_siem_vec = agent_siem_vecs.get(
                    agent, np.zeros(EMBEDDING_DIM, dtype=np.float32)
                )
            else:
                agent_siem_vec = np.zeros(EMBEDDING_DIM, dtype=np.float32)

            agent_obs = {
                'obs': obs_array,
                'action_mask': self._cached_action_masks[agent],
                'siem_embedding': agent_siem_vec,
                'adj_matrix': self._get_adj_matrix_for(agent).flatten(),
                'delta_t': np.array([delta_t_norm], dtype=np.float32),
            }
            if 'blue' in agent.lower():
                agent_obs['blue_comm'] = blue_comm
            if self.pcap_obs:
                agent_obs['pcap'] = pcap_snapshot
                agent_obs['node_features'] = node_feat_snapshot
            observations[agent] = agent_obs
            agent_effect = resolved_effects.get(agent)
            rewards[agent] = self.scenario.calculate_reward(
                agent, self.global_state, agent_effect
            )

        if self.trajectory_recorder is not None:
            for agent, effect in resolved_effects.items():
                meta = action_metadata.get(agent, {})
                self.trajectory_recorder.record_step(
                    tick=self.current_tick,
                    agent_id=agent,
                    action_name=meta.get('name', 'UnknownAction'),
                    target_ip=meta.get('target_ip'),
                    success=effect.success,
                    reward=float(rewards.get(agent, 0.0)),
                )

        self.agents = [
            agent
            for agent in self.agents
            if not terminate[agent] and not truncate[agent]
        ]

        infos = self._extract_agent_infos(observations, resolved_effects, rewards)

        for agent in self.agents:
            if agent in infos:
                infos[agent]['delta_t'] = delta_t
                infos[agent]['delta_t_norm'] = delta_t_norm

        return observations, rewards, terminate, truncate, infos

    def render(self, mode: str = 'rgb_array'):
        """Render the environment frame."""
        if mode == 'ansi':
            return None
        if mode != 'rgb_array':
            raise ValueError(f'Unsupported render mode: {mode}')
        from netforge_rl.render import render_rgb, snapshot_from_envstate

        return render_rgb(snapshot_from_envstate(self.to_envstate()))

    def to_envstate(self):
        """Return a frozen EnvState PyTree snapshot."""
        return from_global_state(self.global_state, tuple(self.possible_agents))

    def _apply_state_deltas(self, effects: Dict[str, ActionEffect]):
        """Apply state deltas to global_state."""
        for effect in effects.values():
            if not effect.success:
                continue
            if isinstance(effect.state_deltas, dict):
                for delta_key, delta_val in effect.state_deltas.items():
                    self.global_state.apply_delta(delta_key, delta_val)
            elif isinstance(effect.state_deltas, list):
                for delta_cmd in effect.state_deltas:
                    self.global_state.apply_delta(delta_cmd)

reset

reset(
    seed=None, options=None
) -> Tuple[Dict[str, np.ndarray], Dict[str, dict]]

Reset the environment.

Source code in netforge_rl\environment\parallel_env.py
def reset(
    self, seed=None, options=None
) -> Tuple[Dict[str, np.ndarray], Dict[str, dict]]:
    """Reset the environment."""
    self.np_random = np.random.default_rng(seed)
    self._py_random = random.Random(seed)
    seed_events(seed)
    self.siem_logger = SIEMLogger(
        seed=seed, latency=self.log_latency, capture=self.record_siem
    )
    self.docker_bridge.teardown_all()
    self.docker_bridge.reseed(seed)
    self.global_state = self.network_generator.generate(seed=seed)
    self.global_state.docker_bridge = self.docker_bridge
    self.agents = self.possible_agents[:]
    self.ordered_hosts = sorted(self.global_state.all_hosts.keys())
    self._cached_action_masks = {
        agent: self.action_mask(agent) for agent in self.agents
    }
    self.global_state.agent_energy = {agent: 50 for agent in self.agents}
    self.global_state.agent_funds = {
        agent: 10000 if 'blue' in agent else 5000 for agent in self.agents
    }
    self.global_state.agent_compute = {agent: 1000 for agent in self.agents}
    self.global_state.business_downtime_score = 0.0
    # SIEM log buffer and research metrics
    self.global_state.siem_log_buffer = []
    self.episode_metrics = {
        'infection_times': {},  # IP -> tick
        'detection_times': {},  # IP -> tick (first SIEM alert)
        'isolation_times': {},  # IP -> tick
        'exfiltrated_data': 0.0,
        'sla_uptime_sum': 0.0,
        'steps_count': 0,
        'deception_hits': 0,  # red actions that struck a decoy/honeytoken
        'red_actions': 0,  # resolved red actions, for efficacy ratio
        'attack_techniques': set(),  # MITRE ATT&CK technique ids exercised
    }

    observations = {}
    for agent_id in self.agents:
        obs = BaseObservation(agent_id)
        obs.update_from_state(self.global_state, [])
        agent_obs = {
            'obs': obs.to_numpy(max_size=256),
            'action_mask': self._cached_action_masks[agent_id],
            'siem_embedding': np.zeros(EMBEDDING_DIM, dtype=np.float32),
            'adj_matrix': self.global_state.get_adjacency_matrix().flatten(),
            'delta_t': np.zeros(1, dtype=np.float32),
        }
        if 'blue' in agent_id:
            agent_obs['blue_comm'] = np.zeros(100, dtype=np.float32)
        if self.pcap_obs:
            agent_obs['pcap'] = np.zeros((N_PACKETS, PACKET_DIM), dtype=np.float32)
            agent_obs['node_features'] = np.zeros((100, NODE_DIM), dtype=np.float32)
        observations[agent_id] = agent_obs
    self.current_tick = 0
    self.event_queue = []
    self.topology_engine.reset(seed=seed)
    self.physics_engine.reset(seed=seed)
    self.correlator.reset()
    if self.trajectory_recorder is not None:
        self.trajectory_recorder.reset(
            scenario=self.scenario.__class__.__name__, seed=seed or 0
        )
    if self.pcap_synthesizer:
        self.pcap_synthesizer.reset(seed=seed)

    return observations, {agent: {} for agent in self.agents}

action_mask

action_mask(agent: str) -> np.ndarray

Generate a binary action mask of shape (132,) = (32 + 100).

Source code in netforge_rl\environment\parallel_env.py
def action_mask(self, agent: str) -> np.ndarray:
    """Generate a binary action mask of shape (132,) = (32 + 100)."""
    mask = np.zeros(132, dtype=np.int8)
    for action_id in action_registry._actions.get(team_of(agent), {}):
        if action_id < 32:
            mask[action_id] = 1
    ordered = sorted(self.global_state.all_hosts.keys())
    for i, ip in enumerate(ordered[:100]):
        host = self.global_state.all_hosts.get(ip)
        if host and host.status != 'isolated':
            mask[32 + i] = 1
    return mask

step

step(
    agent_actions: Dict[str, int],
) -> Tuple[
    Dict[str, BaseObservation],
    Dict[str, float],
    Dict[str, bool],
    Dict[str, bool],
    Dict[str, dict],
]

Process actions and advance simulation.

Source code in netforge_rl\environment\parallel_env.py
def step(
    self, agent_actions: Dict[str, int]
) -> Tuple[
    Dict[str, BaseObservation],
    Dict[str, float],
    Dict[str, bool],
    Dict[str, bool],
    Dict[str, dict],
]:
    """Process actions and advance simulation."""

    per_agent_inflight: Dict[str, int] = {}
    for event in self.event_queue:
        per_agent_inflight[event['agent']] = (
            per_agent_inflight.get(event['agent'], 0) + 1
        )

    for agent, action_int in agent_actions.items():
        if self.current_tick < self.global_state.agent_locked_until.get(agent, 0):
            continue

        if isinstance(action_int, BaseAction):
            action = action_int
        else:
            self.ordered_hosts = sorted(self.global_state.all_hosts.keys())
            action = action_registry.instantiate_action(
                agent, action_int, self.ordered_hosts
            )
            if action is None:
                continue

        # Cap Blue agents at 2 in-flight actions.
        if 'blue' in agent.lower():
            if per_agent_inflight.get(agent, 0) >= 2:
                continue
            per_agent_inflight[agent] = per_agent_inflight.get(agent, 0) + 1

        if self.global_state.agent_energy.get(agent, 0) < action.cost:
            continue
        if not action.validate(self.global_state):
            continue

        self.global_state.agent_energy[agent] -= action.cost

        eta = getattr(action, 'duration', 1)
        completion_tick = self.current_tick + eta
        effect = action.execute(self.global_state)
        effect.action = action

        self.global_state.agent_locked_until[agent] = completion_tick
        self.event_queue.append(
            {
                'completion_tick': completion_tick,
                'agent': agent,
                'action': action,
                'effect': effect,
                'target_ip': getattr(action, 'target_ip', None),
                'start_tick': self.current_tick,
            }
        )

    for event in list(self.event_queue):
        if (
            type(event['action']).__name__ == 'IsolateHost'
            and event['completion_tick'] <= self.current_tick
        ):
            target_to_isolate = event['target_ip']
            for red_event in list(self.event_queue):
                if (
                    'red' in red_event['agent'].lower()
                    and red_event['target_ip'] == target_to_isolate
                ):
                    if red_event in self.event_queue:
                        self.event_queue.remove(red_event)
                    self.global_state.agent_locked_until[red_event['agent']] = (
                        self.current_tick
                    )

    prev_tick = self.current_tick
    if self.event_queue:
        next_event_tick = min(e['completion_tick'] for e in self.event_queue)
        self.current_tick = max(self.current_tick + 1, next_event_tick)
    else:
        self.current_tick += 1

    delta_t = float(self.current_tick - prev_tick)
    delta_t_norm = delta_t / MAX_ACTION_DURATION

    self.global_state.current_tick = self.current_tick
    self.global_state.subnet_bandwidth.clear()

    noise_data = self.green_agent.generate_noise(
        self.current_tick, self.global_state, rng=self._py_random
    )
    for anomaly in noise_data.get('alerts', []):
        self.siem_logger._push_to_buffer(
            anomaly['data'], anomaly['subnet'], self.global_state
        )

    intended_effects = {}
    action_metadata = {}
    remaining_events = []
    for event in self.event_queue:
        if self.current_tick >= event['completion_tick']:
            agent = event['agent']
            intended_effects[agent] = event['effect']
            action_metadata[agent] = {
                'name': type(event['action']).__name__,
                'target_ip': event.get('target_ip'),
            }
        else:
            remaining_events.append(event)
    self.event_queue = remaining_events

    resolved_effects = self.resolution_engine.resolve(intended_effects)
    self._apply_state_deltas(resolved_effects)

    self._update_episode_metrics(resolved_effects)

    for res_agent, res_effect in resolved_effects.items():
        meta = action_metadata.get(res_agent, {})
        self.siem_logger.log_action(
            action_name=meta.get('name', 'UnknownAction'),
            effect=res_effect,
            global_state=self.global_state,
            agent_id=res_agent,
            target_ip=res_effect.observation_data.get('exploit'),
        )

    for res_agent, res_effect in resolved_effects.items():
        if 'red' not in res_agent or not res_effect.success:
            continue
        target_ip = res_effect.observation_data.get('exploit', 'unknown')
        host = self.global_state.all_hosts.get(target_ip)
        subnet = host.subnet_cidr if host else 'unknown'

        self.siem_logger._push_to_buffer(
            sysmon_1(
                res_agent, process='exploit_payload', rng=self.siem_logger._rng
            ),
            subnet,
            self.global_state,
        )
        if host and getattr(host, 'contains_honeytokens', False):
            self.siem_logger._push_to_buffer(
                {
                    'signature': 'HONEYTOKEN_TRIGGERED',
                    'target': target_ip,
                    'agent': res_agent,
                    'severity': 10,
                },
                subnet,
                self.global_state,
            )

    self.siem_logger.log_background_noise(self.global_state)

    if self.dhcp_interval > 0 and self.current_tick % self.dhcp_interval == 0:
        self.global_state.reallocate_dhcp(rng=self._py_random)
        valid_ips = set(self.global_state.all_hosts.keys())
        self.event_queue = [
            e
            for e in self.event_queue
            if e.get('target_ip') is None or e['target_ip'] in valid_ips
        ]
        self._cached_action_masks = {
            agent: self.action_mask(agent) for agent in self.agents
        }

    physics_alerts, physics_deltas = self.physics_engine.tick(self.global_state)
    for delta_key, delta_val in physics_deltas:
        self.global_state.apply_delta(delta_key, delta_val)
    ot_subnet = '10.0.99.0/24'
    for alert in physics_alerts:
        self.siem_logger._push_to_buffer(alert, ot_subnet, self.global_state)

    for incident_log, incident_subnet in self.correlator.correlate(
        self.global_state
    ):
        self.global_state.siem_log_buffer.append((incident_log, incident_subnet))
        if len(self.global_state.siem_log_buffer) > 64:
            self.global_state.siem_log_buffer.pop(0)

    topo_events = self.topology_engine.tick(self.global_state)
    if topo_events:
        valid_ips = set(self.global_state.all_hosts.keys())
        self.event_queue = [
            e
            for e in self.event_queue
            if e.get('target_ip') is None or e['target_ip'] in valid_ips
        ]
        for ev in topo_events:
            self.siem_logger._push_to_buffer(
                {
                    'signature': f'TOPOLOGY_{ev.kind.upper()}',
                    'detail': ev.detail,
                    'severity': 3,
                },
                ev.detail.get('subnet', ev.detail.get('new_subnet', 'unknown')),
                self.global_state,
            )
        self._cached_action_masks = {
            agent: self.action_mask(agent) for agent in self.agents
        }

    observations = {}
    rewards = {}
    terminate = self.scenario.check_termination(self.global_state)
    is_truncated = self.current_tick >= self.max_ticks
    truncate = {agent: is_truncated for agent in self.agents}

    self.siem_logger.release(self.global_state)

    # Encode SIEM logs.
    agent_siem_vecs = {}
    for agent in self.agents:
        if 'blue' in agent.lower():
            subnet_tag = agent.split('_')[1] if '_' in agent else 'dmz'
            subset_logs = self.siem_logger.get_filtered_logs(
                self.global_state, subnet_tag=subnet_tag, n=8
            )
            agent_siem_vecs[agent] = self.log_encoder.encode_buffer(
                subset_logs, agg='mean'
            )

    pcap_snapshot = (
        self.pcap_synthesizer.synthesize(
            self.global_state, self.current_tick, self.max_ticks
        )
        if self.pcap_synthesizer
        else None
    )
    node_feat_snapshot = (
        self.pcap_synthesizer.node_features(self.global_state)
        if self.pcap_synthesizer
        else None
    )

    blue_comm = self._build_blue_comm()

    for agent in self.agents:
        obs = BaseObservation(agent)
        obs.update_from_state(self.global_state, resolved_effects)

        obs_array = obs.to_numpy(max_size=256)

        if 'blue' in agent.lower():
            agent_siem_vec = agent_siem_vecs.get(
                agent, np.zeros(EMBEDDING_DIM, dtype=np.float32)
            )
        else:
            agent_siem_vec = np.zeros(EMBEDDING_DIM, dtype=np.float32)

        agent_obs = {
            'obs': obs_array,
            'action_mask': self._cached_action_masks[agent],
            'siem_embedding': agent_siem_vec,
            'adj_matrix': self._get_adj_matrix_for(agent).flatten(),
            'delta_t': np.array([delta_t_norm], dtype=np.float32),
        }
        if 'blue' in agent.lower():
            agent_obs['blue_comm'] = blue_comm
        if self.pcap_obs:
            agent_obs['pcap'] = pcap_snapshot
            agent_obs['node_features'] = node_feat_snapshot
        observations[agent] = agent_obs
        agent_effect = resolved_effects.get(agent)
        rewards[agent] = self.scenario.calculate_reward(
            agent, self.global_state, agent_effect
        )

    if self.trajectory_recorder is not None:
        for agent, effect in resolved_effects.items():
            meta = action_metadata.get(agent, {})
            self.trajectory_recorder.record_step(
                tick=self.current_tick,
                agent_id=agent,
                action_name=meta.get('name', 'UnknownAction'),
                target_ip=meta.get('target_ip'),
                success=effect.success,
                reward=float(rewards.get(agent, 0.0)),
            )

    self.agents = [
        agent
        for agent in self.agents
        if not terminate[agent] and not truncate[agent]
    ]

    infos = self._extract_agent_infos(observations, resolved_effects, rewards)

    for agent in self.agents:
        if agent in infos:
            infos[agent]['delta_t'] = delta_t
            infos[agent]['delta_t_norm'] = delta_t_norm

    return observations, rewards, terminate, truncate, infos

render

render(mode: str = 'rgb_array')

Render the environment frame.

Source code in netforge_rl\environment\parallel_env.py
def render(self, mode: str = 'rgb_array'):
    """Render the environment frame."""
    if mode == 'ansi':
        return None
    if mode != 'rgb_array':
        raise ValueError(f'Unsupported render mode: {mode}')
    from netforge_rl.render import render_rgb, snapshot_from_envstate

    return render_rgb(snapshot_from_envstate(self.to_envstate()))

to_envstate

to_envstate()

Return a frozen EnvState PyTree snapshot.

Source code in netforge_rl\environment\parallel_env.py
def to_envstate(self):
    """Return a frozen EnvState PyTree snapshot."""
    return from_global_state(self.global_state, tuple(self.possible_agents))

jax

to_numpy

to_numpy(
    jstate,
    meta: HostMeta,
    agent_ids,
    knowledge=None,
    inventory=None,
) -> EnvState

Convert JaxEnvState to numpy EnvState.

Source code in netforge_rl\backends\jax\state.py
def to_numpy(
    jstate, meta: HostMeta, agent_ids, knowledge=None, inventory=None
) -> EnvState:
    """Convert JaxEnvState to numpy EnvState."""
    if knowledge is None:
        knowledge = []
        for j in range(len(agent_ids)):
            agent_know = set()
            for i, ip in enumerate(meta.ip):
                if jstate.knowledge_mask[j, i]:
                    agent_know.add(ip)
            knowledge.append(agent_know)

    if inventory is None:
        from netforge_rl.core.functional import TOKEN_CODES

        inventory = []
        for j in range(len(agent_ids)):
            agent_inv = []
            for i, tok in enumerate(TOKEN_CODES):
                if jstate.agent_credentials[j, i]:
                    agent_inv.append(tok)
            inventory.append(agent_inv)

    h = jstate.hosts
    hosts = HostArrays(
        status=np.asarray(h.status),
        privilege=np.asarray(h.privilege),
        decoy=np.asarray(h.decoy),
        edr_active=np.asarray(h.edr_active),
        is_domain_controller=np.asarray(h.is_domain_controller),
        contains_honeytokens=np.asarray(h.contains_honeytokens),
        human_vulnerability=np.asarray(h.human_vulnerability),
        cvss_score=np.asarray(h.cvss_score),
        compromised_by_id=np.asarray(h.compromised_by_id),
        system_integrity=np.asarray(h.system_integrity),
        vuln_mask=np.asarray(h.vuln_mask),
        host_tokens=np.asarray(h.host_tokens),
        os_family=np.asarray(h.os_family),
    )
    return EnvState(
        hosts=hosts,
        meta=meta,
        agent_ids=tuple(agent_ids),
        agent_energy=np.asarray(jstate.agent_energy),
        agent_funds=np.asarray(jstate.agent_funds),
        agent_compute=np.asarray(jstate.agent_compute),
        agent_locked_until=np.asarray(jstate.agent_locked_until),
        current_tick=int(jstate.current_tick),
        business_downtime_score=float(jstate.business_downtime_score),
        knowledge=tuple(knowledge),
        inventory=tuple(inventory),
    )

resolve_conflicts_mask

resolve_conflicts_mask(
    red_target_mask,
    blue_target_mask,
    red_success,
    blue_success,
)

Return post-resolution Red success vector. Red success is nullified if targeted by Blue.

Source code in netforge_rl\backends\jax\kernels.py
def resolve_conflicts_mask(
    red_target_mask, blue_target_mask, red_success, blue_success
):
    """Return post-resolution Red success vector. Red success is nullified if targeted by Blue."""
    defended_hosts = jnp.any(blue_target_mask & blue_success[:, None], axis=0)
    red_collisions = jnp.any(red_target_mask & defended_hosts[None, :], axis=1)
    return red_success & ~red_collisions

initial_batched_state

initial_batched_state(
    template: JaxEnvState, batch_size: int
) -> JaxEnvState

Tile state across the batch dimension.

Source code in netforge_rl\backends\jax\vector_env.py
def initial_batched_state(template: JaxEnvState, batch_size: int) -> JaxEnvState:
    """Tile state across the batch dimension."""

    def tile(x):
        if isinstance(x, (jax.Array, np.ndarray)):
            return jnp.broadcast_to(jnp.asarray(x), (batch_size,) + tuple(x.shape))
        return jnp.broadcast_to(jnp.asarray(x), (batch_size,))

    return jax.tree_util.tree_map(tile, template)

jax_siem_features

jax_siem_features(hosts) -> jax.Array

Per-host SIEM alert signal in [0, 1], computed in JAX from state — the vectorized-backend analogue of the Python SIEM pipeline (jit/vmap-safe).

Source code in netforge_rl\backends\jax\vector_env.py
def jax_siem_features(hosts) -> jax.Array:
    """Per-host SIEM alert signal in [0, 1], computed in JAX from state — the
    vectorized-backend analogue of the Python SIEM pipeline (jit/vmap-safe)."""
    compromised = (hosts.compromised_by_id >= 0).astype(jnp.float32)
    privileged = (hosts.privilege > 0).astype(jnp.float32)
    honeytoken = hosts.contains_honeytokens.astype(jnp.float32) * compromised
    decoy = (hosts.decoy > 0).astype(jnp.float32)
    edr = hosts.edr_active.astype(jnp.float32)

    alert = 0.4 * compromised + 0.3 * privileged + 0.5 * honeytoken + 0.2 * decoy
    # EDR sharpens detection confidence on the hosts it covers.
    alert = alert * (1.0 + 0.25 * edr)
    return jnp.clip(alert, 0.0, 1.0)

make_vector_step

make_vector_step(spec: VectorEnvSpec)

Return the compiled, batched transition step for this spec.

Source code in netforge_rl\backends\jax\vector_env.py
def make_vector_step(spec: VectorEnvSpec):
    """Return the compiled, batched transition step for this spec."""
    per_env = partial(single_env_step, spec=spec)
    batched = jax.vmap(per_env)

    @jax.jit
    def _step_impl(state, rt, bt, ra, ba, rat, bat):
        return batched(state, rt, bt, ra, ba, rat, bat)

    def step_fn(state, actions):
        actions = _default_action_types(actions, spec)
        return _step_impl(
            state,
            actions.red_target_idx,
            actions.blue_target_idx,
            actions.red_attempt,
            actions.blue_attempt,
            actions.red_action_type,
            actions.blue_action_type,
        )

    return step_fn

scenario_done

scenario_done(state, spec)

Per-env terminal flag for the active scenario. Vectorized over the batch.

Source code in netforge_rl\backends\jax\transition.py
def scenario_done(state, spec):
    """Per-env terminal flag for the active scenario. Vectorized over the batch."""
    hosts = state.hosts
    infected = hosts.privilege >= jnp.int8(_PRIV_USER)
    isolated = hosts.status == jnp.int8(_STATUS_ISOLATED)
    compromised = hosts.compromised_by_id >= 0
    kinetic = hosts.system_integrity == jnp.int8(_INTEGRITY_KINETIC)
    is_dc = hosts.is_domain_controller

    any_kinetic = jnp.any(kinetic, axis=-1)

    any_infected = jnp.any(infected, axis=-1)
    all_infected_isolated = jnp.all(~infected | isolated, axis=-1)
    apt_done = any_infected & all_infected_isolated

    any_dc = jnp.any(is_dc, axis=-1)
    all_dc_compromised = jnp.all(~is_dc | compromised, axis=-1)
    dc_done = any_dc & all_dc_compromised

    compromised_frac = jnp.mean(compromised.astype(jnp.float32), axis=-1)
    ransomware_done = (compromised_frac >= 0.9) | any_kinetic

    if spec.scenario == SCENARIO_APT:
        return apt_done
    if spec.scenario in (SCENARIO_CLOUD, SCENARIO_IOT):
        return dc_done
    if spec.scenario == SCENARIO_OT:
        return any_kinetic
    return ransomware_done

functional

HostArrays dataclass

Vectorizable per-host SoA — JAX PyTree leaves.

Source code in netforge_rl\core\functional.py
@dataclass(frozen=True)
class HostArrays:
    """Vectorizable per-host SoA — JAX PyTree leaves."""

    status: np.ndarray
    privilege: np.ndarray
    decoy: np.ndarray
    edr_active: np.ndarray
    is_domain_controller: np.ndarray
    contains_honeytokens: np.ndarray
    human_vulnerability: np.ndarray
    cvss_score: np.ndarray
    compromised_by_id: np.ndarray
    system_integrity: np.ndarray
    vuln_mask: np.ndarray
    host_tokens: np.ndarray
    os_family: np.ndarray

HostMeta dataclass

Static / variable-length host metadata. Not a PyTree leaf.

Source code in netforge_rl\core\functional.py
@dataclass(frozen=True)
class HostMeta:
    """Static / variable-length host metadata. Not a PyTree leaf."""

    ip: tuple
    hostname: tuple
    subnet_cidr: tuple
    os: tuple
    services: tuple
    vulnerabilities: tuple
    cached_credentials: tuple
    system_tokens: tuple

EnvState dataclass

Immutable snapshot of the MARL environment.

Source code in netforge_rl\core\functional.py
@dataclass(frozen=True)
class EnvState:
    """Immutable snapshot of the MARL environment."""

    hosts: HostArrays
    meta: HostMeta
    agent_ids: tuple
    agent_energy: np.ndarray
    agent_funds: np.ndarray
    agent_compute: np.ndarray
    agent_locked_until: np.ndarray
    current_tick: int = 0
    business_downtime_score: float = 0.0
    knowledge: tuple = field(default_factory=tuple)
    inventory: tuple = field(default_factory=tuple)

    @property
    def host_count(self):
        return self.hosts.status.shape[0]

    def agent_index(self, agent_id):
        return self.agent_ids.index(agent_id)

    def host_index(self, ip):
        return self.meta.ip.index(ip)

    def with_tick(self, tick):
        return replace(self, current_tick=tick)

from_global_state

from_global_state(legacy, agent_ids)

Build a frozen EnvState from a legacy GlobalNetworkState.

Source code in netforge_rl\core\functional.py
def from_global_state(legacy, agent_ids):
    """Build a frozen EnvState from a legacy GlobalNetworkState."""
    sorted_ips = tuple(sorted(legacy.all_hosts.keys()))
    n = len(sorted_ips)
    if n != N_HOSTS:
        raise ValueError(f'Expected exactly {N_HOSTS} hosts; got {n}.')
    hosts_in_order = [legacy.all_hosts[ip] for ip in sorted_ips]
    status_arr = np.array(
        [_encode(h.status, STATUS_CODES) for h in hosts_in_order], dtype=np.int8
    )
    priv_arr = np.array(
        [_encode(h.privilege, PRIVILEGE_CODES) for h in hosts_in_order], dtype=np.int8
    )
    decoy_arr = np.array(
        [_encode(h.decoy, DECOY_CODES) for h in hosts_in_order], dtype=np.int8
    )
    edr_arr = np.array([bool(h.edr_active) for h in hosts_in_order], dtype=bool)
    dc_arr = np.array(
        [bool(h.is_domain_controller) for h in hosts_in_order], dtype=bool
    )
    honey_arr = np.array(
        [bool(getattr(h, 'contains_honeytokens', False)) for h in hosts_in_order],
        dtype=bool,
    )
    hvuln_arr = np.array(
        [float(h.human_vulnerability_score) for h in hosts_in_order], dtype=np.float32
    )
    cvss_arr = np.array(
        [float(getattr(h, 'cvss_score', 0.0)) for h in hosts_in_order], dtype=np.float32
    )
    comp_arr = np.array(
        [
            agent_ids.index(h.compromised_by) if h.compromised_by in agent_ids else -1
            for h in hosts_in_order
        ],
        dtype=np.int8,
    )
    integrity_arr = np.array(
        [
            _encode(getattr(h, 'system_integrity', 'clean'), INTEGRITY_CODES)
            for h in hosts_in_order
        ],
        dtype=np.int8,
    )
    vuln_mask = np.zeros((n, N_CVE), dtype=bool)
    for i, h in enumerate(hosts_in_order):
        for cve in getattr(h, 'vulnerabilities', None) or ():
            if cve in CVE_CODES:
                vuln_mask[i, CVE_CODES.index(cve)] = True
    host_tokens = np.zeros((n, N_TOKEN), dtype=bool)
    for i, h in enumerate(hosts_in_order):
        for tok in getattr(h, 'cached_credentials', None) or ():
            if tok in TOKEN_CODES:
                host_tokens[i, TOKEN_CODES.index(tok)] = True
        for tok in getattr(h, 'system_tokens', None) or ():
            if tok in TOKEN_CODES:
                host_tokens[i, TOKEN_CODES.index(tok)] = True
    os_family = np.array([_os_family_code(h.os) for h in hosts_in_order], dtype=np.int8)
    hosts = HostArrays(
        status=status_arr,
        privilege=priv_arr,
        decoy=decoy_arr,
        edr_active=edr_arr,
        is_domain_controller=dc_arr,
        contains_honeytokens=honey_arr,
        human_vulnerability=hvuln_arr,
        cvss_score=cvss_arr,
        compromised_by_id=comp_arr,
        system_integrity=integrity_arr,
        vuln_mask=vuln_mask,
        host_tokens=host_tokens,
        os_family=os_family,
    )
    meta = HostMeta(
        ip=sorted_ips,
        hostname=tuple((h.hostname for h in hosts_in_order)),
        subnet_cidr=tuple((h.subnet_cidr for h in hosts_in_order)),
        os=tuple((h.os for h in hosts_in_order)),
        services=tuple((tuple(h.services) for h in hosts_in_order)),
        vulnerabilities=tuple((tuple(h.vulnerabilities) for h in hosts_in_order)),
        cached_credentials=tuple((tuple(h.cached_credentials) for h in hosts_in_order)),
        system_tokens=tuple((tuple(h.system_tokens) for h in hosts_in_order)),
    )
    return EnvState(
        hosts=hosts,
        meta=meta,
        agent_ids=tuple(agent_ids),
        agent_energy=np.array(
            [int(legacy.agent_energy.get(a, 0)) for a in agent_ids], dtype=np.int32
        ),
        agent_funds=np.array(
            [int(legacy.agent_funds.get(a, 0)) for a in agent_ids], dtype=np.int32
        ),
        agent_compute=np.array(
            [int(legacy.agent_compute.get(a, 0)) for a in agent_ids], dtype=np.int32
        ),
        agent_locked_until=np.array(
            [int(legacy.agent_locked_until.get(a, 0)) for a in agent_ids],
            dtype=np.int32,
        ),
        current_tick=int(legacy.current_tick),
        business_downtime_score=float(legacy.business_downtime_score),
        knowledge=tuple(
            (frozenset(legacy.agent_knowledge.get(a, set())) for a in agent_ids)
        ),
        inventory=tuple(
            (frozenset(legacy.agent_inventory.get(a, set())) for a in agent_ids)
        ),
    )

to_global_state

to_global_state(snap: EnvState)

Inverse of from_global_state. Discards action_history / SIEM buffer fields.

Source code in netforge_rl\core\functional.py
def to_global_state(snap: EnvState):
    """Inverse of from_global_state. Discards action_history / SIEM buffer fields."""
    legacy = GlobalNetworkState()
    seen = {}
    for cidr in snap.meta.subnet_cidr:
        if cidr in seen:
            continue
        sn = Subnet(cidr=cidr, name=cidr)
        seen[cidr] = sn
        legacy.add_subnet(sn)
    for i, ip in enumerate(snap.meta.ip):
        host = Host(
            ip=ip, hostname=snap.meta.hostname[i], subnet_cidr=snap.meta.subnet_cidr[i]
        )
        host.status = _decode(snap.hosts.status[i], STATUS_CODES)
        host.privilege = _decode(snap.hosts.privilege[i], PRIVILEGE_CODES)
        host.decoy = _decode(snap.hosts.decoy[i], DECOY_CODES)
        host.edr_active = bool(snap.hosts.edr_active[i])
        host.is_domain_controller = bool(snap.hosts.is_domain_controller[i])
        host.contains_honeytokens = bool(snap.hosts.contains_honeytokens[i])
        host.human_vulnerability_score = float(snap.hosts.human_vulnerability[i])
        host.cvss_score = float(snap.hosts.cvss_score[i])
        host.os = snap.meta.os[i]
        host.services = list(snap.meta.services[i])
        host.vulnerabilities = list(snap.meta.vulnerabilities[i])
        host.cached_credentials = list(snap.meta.cached_credentials[i])
        host.system_tokens = list(snap.meta.system_tokens[i])
        cid = int(snap.hosts.compromised_by_id[i])
        host.compromised_by = snap.agent_ids[cid] if cid >= 0 else 'None'
        host.system_integrity = _decode(snap.hosts.system_integrity[i], INTEGRITY_CODES)
        legacy.register_host(host)
    for j, agent in enumerate(snap.agent_ids):
        legacy.agent_energy[agent] = int(snap.agent_energy[j])
        legacy.agent_funds[agent] = int(snap.agent_funds[j])
        legacy.agent_compute[agent] = int(snap.agent_compute[j])
        legacy.agent_locked_until[agent] = int(snap.agent_locked_until[j])
        legacy.agent_knowledge[agent] = set(snap.knowledge[j])
        legacy.agent_inventory[agent] = set(snap.inventory[j])
    legacy.current_tick = int(snap.current_tick)
    legacy.business_downtime_score = float(snap.business_downtime_score)
    return legacy

apply_state_delta

apply_state_delta(state, delta_key, delta_value=None)

Pure interpreter for legacy state_deltas entries.

Source code in netforge_rl\core\functional.py
def apply_state_delta(state, delta_key, delta_value=None):
    """Pure interpreter for legacy ``state_deltas`` entries."""
    if not isinstance(delta_key, str):
        return state
    parts = delta_key.split('/')
    if parts[0] == 'hosts' and len(parts) == 3:
        ip, attribute = (parts[1], parts[2])
        if ip not in state.meta.ip:
            return state
        idx = state.meta.ip.index(ip)
        if attribute == 'compromised_by':
            return _set_compromised_by(state, idx, delta_value)
        if attribute in _ARRAY_FIELD:
            field_name, encoder = _ARRAY_FIELD[attribute]
            return _set_host_array(state, idx, field_name, encoder(delta_value))
        if attribute in _META_FIELD:
            return _set_host_meta(state, idx, _META_FIELD[attribute], delta_value)
        return state
    if parts[0] == 'knowledge' and len(parts) == 3:
        agent_id, ip = (parts[1], parts[2])
        if agent_id not in state.agent_ids:
            return state
        j = state.agent_ids.index(agent_id)
        new_set = state.knowledge[j] | {ip}
        new_knowledge = tuple(
            (new_set if k == j else s for k, s in enumerate(state.knowledge))
        )
        return replace(state, knowledge=new_knowledge)
    return state

apply_state_deltas

apply_state_deltas(state, deltas)

Apply a dict-of-deltas or list-of-command-deltas left to right.

Source code in netforge_rl\core\functional.py
def apply_state_deltas(state, deltas):
    """Apply a dict-of-deltas or list-of-command-deltas left to right."""
    if isinstance(deltas, dict):
        for k, v in deltas.items():
            state = apply_state_delta(state, k, v)
    elif isinstance(deltas, (list, tuple)):
        for item in deltas:
            state = apply_state_delta(state, item)
    return state