main.c

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
/*
 * Proxy Pool Governor — simulation/replay harness.
 *
 * Copyright (C) 2026  SWGY, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

#include "clips.h"
#include "scenario.h"

#include <err.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#define RULES_FILE "gov.clp"
#define MAX_POOLS 256
#define MAX_SERVICES 256

/*
 * Runtime mode
 */
typedef enum {
	MODE_SIMULATE,
	MODE_REPLAY
} RunMode;

/*
 * Runtime configuration
 */
typedef struct {
	RunMode      mode;
	const char  *scenario_path;
	int          sim_cycles;
	int          verbose;
} Config;

/*
 * Pool and service names (from scenario or defaults)
 */
static size_t num_pools;
static size_t num_services;
static char pool_names[MAX_POOLS][SCENARIO_MAX_NAME];
static char service_names[MAX_SERVICES][SCENARIO_MAX_NAME];

/*
 * Default pools and services for simulation mode
 */
static const char *default_pools[] = {
	"residential-us",
	"residential-eu",
	"datacenter-1",
	"datacenter-2",
	"mobile-us"
};
static const int default_num_pools = 5;

static const char *default_services[] = {
	"search",
	"checkout",
	"bulk-export"
};
static const int default_num_services = 3;

/*
 * Per-service configuration
 */
typedef struct {
	const char *service;
	double sigma_threshold;
	double min_success_rate;
	double max_response_time;
	double weight_reduction;
	int min_weight;
	double restore_cooldown;
	double service_degrade_threshold;
} ServiceConfig;

static ServiceConfig service_configs[MAX_SERVICES];
static size_t num_service_configs;

/*
 * Base weights [service][pool] - dynamically sized
 */
static int base_weights[MAX_SERVICES][MAX_POOLS];
static int effective_weights[MAX_SERVICES][MAX_POOLS];

/*
 * Forward declarations for simulation mode
 */
typedef struct {
	double base_success_rate;
	double base_response_time;
	double current_success_rate;
	double current_response_time;
	int degraded;
	int cycles_until_recovery;
	int cycles_until_incident;
} PoolHealth;

typedef struct {
	double success_sum;
	double success_sq_sum;
	double rt_sum;
	double rt_sq_sum;
	int count;
} StatsAccumulator;

static PoolHealth pool_health[MAX_SERVICES][MAX_POOLS];
static StatsAccumulator stats_accum[MAX_SERVICES][MAX_POOLS];

/*
 * Random helpers
 */
static double
rand_uniform(void)
{
	return (double)rand() / RAND_MAX;
}

static double
rand_normal(double mean, double stddev)
{
	double u1 = rand_uniform();
	double u2 = rand_uniform();
	if (u1 < 1e-10)
		u1 = 1e-10;
	double z = sqrt(-2.0 * log(u1)) * cos(2.0 * M_PI * u2);
	return mean + stddev * z;
}

static double
clamp(double val, double lo, double hi)
{
	if (val < lo)
		return lo;
	if (val > hi)
		return hi;
	return val;
}

/*
 * Initialize default configuration
 */
static void
init_defaults(void)
{
	/* Copy default pool names */
	num_pools = default_num_pools;
	for (int i = 0; i < default_num_pools; i++)
		strncpy(pool_names[i], default_pools[i], SCENARIO_MAX_NAME - 1);

	/* Copy default service names */
	num_services = default_num_services;
	for (int i = 0; i < default_num_services; i++)
		strncpy(service_names[i], default_services[i], SCENARIO_MAX_NAME - 1);

	/* Default service configs */
	service_configs[0] = (ServiceConfig){"search", 2.0, 0.85, 5.0, 0.5, 1, 3600.0, 0.7};
	service_configs[1] = (ServiceConfig){"checkout", 1.5, 0.95, 3.0, 0.25, 1, 7200.0, 0.7};
	service_configs[2] = (ServiceConfig){"bulk-export", 3.0, 0.70, 30.0, 0.75, 1, 1800.0, 0.7};
	num_service_configs = 3;

	/* Default base weights */
	int defaults[3][5] = {
		{20, 10, 5, 5, 1},   /* search */
		{25, 20, 3, 3, 1},   /* checkout */
		{5, 5, 15, 15, 10}   /* bulk-export */
	};
	for (int s = 0; s < 3; s++) {
		for (int p = 0; p < 5; p++) {
			base_weights[s][p] = defaults[s][p];
			effective_weights[s][p] = defaults[s][p];
		}
	}
}

/*
 * Initialize from scenario file
 */
static void
init_from_scenario(const Scenario *scen)
{
	num_pools = scen->num_pools;
	num_services = scen->num_services;

	for (size_t i = 0; i < num_pools; i++)
		strncpy(pool_names[i], scen->pool_names[i], SCENARIO_MAX_NAME - 1);

	for (size_t i = 0; i < num_services; i++)
		strncpy(service_names[i], scen->service_names[i], SCENARIO_MAX_NAME - 1);

	/* Use default service configs, matching by name where possible */
	ServiceConfig defaults[] = {
		{"search", 2.0, 0.85, 5.0, 0.5, 1, 3600.0, 0.7},
		{"checkout", 1.5, 0.95, 3.0, 0.25, 1, 7200.0, 0.7},
		{"bulk-export", 3.0, 0.70, 30.0, 0.75, 1, 1800.0, 0.7}
	};
	ServiceConfig fallback = {"unknown", 2.0, 0.85, 5.0, 0.5, 1, 3600.0, 0.7};

	for (size_t s = 0; s < num_services; s++) {
		int found = 0;
		for (int d = 0; d < 3; d++) {
			if (strcmp(service_names[s], defaults[d].service) == 0) {
				service_configs[s] = defaults[d];
				service_configs[s].service = service_names[s];
				found = 1;
				break;
			}
		}
		if (!found) {
			service_configs[s] = fallback;
			service_configs[s].service = service_names[s];
		}
	}
	num_service_configs = num_services;

	/* Default weights: 10 for all pool-service pairs */
	for (size_t s = 0; s < num_services; s++) {
		for (size_t p = 0; p < num_pools; p++) {
			base_weights[s][p] = 10;
			effective_weights[s][p] = 10;
		}
	}
}

/*
 * Initialize simulation state
 */
static void
init_simulation(void)
{
	srand(time(NULL));

	for (size_t s = 0; s < num_services; s++) {
		for (size_t p = 0; p < num_pools; p++) {
			pool_health[s][p].base_success_rate = 0.90 + rand_uniform() * 0.05;
			pool_health[s][p].base_response_time = 0.8 + rand_uniform() * 0.4;
			pool_health[s][p].current_success_rate = pool_health[s][p].base_success_rate;
			pool_health[s][p].current_response_time = pool_health[s][p].base_response_time;
			pool_health[s][p].degraded = 0;
			pool_health[s][p].cycles_until_recovery = 0;
			pool_health[s][p].cycles_until_incident = 10 + rand() % 30;

			memset(&stats_accum[s][p], 0, sizeof(stats_accum[s][p]));
		}
	}
}

/*
 * Simulate one cycle of pool health changes
 */
static void
simulate_pool_health(void)
{
	for (size_t s = 0; s < num_services; s++) {
		for (size_t p = 0; p < num_pools; p++) {
			PoolHealth *ph = &pool_health[s][p];

			if (ph->degraded) {
				ph->cycles_until_recovery--;
				if (ph->cycles_until_recovery <= 0) {
					ph->degraded = 0;
					ph->cycles_until_incident = 15 + rand() % 30;
					printf("  [SIM] %s/%s recovered\n",
					    pool_names[p], service_names[s]);
				}
			} else {
				ph->cycles_until_incident--;
				if (ph->cycles_until_incident <= 0) {
					ph->degraded = 1;
					ph->cycles_until_recovery = 5 + rand() % 15;
					printf("  [SIM] %s/%s incident started\n",
					    pool_names[p], service_names[s]);
				}
			}

			if (ph->degraded) {
				ph->current_success_rate = clamp(
				    rand_normal(0.65, 0.10), 0.3, 0.85);
				ph->current_response_time = clamp(
				    rand_normal(ph->base_response_time * 3.0, 0.5),
				    1.0, 10.0);
			} else {
				ph->current_success_rate = clamp(
				    rand_normal(ph->base_success_rate, 0.02),
				    0.80, 0.99);
				ph->current_response_time = clamp(
				    rand_normal(ph->base_response_time, 0.1),
				    0.3, 3.0);
			}

			StatsAccumulator *sa = &stats_accum[s][p];
			sa->success_sum += ph->current_success_rate;
			sa->success_sq_sum += ph->current_success_rate * ph->current_success_rate;
			sa->rt_sum += ph->current_response_time;
			sa->rt_sq_sum += ph->current_response_time * ph->current_response_time;
			sa->count++;
		}
	}
}

/*
 * Get moving average and stddev for a pool-service pair (simulation mode)
 */
static void
get_simulated_stats(int service, int pool,
    double *avg_success, double *stddev_success,
    double *avg_rt, double *stddev_rt)
{
	StatsAccumulator *sa = &stats_accum[service][pool];

	if (sa->count < 2) {
		*avg_success = 0.90;
		*stddev_success = 0.02;
		*avg_rt = 1.0;
		*stddev_rt = 0.3;
		return;
	}

	double n = (double)sa->count;

	*avg_success = sa->success_sum / n;
	double var_success = (sa->success_sq_sum / n) - (*avg_success * *avg_success);
	*stddev_success = (var_success > 0) ? sqrt(var_success) : 0.01;

	*avg_rt = sa->rt_sum / n;
	double var_rt = (sa->rt_sq_sum / n) - (*avg_rt * *avg_rt);
	*stddev_rt = (var_rt > 0) ? sqrt(var_rt) : 0.1;
}

/*
 * CLIPS injection helpers
 */
static void
inject_service_config(Environment *env, const ServiceConfig *cfg)
{
	char buf[512];
	snprintf(buf, sizeof(buf),
	    "(service-config (service %s) "
	    "(sigma-threshold %f) (min-success-rate %f) (max-response-time %f) "
	    "(weight-reduction %f) (min-weight %d) (restore-cooldown %f) "
	    "(service-degrade-threshold %f))",
	    cfg->service,
	    cfg->sigma_threshold, cfg->min_success_rate, cfg->max_response_time,
	    cfg->weight_reduction, cfg->min_weight, cfg->restore_cooldown,
	    cfg->service_degrade_threshold);
	AssertString(env, buf);
}

static void
inject_weight(Environment *env, const char *pool, const char *service,
    int base_weight, int eff_weight)
{
	char buf[256];
	snprintf(buf, sizeof(buf),
	    "(current-weight (pool %s) (service %s) "
	    "(base-weight %d) (effective-weight %d))",
	    pool, service, base_weight, eff_weight);
	AssertString(env, buf);
}

static void
inject_stats(Environment *env, const char *pool, const char *service,
    double timestamp, double rate_success, double rate_lost_race,
    double rate_302, double rate_timeout, double rate_ssl, double rate_other,
    double response_time, double avg_success, double avg_response_time,
    double stddev_success, double stddev_response_time)
{
	char buf[1024];
	snprintf(buf, sizeof(buf),
	    "(pool-service-stats "
	    "(pool %s) (service %s) (timestamp %f) "
	    "(rate-success %f) (rate-lost-race %f) (rate-302-unusual %f) "
	    "(rate-timeout %f) (rate-ssl-error %f) (rate-other %f) "
	    "(response-time %f) "
	    "(avg-success %f) (avg-response-time %f) "
	    "(stddev-success %f) (stddev-response-time %f))",
	    pool, service, timestamp,
	    rate_success, rate_lost_race, rate_302,
	    rate_timeout, rate_ssl, rate_other,
	    response_time,
	    avg_success, avg_response_time,
	    stddev_success, stddev_response_time);
	AssertString(env, buf);
}

static void
inject_scenario_record(Environment *env, const Scenario *scen,
    const ScenarioRecord *rec)
{
	const char *pool = scenario_pool_name(scen, rec->pool);
	const char *service = scenario_service_name(scen, rec->service);

	if (pool == NULL || service == NULL)
		return;

	inject_stats(env, pool, service, rec->timestamp,
	    rec->rate_success, rec->rate_lost_race, rec->rate_302,
	    rec->rate_timeout, rec->rate_ssl, rec->rate_other,
	    rec->response_time, rec->avg_success, rec->avg_response_time,
	    rec->stddev_success, rec->stddev_response_time);
}

/*
 * Retract all facts of a given template
 */
static void
retract_all(Environment *env, const char *template_name)
{
	Fact *fact = GetNextFact(env, NULL);
	while (fact != NULL) {
		Fact *next = GetNextFact(env, fact);
		if (strcmp(FactDeftemplate(fact)->header.name->contents,
		    template_name) == 0) {
			Retract(fact);
		}
		fact = next;
	}
}

/*
 * Clear transient facts between cycles
 */
static void
cleanup_cycle(Environment *env)
{
	retract_all(env, "current-weight");
	retract_all(env, "pool-service-stats");
	retract_all(env, "degradation");
	retract_all(env, "service-status");
	retract_all(env, "service-config");
}

/*
 * Callbacks
 */
static void
on_weight_adjustment(const char *pool, const char *service, int old_weight,
    int new_weight, const char *reason, double severity)
{
	printf("  ADJUST: %s/%s weight=%d->%d reason=%s severity=%.2f\n",
	    pool, service, old_weight, new_weight, reason, severity);

	for (size_t s = 0; s < num_services; s++) {
		if (strcmp(service_names[s], service) != 0)
			continue;
		for (size_t p = 0; p < num_pools; p++) {
			if (strcmp(pool_names[p], pool) != 0)
				continue;
			effective_weights[s][p] = new_weight;
			return;
		}
	}
}

static void
on_alert(const char *type, const char *service, const char *pool,
    const char *message)
{
	printf("  ALERT: type=%s service=%s pool=%s msg=%s\n",
	    type, service, pool ? pool : "(nil)", message);
}

/*
 * Process emitted facts
 */
static void
process_weight_adjustments(Environment *env)
{
	Fact *fact = GetNextFact(env, NULL);
	while (fact != NULL) {
		Fact *next = GetNextFact(env, fact);

		if (strcmp(FactDeftemplate(fact)->header.name->contents,
		    "weight-adjustment") == 0) {
			CLIPSValue pool, service, old_w, new_w, reason, severity;

			GetFactSlot(fact, "pool", &pool);
			GetFactSlot(fact, "service", &service);
			GetFactSlot(fact, "old-weight", &old_w);
			GetFactSlot(fact, "new-weight", &new_w);
			GetFactSlot(fact, "reason", &reason);
			GetFactSlot(fact, "severity", &severity);

			on_weight_adjustment(
			    pool.lexemeValue->contents,
			    service.lexemeValue->contents,
			    (int)old_w.integerValue->contents,
			    (int)new_w.integerValue->contents,
			    reason.lexemeValue->contents,
			    severity.floatValue->contents);

			Retract(fact);
		}
		fact = next;
	}
}

static void
process_alerts(Environment *env)
{
	Fact *fact = GetNextFact(env, NULL);
	while (fact != NULL) {
		Fact *next = GetNextFact(env, fact);

		if (strcmp(FactDeftemplate(fact)->header.name->contents, "alert") == 0) {
			CLIPSValue type, service, pool, message;

			GetFactSlot(fact, "type", &type);
			GetFactSlot(fact, "service", &service);
			GetFactSlot(fact, "pool", &pool);
			GetFactSlot(fact, "message", &message);

			on_alert(
			    type.lexemeValue->contents,
			    service.lexemeValue->contents,
			    pool.lexemeValue->contents,
			    message.lexemeValue->contents);

			Retract(fact);
		}
		fact = next;
	}
}

/*
 * Inject all service configs and weights
 */
static void
inject_configs_and_weights(Environment *env)
{
	for (size_t s = 0; s < num_service_configs; s++)
		inject_service_config(env, &service_configs[s]);

	for (size_t s = 0; s < num_services; s++) {
		for (size_t p = 0; p < num_pools; p++) {
			inject_weight(env, pool_names[p], service_names[s],
			    base_weights[s][p], effective_weights[s][p]);
		}
	}
}

/*
 * Print weight matrix
 */
static void
print_weights(void)
{
	printf("\n  Weights (base/eff):\n");
	printf("  %-12s", "");
	for (size_t p = 0; p < num_pools; p++)
		printf(" %14s", pool_names[p]);
	printf("\n");

	for (size_t s = 0; s < num_services; s++) {
		printf("  %-12s", service_names[s]);
		for (size_t p = 0; p < num_pools; p++) {
			char buf[16];
			snprintf(buf, sizeof(buf), "%d/%d",
			    base_weights[s][p], effective_weights[s][p]);
			printf(" %14s", buf);
		}
		printf("\n");
	}
	printf("\n");
}

/*
 * Run in simulation mode
 */
static void
run_simulation(Environment *env, int cycles)
{
	printf("Running simulation mode: %d cycles\n\n", cycles);

	init_defaults();
	init_simulation();
	print_weights();

	double timestamp = 1737300000.0;

	for (int i = 0; i < cycles; i++) {
		printf("=== Cycle %d (t=%.0f) ===\n", i, timestamp);

		simulate_pool_health();
		cleanup_cycle(env);
		inject_configs_and_weights(env);

		/* Inject simulated stats */
		for (size_t s = 0; s < num_services; s++) {
			for (size_t p = 0; p < num_pools; p++) {
				double avg_success, stddev_success, avg_rt, stddev_rt;
				get_simulated_stats(s, p, &avg_success, &stddev_success,
				    &avg_rt, &stddev_rt);

				PoolHealth *ph = &pool_health[s][p];
				double failure = 1.0 - ph->current_success_rate;
				double rate_timeout = ph->degraded ? failure * 0.4 : failure * 0.2;
				double rate_ssl = ph->degraded ? failure * 0.2 : failure * 0.1;
				double rate_302 = failure * 0.2;
				double rate_lost = failure * 0.1;
				double rate_other = failure - rate_timeout - rate_ssl - rate_302 - rate_lost;
				if (rate_other < 0)
					rate_other = 0;

				inject_stats(env, pool_names[p], service_names[s], timestamp,
				    ph->current_success_rate, rate_lost, rate_302,
				    rate_timeout, rate_ssl, rate_other,
				    ph->current_response_time,
				    avg_success, avg_rt, stddev_success, stddev_rt);
			}
		}

		Run(env, -1);
		process_weight_adjustments(env);
		process_alerts(env);

		timestamp += 60.0;

		if ((i + 1) % 10 == 0)
			print_weights();
	}

	printf("\nFinal state:\n");
	print_weights();
}

/*
 * Run in replay mode
 */
static void
run_replay(Environment *env, const char *path)
{
	Scenario *scen;
	ScenarioRecord rec;
	double current_timestamp = -1;
	int cycle = 0;
	int ret;

	scen = scenario_open_read(path);
	if (scen == NULL)
		err(1, "scenario_open_read: %s", path);

	printf("Replaying scenario: %s\n", path);
	printf("  Pools: %zu, Services: %zu, Records: %zu\n\n",
	    scen->num_pools, scen->num_services, scen->num_records);

	init_from_scenario(scen);
	print_weights();

	while ((ret = scenario_read(scen, &rec)) == 1) {
		/* New timestamp = new cycle */
		if (rec.timestamp != current_timestamp) {
			if (current_timestamp >= 0) {
				/* Process previous cycle */
				Run(env, -1);
				process_weight_adjustments(env);
				process_alerts(env);

				if ((cycle + 1) % 10 == 0)
					print_weights();

				cycle++;
				cleanup_cycle(env);
				inject_configs_and_weights(env);
			} else {
				/* First cycle */
				inject_configs_and_weights(env);
			}

			current_timestamp = rec.timestamp;
			printf("=== Cycle %d (t=%.0f) ===\n", cycle, current_timestamp);
		}

		inject_scenario_record(env, scen, &rec);
	}

	if (ret < 0)
		errx(1, "scenario_read error");

	/* Process final cycle */
	if (current_timestamp >= 0) {
		Run(env, -1);
		process_weight_adjustments(env);
		process_alerts(env);
	}

	printf("\nFinal state:\n");
	print_weights();

	scenario_close(scen);
}

static void
usage(void)
{
	fprintf(stderr, "usage: gov-sim [-s cycles] [-r scenario.pps]\n");
	fprintf(stderr, "  -s cycles   Run simulation mode for N cycles (default: 60)\n");
	fprintf(stderr, "  -r path     Replay scenario from file\n");
	exit(1);
}

int
main(int argc, char *argv[])
{
	Environment *env;
	Config cfg = {
		.mode = MODE_SIMULATE,
		.scenario_path = NULL,
		.sim_cycles = 60,
		.verbose = 0
	};
	int ch;

	while ((ch = getopt(argc, argv, "s:r:v")) != -1) {
		switch (ch) {
		case 's':
			cfg.mode = MODE_SIMULATE;
			cfg.sim_cycles = atoi(optarg);
			break;
		case 'r':
			cfg.mode = MODE_REPLAY;
			cfg.scenario_path = optarg;
			break;
		case 'v':
			cfg.verbose = 1;
			break;
		default:
			usage();
		}
	}

	/* Unveil paths */
	if (unveil(RULES_FILE, "r") == -1)
		err(1, "unveil %s", RULES_FILE);

	if (cfg.mode == MODE_REPLAY) {
		if (unveil(cfg.scenario_path, "r") == -1)
			err(1, "unveil %s", cfg.scenario_path);
	}

	if (unveil(NULL, NULL) == -1)
		err(1, "unveil lock");

	/* Create CLIPS environment */
	env = CreateEnvironment();
	if (env == NULL)
		errx(1, "CreateEnvironment failed");

	if (Load(env, RULES_FILE) != LE_NO_ERROR)
		errx(1, "failed to load %s", RULES_FILE);

	if (pledge("stdio rpath", NULL) == -1)
		err(1, "pledge");

	/* Run appropriate mode */
	printf("Proxy Pool Governor\n");
	printf("===================\n\n");

	if (cfg.mode == MODE_REPLAY)
		run_replay(env, cfg.scenario_path);
	else
		run_simulation(env, cfg.sim_cycles);

	DestroyEnvironment(env);
	return 0;
}