Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
8940 lines (8308 loc) · 464 KB
/
Copy pathProgram.cs
File metadata and controls
8940 lines (8308 loc) · 464 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using OpenTelemetry.Exporter;
using OpenTelemetry.Logs;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using CodeyBox.Agents;
using CodeyBox.Agents.Aider;
using CodeyBox.Agents.Antigravity;
using CodeyBox.Agents.Autohand;
using CodeyBox.Agents.CavemanCode;
using CodeyBox.Agents.Cline;
using CodeyBox.Agents.Crock;
using CodeyBox.Agents.Claude;
using CodeyBox.Agents.Cmd;
using CodeyBox.Agents.Codex;
using CodeyBox.Agents.Copilot;
using CodeyBox.Agents.Cursor;
using CodeyBox.Agents.Devin;
using CodeyBox.Agents.Gemini;
using CodeyBox.Agents.Goose;
using CodeyBox.Agents.Kilo;
using CodeyBox.Agents.Omp;
using CodeyBox.Agents.Continue;
using CodeyBox.Agents.Crush;
using CodeyBox.Agents.Opencode;
using CodeyBox.Agents.Pi;
using CodeyBox.Agents.Prime;
using CodeyBox.Agents.Qwen;
using CodeyBox.Agents.Vibe;
using CodeyBox.Agents.DotNetOpencode;
using CodeyBox.Agents.Unreal;
using CodeyBox.AdminSeed;
using CodeyBox.Api;
using CodeyBox.Api.Hubs;
using CodeyBox.Api.Majordomo;
using CodeyBox.Audit;
using CodeyBox.Audit.Llm;
using CodeyBox.Audit.Llm.PlanAudit;
using CodeyBox.Audit.Presets;
using CodeyBox.Audit.Shell;
using CodeyBox.Build.GitHubActions;
using CodeyBox.Build.MSBuild;
using CodeyBox.DotnetTestRunnerPlugin;
using CodeyBox.Core;
using CodeyBox.Deployment;
using CodeyBox.Git;
using CodeyBox.Orchestrator;
using CodeyBox.Projects;
using CodeyBox.Sandbox;
using CodeyBox.Sandbox.ArtifactProvenance;
using CodeyBox.Sandbox.Bubblewrap;
using CodeyBox.Sandbox.Incus;
using CodeyBox.Sandbox.Multipass;
using CodeyBox.Sandbox.MultipassRemote;
using CodeyBox.Sandbox.Process;
using CodeyBox.Sandbox.Sprites;
using CodeyBox.HostProcess;
using CodeyBox.Webhooks;
using CodeyBox.Upstream.GitHub;
using CodeyBox.Notifications;
using Serilog;
using Serilog.Events;
using Serilog.Extensions.Logging;
using Serilog.Filters;
using Serilog.Formatting.Compact;
// Disambiguate: both Serilog and MEL expose an ILogger interface.
// Program.cs only uses Serilog.Log (the static class) and MEL's ILogger<T>;
// declaring the alias keeps local function signatures unambiguous.
using ILogger = Microsoft.Extensions.Logging.ILogger;
// Converts a missing-required-setting startup failure into a clean
// diagnostic (message on stderr, conventional non-zero exit, no stack trace,
// no core dump). Scoped to RequiredConfigurationException only — every other
// unhandled exception keeps the runtime's existing crash behaviour.
RequiredConfigurationValidator.RegisterUnhandledExceptionHandler();
var builder = WebApplication.CreateBuilder(args);
// Optional extra-config file pointed at by CODEYBOX_EXTRA_CONFIG. Lets
// operator-side configuration (e.g. dev/test setups in a gitignored
// local/ directory) layer on top of the committed appsettings.json
// without copying files into the API project. Loaded LAST so it wins.
// reloadOnChange:true so an operator can edit this file without restarting
// CodeyBox — IOptionsMonitor<T> consumers will observe the new values within
// the framework's debounce window (~1 s).
{
var extra = Environment.GetEnvironmentVariable("CODEYBOX_EXTRA_CONFIG");
if (!string.IsNullOrEmpty(extra))
builder.Configuration.AddJsonFile(extra, optional: false, reloadOnChange: true);
}
// Default to loopback-only. Operators putting a TLS-terminating reverse
// proxy in front should override via ASPNETCORE_URLS or appsettings.
// Anything beyond localhost MUST be intentional, since the API can spawn
// sandboxes and trigger merges.
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_URLS"))
&& builder.Configuration["urls"] is null
&& builder.Configuration["Kestrel:Endpoints:Default:Url"] is null)
{
builder.WebHost.UseUrls("http://127.0.0.1:5000");
}
// ── Serilog bootstrap ─────────────────────────────────────────────────────
// Configured from CodeyBox:AuditLog section before the host builds so the
// logger is available from startup. UseSerilog() replaces the default MEL
// providers, so all ILogger<T> call sites continue to work unchanged.
{
var cbConf = builder.Configuration.GetSection("CodeyBox").Get<CodeyBoxOptions>()
?? new CodeyBoxOptions();
var auditOpts = cbConf.AuditLog;
var agentStreamOpts = cbConf.AgentStreams;
AuditLogStartup.ValidateAndPrepare(auditOpts);
using var bootstrapLoggerFactory = LoggerFactory.Create(static b => b.AddSerilog(dispose: false));
AgentStreamsOptions.ValidateAtStartup(
agentStreamOpts,
bootstrapLoggerFactory.CreateLogger("CodeyBox.AgentStreams"));
// When OTel export is enabled we forward Serilog events to the MEL provider
// pipeline (the OpenTelemetry logging provider added in the OTel section).
// UseSerilog(providers:) bridges every registered ILoggerProvider into this
// collection and the WriteTo.Providers sink fans events out to them, so the
// existing ILogger call sites flow to OTel with trace correlation while the
// console / file sinks stay owned by this single logger. Null (OTel off)
// keeps the original Serilog-only path with zero added overhead.
var otelLogForwarding = cbConf.Otel.Enabled ? new LoggerProviderCollection() : null;
var serilogConfig = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithThreadId()
.Enrich.WithProperty("Application", "CodeyBox")
.Enrich.With<SensitiveDataRedactionEnricher>()
.WriteTo.Console();
// Rolling plain-text mirror of the console stream. Replaces the
// historical `>>` shell-redirect of stdout to codeybox-orchestrator.run.log,
// which grew without bound (22 M+ lines / multi-GB by 2026-06) and made
// operator tail/grep return weeks-old lines. RunLogSink bounds it by size
// (RetainedFileCountLimit x MaxFileSizeBytes peak) and stamps every line
// with a full-date UTC timestamp. Both rotation knobs are re-read live
// (see ReadRunLogOptions), so they hot-reload without a restart; only the
// path stays pinned to its startup value. Disable via
// CodeyBox:AuditLog:ConsoleLog:Enabled=false if the operator manages
// run-log capture out of process.
// builder.Configuration reloads appsettings / CODEYBOX_EXTRA_CONFIG in
// place, so re-binding just the small ConsoleLog section here (at most
// once per second) is what makes the knobs hot-reloadable this early in
// bootstrap, before the DI container (and IOptionsMonitor) exists.
var runLogGate = new object();
var runLogCached = auditOpts.ConsoleLog;
var runLogCachedAt = DateTimeOffset.UtcNow;
ConsoleLogOptions ReadRunLogOptions()
{
lock (runLogGate)
{
if (DateTimeOffset.UtcNow - runLogCachedAt > TimeSpan.FromSeconds(1))
{
runLogCached = builder.Configuration
.GetSection("CodeyBox:AuditLog:ConsoleLog")
.Get<ConsoleLogOptions>() ?? new ConsoleLogOptions();
runLogCachedAt = DateTimeOffset.UtcNow;
}
return runLogCached;
}
}
if (auditOpts.ConsoleLog.Enabled)
{
serilogConfig = serilogConfig.WriteTo.Sink(
new RunLogSink(auditOpts.ConsoleLog.Path, ReadRunLogOptions));
}
serilogConfig = serilogConfig
.WriteTo.File(
formatter: new CompactJsonFormatter(),
path: auditOpts.Path,
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: auditOpts.RetainedDays,
fileSizeLimitBytes: auditOpts.MaxFileSizeBytes,
rollOnFileSizeLimit: true,
shared: false)
.WriteTo.Logger(lc => lc
.Filter.ByIncludingOnly(Matching.WithProperty<bool>("Audit", v => v))
.WriteTo.File(
formatter: new CompactJsonFormatter(),
path: auditOpts.AuditPath,
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: auditOpts.RetainedDays,
fileSizeLimitBytes: auditOpts.MaxFileSizeBytes,
rollOnFileSizeLimit: true,
shared: false));
if (otelLogForwarding is not null)
serilogConfig = serilogConfig.WriteTo.Providers(otelLogForwarding);
Log.Logger = serilogConfig.CreateLogger();
builder.Host.UseSerilog(Log.Logger, dispose: false, providers: otelLogForwarding);
}
// ── OpenTelemetry ─────────────────────────────────────────────────────────
// Off by default (OtelOptions.Enabled = false). Operators opt in by setting
// CodeyBox:Otel:Enabled=true and CodeyBox:Otel:OtlpEndpoint. When disabled,
// no OTel types are registered — zero overhead in the default configuration.
//
// The Prometheus scrape exporter (CodeyBox:Otel:Prometheus:Enabled) is a
// peer of the OTLP push exporter: enabling either one (or both) registers
// the metric provider, observable gauges, and CodeyBox meters. The
// tracing / logging providers and the OTLP push pipeline activate only
// when CodeyBox:Otel:Enabled=true; Prometheus alone keeps tracing and logs
// on the existing Serilog-only path.
{
var cbConf = builder.Configuration.GetSection("CodeyBox").Get<CodeyBoxOptions>()
?? new CodeyBoxOptions();
var otelOpts = cbConf.Otel;
OtelOptions.Validate(otelOpts);
var prometheusEnabled = otelOpts.Prometheus.Enabled;
var metricsEnabled = otelOpts.Enabled || prometheusEnabled;
if (metricsEnabled)
{
// service.version defaults to the API assembly version when the operator
// hasn't pinned a git SHA / release tag.
var serviceVersion = otelOpts.ServiceVersion
?? typeof(Program).Assembly.GetName().Version?.ToString();
// service.name honours the standard OTEL_SERVICE_NAME env var, falling
// back to the CodeyBox:Otel appsettings value — env wins so the standard
// OTel bootstrap can retarget identity without editing appsettings.
var serviceName = Environment.GetEnvironmentVariable("OTEL_SERVICE_NAME") is { Length: > 0 } envServiceName
? envServiceName
: otelOpts.ServiceName;
// Resource attributes shared by traces, metrics, and logs so the three
// signals correlate on identical service identity. service.instance.id
// and deployment.environment are added automatically; appsettings
// ResourceAttributes are applied, then any OTEL_RESOURCE_ATTRIBUTES env
// pairs last so the standard env contract overrides appsettings on key
// collision.
var instanceId = $"{Environment.MachineName}:{Environment.ProcessId}";
var deploymentEnv = builder.Environment.EnvironmentName;
void ConfigureResource(ResourceBuilder r)
{
r.AddService(serviceName, serviceVersion: serviceVersion, serviceInstanceId: instanceId);
if (!string.IsNullOrWhiteSpace(deploymentEnv))
r.AddAttributes(new[] { new KeyValuePair<string, object>("deployment.environment", deploymentEnv) });
if (otelOpts.ResourceAttributes.Count > 0)
r.AddAttributes(otelOpts.ResourceAttributes.Select(
kv => new KeyValuePair<string, object>(kv.Key, kv.Value)));
var envAttrs = OtelOptions.ParseResourceAttributesEnv(
Environment.GetEnvironmentVariable("OTEL_RESOURCE_ATTRIBUTES"));
if (envAttrs.Count > 0)
r.AddAttributes(envAttrs);
}
var otelBuilder = builder.Services.AddOpenTelemetry()
.ConfigureResource(ConfigureResource);
if (otelOpts.Enabled)
{
otelBuilder.WithTracing(t => t
.AddSource("CodeyBox.Pipeline")
.AddSource("CodeyBox.Sandbox")
.AddSource("CodeyBox.Upstream")
.AddSource("CodeyBox.Audit")
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddOtlpExporter(o => ConfigureOtlp(o, otelOpts)));
}
otelBuilder.WithMetrics(m =>
{
m.AddMeter("CodeyBox.Pipeline")
.AddMeter("CodeyBox.Sandbox")
.AddMeter("CodeyBox.Audit")
.AddMeter("CodeyBox.Upstream")
.AddMeter("CodeyBox.Coordinator")
.AddRuntimeInstrumentation();
if (otelOpts.Enabled)
m.AddOtlpExporter(o => ConfigureOtlp(o, otelOpts));
if (prometheusEnabled)
m.AddPrometheusExporter();
});
if (otelOpts.Enabled)
{
// Route the existing ILogger output through the OpenTelemetry logging
// provider. Serilog forwards events here via the LoggerProviderCollection
// wired above (writeToProviders); LogRecords are stamped with the active
// Activity's TraceId/SpanId for log↔trace correlation.
builder.Logging.AddOpenTelemetry(o =>
{
o.IncludeScopes = true;
o.IncludeFormattedMessage = true;
o.ParseStateValues = true;
var rb = ResourceBuilder.CreateDefault();
ConfigureResource(rb);
o.SetResourceBuilder(rb);
o.AddOtlpExporter(e => ConfigureOtlp(e, otelOpts));
});
}
// Observable gauges (work items by state, worker pool occupancy, active
// sandboxes, quota headroom) are registered only when at least one
// metric exporter is active to preserve the zero-overhead disabled path.
builder.Services.AddHostedService<CodeyBoxObservableMetrics>();
}
}
// AddOptions + PostConfigure instead of plain Configure so the AgentClasses
// override resolver runs after the binder. The default ConfigurationBinder
// merges arrays positionally — for AgentClasses that's a silent footgun
// (a shorter operator override exposes the base array's trailing element).
// The post-configure step REPLACES AgentClasses with the highest-precedence
// provider's view, and re-runs on every IOptionsMonitor reload.
// SandboxClasses gets the same treatment: it is the same shape of data
// (classes each holding a member array) with the same footgun.
builder.Services.AddOptions<CodeyBoxOptions>()
.Bind(builder.Configuration.GetSection("CodeyBox"))
.PostConfigure(opts => AgentClassesOverrideResolver.ApplyTo(opts, builder.Configuration))
.PostConfigure(opts => AgentClassesOverrideResolver.ApplySandboxClassesTo(opts, builder.Configuration));
// Artifact provenance: operator-owned, opt-in trust policy for plugin
// bundles and externally staged tool executables. Disabled by default; when
// enabled, admission is verified before load/provisioning. Validation fails
// fast at host start; the options remain hot-reloadable and the admission
// service keys cached verdicts by the live policy digest. The admission
// singleton is always registered (it is inert while the policy is disabled)
// so enabling the policy at runtime takes effect without a restart.
builder.Services.AddSingleton<IValidateOptions<ArtifactTrustOptions>, ArtifactTrustOptionsValidator>();
builder.Services.AddOptions<ArtifactTrustOptions>()
.Bind(builder.Configuration.GetSection(ArtifactTrustOptions.SectionName))
.ValidateOnStart();
builder.Services.AddSingleton(new ArtifactAdmissionService());
// Majordomo MCP surface: hot-reloadable policy (autonomy mode, per-turn
// blast-radius cap, identity name, turn window) mirroring the vocabulary's
// MajordomoOptions. Validation fails fast at host start rather than silently
// weakening the gate on a config typo, and reports the specific rule that
// failed via the IValidateOptions implementation.
builder.Services.AddSingleton<IValidateOptions<MajordomoServerOptions>, MajordomoServerOptionsValidator>();
builder.Services.AddOptions<MajordomoServerOptions>()
.Bind(builder.Configuration.GetSection(MajordomoServerOptions.SectionName))
.ValidateOnStart();
builder.Services.AddMajordomoMcp();
// Majordomo sandbox: long-lived, reusable-across-turns sandbox for the
// operator's assistant. Hot-reloadable options (network profile, idle bound,
// model backend) mirroring MajordomoSandboxOptions. Validation fails fast at
// host start rather than silently weakening the egress or credential posture.
builder.Services.AddSingleton<IValidateOptions<MajordomoSandboxOptions>, MajordomoSandboxOptionsValidator>();
builder.Services.AddOptions<MajordomoSandboxOptions>()
.Bind(builder.Configuration.GetSection(MajordomoSandboxOptions.SectionName))
.ValidateOnStart();
// Long-lived majordomo sandbox: one reusable sandbox for the operator's
// assistant, created on demand and torn down after the configured idle bound
// by MajordomoSandboxIdleService. It never touches the work-item dispatch
// path (no concurrency-gate permit, no worker-pool mutation), so the fleet's
// accounting is unchanged while it is alive. Both accessors re-read live
// options, so network-profile and idle-bound edits apply without a restart.
builder.Services.AddSingleton(sp => new MajordomoSandboxSession(
sp.GetRequiredService<ISandboxProvider>(),
() => sp.GetRequiredService<IOptionsMonitor<MajordomoSandboxOptions>>().CurrentValue,
() => sp.GetRequiredService<IOptionsMonitor<CodeyBoxOptions>>().CurrentValue.SandboxNetworkProfiles.Keys.ToArray(),
TimeProvider.System,
sp.GetRequiredService<ILoggerFactory>().CreateLogger<MajordomoSandboxSession>()));
builder.Services.AddHostedService(sp => new MajordomoSandboxIdleService(
sp.GetRequiredService<MajordomoSandboxSession>(),
() => sp.GetRequiredService<IOptionsMonitor<MajordomoSandboxOptions>>().CurrentValue,
TimeProvider.System,
sp.GetRequiredService<ILoggerFactory>().CreateLogger<MajordomoSandboxIdleService>()));
builder.Services.AddSingleton(sp => new SqliteDatabaseWriteGateFactory(
() => sp.GetRequiredService<IOptionsMonitor<CodeyBoxOptions>>().CurrentValue.SqliteWriteGate,
sp.GetRequiredService<ILoggerFactory>(),
TimeProvider.System));
// A BackgroundService fault stops the host via StopHost, which the host
// reports as a graceful shutdown (exit code 0) — indistinguishable from an
// intentional stop, so Restart=on-failure supervisors never restart after an
// orchestrator crash (e.g. a sustained SQLite write-gate outage escalated by
// the dispatch loop). Stated explicitly here (rather than relying on the
// framework default) because the exit-code contract below depends on it:
// faults are recorded on the tracker and mapped to a non-zero exit.
builder.Services.Configure<HostOptions>(static o =>
o.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.StopHost);
builder.Services.AddSingleton<BackgroundServiceFailureTracker>();
builder.Services.AddHostedService(sp => new SqliteDatabaseMaintenanceService(
sp.GetRequiredService<IOptions<CodeyBoxOptions>>().Value.StateDatabasePath,
() => sp.GetRequiredService<IOptionsMonitor<CodeyBoxOptions>>().CurrentValue.SqliteMaintenance,
sp.GetRequiredService<SqliteDatabaseWriteGateFactory>(),
sp.GetRequiredService<ILogger<SqliteDatabaseMaintenanceService>>(),
TimeProvider.System));
builder.Services.Configure<BuildScriptAuditorOptions>(builder.Configuration.GetSection("CodeyBox:BuildScriptAudit"));
// Regression-test-selection mode (Audit:TestSelection:Mode). Bound through
// AddOptions so IOptionsMonitor<TestSelectionOptions> hot-reloads the mode
// without a restart, with a fail-fast validator rejecting an unrecognised value
// at load rather than silently narrowing at audit time. Default 'all' keeps the
// emitted dotnet-test command byte-identical to today.
builder.Services.AddOptions<TestSelectionOptions>()
.Bind(builder.Configuration.GetSection(TestSelectionOptions.SectionName))
.Validate(
static opts => TestSelectionModeParser.TryParse(opts.Mode, out _),
$"{TestSelectionOptions.SectionName}:Mode must be one of: all, coverage-shadow, project-graph, coverage");
// Coverage-guided selection knobs (Audit:TestSelection:Coverage). Bound through
// AddOptions so IOptionsMonitor<CoverageTestSelectionOptions> hot-reloads the
// baseline location, age/size caps, and global targets without a restart, with
// a fail-fast validator rejecting a malformed section at load. Every consumer
// treats invalid/absent values as "no baseline" and falls back to the full
// suite — the validator only fails fast on structurally invalid config.
builder.Services.AddOptions<CoverageTestSelectionOptions>()
.Bind(builder.Configuration.GetSection(CoverageTestSelectionOptions.SectionName))
.Validate(
static opts => CoverageTestSelectionOptions.IsValid(opts),
$"{CoverageTestSelectionOptions.SectionName} is invalid");
// Soundness-report knobs (Audit:TestSelection:Soundness). Bound through
// AddOptions so IOptionsMonitor<TestSelectionSoundnessOptions> hot-reloads
// the calibration window and the report limit bound without a restart.
builder.Services.AddOptions<TestSelectionSoundnessOptions>()
.Bind(builder.Configuration.GetSection(TestSelectionSoundnessOptions.SectionName))
.Validate(
static opts => TestSelectionSoundnessOptions.IsValid(opts),
$"{TestSelectionSoundnessOptions.SectionName} is invalid");
// Standalone audit-run knobs (CodeyBox:AuditRuns). Disabled by default:
// queue implementation only until the operator enables a supported
// sandbox provider with real installed tools.
builder.Services.AddOptions<AuditRunOptions>()
.Bind(builder.Configuration.GetSection(AuditRunOptions.SectionName))
.Validate(
static opts => AuditRunOptions.IsValid(opts),
$"{AuditRunOptions.SectionName} is invalid");
// MSBuild structured build-diagnostics adapter (CodeyBox:MSBuildDiagnostics).
// Disabled by default: registers the hot-reloadable options plus the
// capability-based producer, but captures/parses nothing until the operator
// opts in. See docs/concepts/msbuild-diagnostics.md.
builder.Services.AddMSBuildBuildDiagnostics(builder.Configuration);
// GitHub Actions execution/evidence adapter (CodeyBox:GitHubActionsBuilds).
// Disabled by default: registers the hot-reloadable options plus the
// binding store only. The HTTP transport and provider need the credentialed
// overload with an explicit IGitHubTokenProvider; nothing dispatches, polls,
// or reads artifacts until the operator opts in AND pins an approved
// workflow. See docs/concepts/github-actions-builds.md.
builder.Services.AddGitHubActionsExternalBuilds(builder.Configuration);
// Post-merge baseline-production knobs
// (Audit:TestSelection:BaselineProduction). Bound through AddOptions so
// IOptionsMonitor<TestSelectionBaselineProductionOptions> hot-reloads the
// kill-switch, the sandboxed-job timeout, retention, and the guest producer
// binary without a restart.
builder.Services.AddOptions<TestSelectionBaselineProductionOptions>()
.Bind(builder.Configuration.GetSection(TestSelectionBaselineProductionOptions.SectionName))
.Validate(
static opts => TestSelectionBaselineProductionOptions.IsValid(opts),
$"{TestSelectionBaselineProductionOptions.SectionName} is invalid");
builder.Services.Configure<NotificationsOptions>(builder.Configuration.GetSection("CodeyBox:Notifications"));
builder.Services.Configure<AuditProgressApiOptions>(builder.Configuration.GetSection("CodeyBox:AuditProgressApi"));
// E2eExecutionOptions binds as a standalone section so the pool / dispatcher can
// take IOptionsMonitor<E2eExecutionOptions> directly without dragging the whole
// CodeyBoxOptions graph. The same section is also a property on CodeyBoxOptions
// (for the unbound-key validator's walk and operator visibility); the standalone
// binding is what gets hot-reloaded into the pool's MaxConcurrent.
builder.Services.AddOptions<E2eExecutionOptions>()
.Bind(builder.Configuration.GetSection("CodeyBox:E2eExecution"))
.Validate(static opts => IsValidE2eExecutionOptions(opts), "CodeyBox:E2eExecution is invalid")
.Validate(opts => IsValidE2eExecutionOptionsForConfig(opts, builder.Configuration), "CodeyBox:E2eExecution remote pool prerequisites are invalid");
// Post-implementation e2e-replay authoring/verification gate config. Bound
// through AddOptions so IOptionsMonitor<E2eReplayAuthoringOptions> hot-reloads
// the Enabled switch and thresholds without restart. Disabled by default; the
// gate is a no-op until a deployment opts in AND wires a cheap-model authoring
// driver (IE2eReplayAuthoringDriver).
builder.Services.AddOptions<E2eReplayAuthoringOptions>()
.Bind(builder.Configuration.GetSection("CodeyBox:E2eReplayAuthoring"))
.Validate(
static opts => opts.MaxReauthorAttempts >= E2eReplayAuthoringOptions.MinReauthorAttempts
&& opts.MaxReauthorAttempts <= E2eReplayAuthoringOptions.MaxAllowedReauthorAttempts,
"CodeyBox:E2eReplayAuthoring:MaxReauthorAttempts is out of range")
.Validate(
static opts => opts.VerificationTimeout > TimeSpan.Zero && opts.VerificationPollInterval > TimeSpan.Zero,
"CodeyBox:E2eReplayAuthoring verification timeout/poll interval must be positive")
.Validate(
static opts => !string.IsNullOrWhiteSpace(opts.AuthorModelId),
"CodeyBox:E2eReplayAuthoring:AuthorModelId is required");
// Register ProjectsOptions through AddOptions so IOptionsMonitor<ProjectsOptions>
// is wired into the framework's reload pipeline. PostConfigure layers our custom
// map-shaped binding (audit-type / language overrides / profile inheritance) on
// top of the framework's section.Bind() — these dictionaries don't bind from the
// standard Bind() path because their keys are dynamic JSON property names. On
// reload, both run again automatically.
builder.Services.AddOptions<ProjectsOptions>()
.Bind(builder.Configuration.GetSection("CodeyBox"))
.PostConfigure(opts => ProjectsOptionsBinder.ApplyCustomMaps(opts, builder.Configuration.GetSection("CodeyBox")));
// Immutable-field guard for CodeyBoxOptions. The startup snapshot is bound from
// IConfiguration when the service provider resolves it, after test/host
// ConfigureAppConfiguration hooks have had a chance to add their final sources.
// The retaining monitor cache is deliberate: stock IOptionsMonitor drops its
// prior cached value before validating a reload candidate, so a rejected edit
// would make CurrentValue throw until the next successful reload.
//
// AgentClassesOverrideResolver runs here AS WELL AS in the IOptions PostConfigure
// pipeline: this snapshot pre-seeds the RetainingOptionsMonitorCache below, and
// stock IOptionsMonitor returns that cached value without running the options
// factory, so without this call IOptionsMonitor<CodeyBoxOptions>.CurrentValue
// would observe the raw positional-merge AgentClasses until the first reload.
builder.Services.AddSingleton(sp =>
{
var config = sp.GetRequiredService<IConfiguration>();
var snapshot = config.GetSection("CodeyBox").Get<CodeyBoxOptions>() ?? new CodeyBoxOptions();
AgentClassesOverrideResolver.ApplyTo(snapshot, config);
AgentClassesOverrideResolver.ApplySandboxClassesTo(snapshot, config);
AgentFailureClassifier.SetAdditionalTransientNetworkPatterns(snapshot.TransientNetworkFailurePatterns);
ProviderTransientSignatureBinder.SyncStore(snapshot);
return new CodeyBoxOptionsStartupSnapshot(snapshot);
});
builder.Services.AddSingleton<IOptionsMonitorCache<CodeyBoxOptions>>(
sp => new RetainingOptionsMonitorCache<CodeyBoxOptions>(
sp.GetRequiredService<CodeyBoxOptionsStartupSnapshot>().Value,
opts =>
{
AgentFailureClassifier.SetAdditionalTransientNetworkPatterns(opts.TransientNetworkFailurePatterns);
if (!ProviderTransientSignatureBinder.TrySyncStore(opts, out var transientError))
{
sp.GetRequiredService<ILoggerFactory>().CreateLogger("CodeyBoxOptions")
.LogWarning("Hot-reload of CodeyBox:ProviderTransientSignatures rejected; keeping prior signatures: {Error}", transientError);
}
}));
builder.Services.TryAddSingleton<IProcessRunner, DefaultProcessRunner>();
builder.Services.TryAddSingleton<IOpenSshConfigResolver, OpenSshConfigResolver>();
builder.Services.TryAddSingleton<E2eRemoteHostValidation>();
builder.Services.TryAddSingleton<E2eRemotePoolConfigValidation>();
builder.Services.AddSingleton<IValidateOptions<CodeyBoxOptions>>(
sp => new ImmutableCodeyBoxOptionsValidator(
sp.GetRequiredService<CodeyBoxOptionsStartupSnapshot>().Value));
builder.Services.AddSingleton<IValidateOptions<CodeyBoxOptions>>(
sp => new CodeyBoxOptionsValidator(
sp.GetRequiredService<E2eRemotePoolConfigValidation>(),
sp.GetRequiredService<PluginSandboxProviderCatalog>().Kinds));
// Deploy-consistency probe. Refreshes the built-vs-checkout comparison at
// startup and warns while the service is still healthy when the working tree
// has moved ahead of bin/. Registered before UnboundConfigKeyHostedValidator
// so the unbound-key failure can name a stale build as its cause. Never
// throws; unknown revisions report unknown, not diverged.
builder.Services.AddSingleton<DeployConsistencyService>();
builder.Services.AddHostedService(sp => sp.GetRequiredService<DeployConsistencyService>());
// Unbound-key startup check. Walks the CodeyBox:* configuration sub-tree
// and surfaces any key that does not bind to a property on the typed
// options graph (the .NET binder silently drops these, which makes a
// misspelled or renamed key a no-op the operator never notices). Default
// behaviour is fail-fast at host start; switch to warn-only via
// CodeyBox:ConfigValidation:UnboundKeys:Mode="warn".
builder.Services.AddHostedService<UnboundConfigKeyHostedValidator>();
// Audit-budget ordering startup check. Rejects auditor-idle >= per-iteration,
// per-iteration >= item-stale, and item-stale >= sandbox wall clock with the
// offending config paths named, so a misordered budget fails startup instead
// of silently killing healthy long runs at audit time.
builder.Services.AddHostedService<AuditBudgetOrderingStartupValidator>();
// Rejects ProjectsOptions reloads that remove a project still holding
// non-terminal work items. Adding new projects passes cleanly.
builder.Services.AddSingleton<IValidateOptions<ProjectsOptions>, ProjectsOptionsRemovalValidator>();
// Sized from the resolved sandbox provider's capability, not the provider config
// name. SandboxTeardownMode is intentionally hot-reloadable at shutdown time, but
// HostOptions is captured at startup, so suspend-capable providers keep the
// RAM-snapshot ceiling even when startup config says Stop/Dispose. It is only a
// ceiling: shutdown still returns promptly when no suspend work is running.
// Using the DI-resolved provider keeps the deployment knowledge (name → provider)
// in the composition root and out of the Core policy. See ComputeHostShutdownTimeout.
builder.Services.AddOptions<HostOptions>()
.Configure<IOptions<CodeyBoxOptions>, ISandboxProvider, ILoggerFactory>(
(o, cbOptsAccessor, sandboxProvider, loggerFactory) =>
{
var providerSupportsSuspend = sandboxProvider is ISuspendingSandboxProvider;
o.ShutdownTimeout = Program.ComputeHostShutdownTimeout(
cbOptsAccessor.Value,
providerSupportsSuspend,
loggerFactory.CreateLogger("CodeyBox.HostShutdown"));
});
ApiKeyAuth.Configure(builder);
// --- Sandbox provider --------------------------------------------------------
// Selected by CodeyBox:SandboxProvider in config. Each option has a different
// security/setup trade-off — see docs/concepts/sandboxes.md.
//
// process — UNSAFE. No isolation. Dev only; refuses to load outside
// Development env unless DangerouslyAllowProcessSandbox=true.
// bubblewrap — Namespace + seccomp isolation, no daemon. Single package
// install. Shares the host kernel.
// multipass — Real Ubuntu VMs via Canonical's snap. Separate guest
// kernel. Single 'snap install multipass' on Ubuntu, no
// podman / OCI runtime / /etc edits. ~10-30s VM launch.
// incus — Real VMs backed by a snapshot-capable Incus storage pool.
// Baseline clones are copy-on-write and host directories are
// shared through explicitly selected virtiofs devices.
// sprites — Fly.io hosted Firecracker microVMs via sprites.dev. Requires
// SPRITES_TOKEN (or configured token env var).
builder.Services.AddSingleton<ISandboxProvider>(SelectSandboxProvider);
// Colocated executor: the in-process executor host giving single-host
// deployments working local phase execution with no configuration. Every
// knob carries a safe default and validation fails fast at host start, so an
// operator who configures nothing still gets the executor path. The phase
// handler is optional here (none is composed yet): without one the host
// reports no runner and any dispatch to it fails loudly instead of silently
// running elsewhere.
builder.Services.AddSingleton<IValidateOptions<ColocatedExecutorOptions>, ColocatedExecutorOptionsValidator>();
builder.Services.AddOptions<ColocatedExecutorOptions>()
.Bind(builder.Configuration.GetSection(ColocatedExecutorOptions.SectionName))
.ValidateOnStart();
builder.Services.AddSingleton(sp => new ColocatedExecutorHost(
sp.GetRequiredService<ISandboxProvider>(),
() => sp.GetRequiredService<IOptionsMonitor<ColocatedExecutorOptions>>().CurrentValue,
() => sp.GetRequiredService<IOptionsMonitor<CodeyBoxOptions>>().CurrentValue.ExecutorPhaseDispatch,
sp.GetService<IExecutorPhaseHandler>(),
tracker: new ExecutorSandboxTracker(),
loggerFactory: sp.GetRequiredService<ILoggerFactory>(),
repositoriesRootAccessor: () => sp.GetRequiredService<IGitHost>().RepositoriesRootDirectory));
builder.Services.AddSingleton<IExecutorPhaseTransportFactory>(sp =>
new ColocatedExecutorTransportFactory(sp.GetRequiredService<ColocatedExecutorHost>()));
// Remote phase-dispatch rendezvous: the poll-driven protocol's
// orchestrator-side state (pending queues, in-flight dispatches, chunk
// relay) plus the stage-out upload registry backing the two-call complete
// protocol. Both live as long as the process; the broker fails pending
// dispatches and deletes temp archives on shutdown. Reached only through the
// executor-initiated phase endpoints below — the orchestrator never dials
// an executor.
builder.Services.AddSingleton(sp => new ExecutorPhaseBroker(
() => sp.GetRequiredService<IOptionsMonitor<CodeyBoxOptions>>().CurrentValue.ExecutorPhaseDispatch,
log: sp.GetRequiredService<ILoggerFactory>().CreateLogger<ExecutorPhaseBroker>()));
builder.Services.AddSingleton<ExecutorPhaseStageOutUploads>();
builder.Services.AddSingleton<TimeProvider>(TimeProvider.System);
builder.Services.AddSingleton<Func<ExecutorPhaseDispatchOptions>>(sp =>
() => sp.GetRequiredService<IOptionsMonitor<CodeyBoxOptions>>().CurrentValue.ExecutorPhaseDispatch);
// Member-keyed provider registry for sandbox placement. Each provider kind
// named by a SandboxClass member is constructed once here (via the same
// BuildSandboxProviderInner the singleton uses, or via the plugin catalog for
// plugin-contributed kinds) and shared across the members
// naming it; lookup is by normalised kind so registration order never affects
// resolution. Each instance carries an admission wrapper whose gate is
// DERIVED from the member catalog (see ISandboxProviderRegistry
// .SyncKindCapacities): the gate target is the sum of member capacities
// naming the kind, so the kind gate always fits the member gates beneath it
// and never clamps them — real admission happens once, at the member gate
// inside SandboxPlacementAcquirer, while the kind wrapper keeps owning
// lifecycle tracking, metrics, and capability preservation. No provider kind
// is named anywhere outside this factory: core and pipeline code resolve
// through the registry.
builder.Services.AddSingleton<ISandboxProviderRegistry>(sp => new SandboxProviderRegistry(
kind => BuildRegistrySandboxProvider(sp, kind),
sp.GetRequiredService<ILoggerFactory>().CreateLogger<SandboxProviderRegistry>(),
sp.GetRequiredService<PluginSandboxProviderCatalog>().Kinds));
// B1: register baseline-image capabilities as derived views of the selected
// provider. Providers without baseline support (process / bubblewrap) receive
// null-object implementations, so consumers can depend on the capability
// without knowing which concrete provider is active.
builder.Services.AddSingleton(sp =>
sp.GetRequiredService<ISandboxProvider>() as IBaselineImageResolver
?? NullBaselineImageResolver.Instance);
builder.Services.AddSingleton(sp =>
sp.GetRequiredService<ISandboxProvider>() as IBaselineImageProvisioner
?? NullBaselineImageProvisioner.Instance);
static void ConfigureOtlp(OtlpExporterOptions o, OtelOptions opts)
{
// Honour the standard OTel env contract: when OTEL_EXPORTER_OTLP_ENDPOINT /
// OTEL_EXPORTER_OTLP_HEADERS are set we leave the exporter's SDK defaults in
// place (the SDK reads those vars itself, including the http path-append
// semantics), so env overrides appsettings. We only assign from
// CodeyBox:Otel when the corresponding env var is absent.
var envEndpoint = Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_ENDPOINT");
if (string.IsNullOrWhiteSpace(envEndpoint) && !string.IsNullOrWhiteSpace(opts.OtlpEndpoint))
o.Endpoint = new Uri(opts.OtlpEndpoint);
// OTEL_EXPORTER_OTLP_PROTOCOL is part of the same env contract: when it is
// set the SDK reads it itself, so forcing the appsettings protocol here would
// silently override an env-only deployment (e.g. http/protobuf on :4318 while
// appsettings still defaults to grpc). Only assign from CodeyBox:Otel when the
// env var is absent.
var envProtocol = Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_PROTOCOL");
if (string.IsNullOrWhiteSpace(envProtocol))
o.Protocol = opts.ExportProtocol == "httpprotobuf"
? OtlpExportProtocol.HttpProtobuf
: OtlpExportProtocol.Grpc;
var envHeaders = Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_HEADERS");
if (string.IsNullOrWhiteSpace(envHeaders) && !string.IsNullOrEmpty(opts.OtlpHeaders))
o.Headers = opts.OtlpHeaders;
}
static ISandboxProvider SelectSandboxProvider(IServiceProvider sp)
{
var opts = sp.GetRequiredService<IOptions<CodeyBoxOptions>>().Value;
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
var startupLog = loggerFactory.CreateLogger("CodeyBox.Sandbox");
var environment = sp.GetRequiredService<IHostEnvironment>();
var kind = SandboxProviderSelection.ResolveConfiguredKind(
opts.SandboxProvider,
sp.GetRequiredService<IConfiguration>(),
environment,
startupLog);
var hostPlatformEarly = CodeyBox.Core.HostPlatformSupport.HostOperatingSystem.Current;
var pluginKindsEarly = sp.GetRequiredService<PluginSandboxProviderCatalog>().Kinds;
if (!CodeyBox.Core.HostPlatformSupport.IsProviderSupportedOnHost(kind, hostPlatformEarly, pluginKindsEarly))
{
throw new InvalidOperationException(
$"CodeyBox:SandboxProvider '{kind}' is not supported on {hostPlatformEarly.Name}: " +
CodeyBox.Core.HostPlatformSupport.GetUnsupportedReason(kind, hostPlatformEarly, pluginKindsEarly));
}
// Plain (non-reloadable) kinds are owned by the member-keyed registry:
// the singleton and any member naming the kind share the exact same
// admission-wrapped instance, so lifecycle inventory is never split
// across two instances of one backend. Reloadable kinds keep their
// dedicated cutover router below.
if (!SandboxProviderKinds.SupportsHotReload(kind))
{
return sp.GetRequiredService<ISandboxProviderRegistry>().EnsureKind(kind);
}
ISandboxProvider inner = BuildReloadableSandboxProvider(sp, loggerFactory);
var hostPlatform = hostPlatformEarly;
LogSandboxEgressClassification(kind, hostPlatform, startupLog);
SandboxProviderSelection.ValidateWorkloadTrust(
inner,
opts,
sp.GetRequiredService<IConfiguration>(),
environment);
var orchestratorOptions = sp.GetRequiredService<OrchestratorOptions>();
startupLog.LogInformation(
"Sandbox admission control: provider={Provider}, MaxConcurrentSandboxes={MaxConcurrentSandboxes}",
inner.Name,
orchestratorOptions.MaxConcurrentSandboxes);
if (inner is ISandboxHostPoolSnapshot hostPool)
RemoteHostPoolCapacityLogger.Log(hostPool, startupLog);
LogSandboxProviderCapabilities(inner, startupLog);
var pipelineTuning = sp.GetRequiredService<PipelineTuningSnapshot>();
return SandboxAdmissionControlledProvider.Wrap(
inner,
orchestratorOptions.MaxConcurrentSandboxes,
loggerFactory.CreateLogger<SandboxAdmissionControlledProvider>(),
waitWarningThresholdProvider: () => pipelineTuning.Current.SandboxPermitWaitWarningThreshold);
}
static ISandboxProvider BuildRegistrySandboxProvider(IServiceProvider sp, string kind)
{
var opts = sp.GetRequiredService<IOptions<CodeyBoxOptions>>().Value;
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
var startupLog = loggerFactory.CreateLogger("CodeyBox.Sandbox.Registry");
var environment = sp.GetRequiredService<IHostEnvironment>();
var pluginCatalog = sp.GetRequiredService<PluginSandboxProviderCatalog>();
var isPluginKind = pluginCatalog.IsPluginKind(kind);
if (!SandboxProviderKinds.IsRegistered(kind) && !isPluginKind)
{
throw new InvalidOperationException(
$"Unregistered sandbox provider kind '{kind}'. Registered providers: " +
$"{CodeyBox.Core.HostPlatformSupport.FormatKnownProviders(pluginCatalog.Kinds)}. " +
"The kind is NOT silently falling back to another provider.");
}
var hostPlatform = CodeyBox.Core.HostPlatformSupport.HostOperatingSystem.Current;
if (!CodeyBox.Core.HostPlatformSupport.IsProviderSupportedOnHost(kind, hostPlatform, pluginCatalog.Kinds))
{
throw new InvalidOperationException(
$"Sandbox provider kind '{kind}' is not supported on {hostPlatform.Name}: " +
CodeyBox.Core.HostPlatformSupport.GetUnsupportedReason(kind, hostPlatform, pluginCatalog.Kinds));
}
ISandboxProvider inner;
if (isPluginKind && pluginCatalog.TryGetProvider(kind, out var pluginProvider))
{
inner = pluginProvider;
startupLog.LogInformation(
"Sandbox provider registry: kind '{Kind}' is plugin-contributed by '{PluginId}' (provider={Provider}); " +
"platform support and workload-trust gates apply exactly as for built-in kinds.",
kind.Trim().ToLowerInvariant(),
pluginCatalog.PluginIdFor(kind),
inner.Name);
}
else
{
inner = BuildSandboxProviderInner(sp, opts, environment, startupLog, loggerFactory, kind);
}
SandboxProviderSelection.ValidateWorkloadTrust(
inner,
opts,
sp.GetRequiredService<IConfiguration>(),
environment);
LogSandboxEgressClassification(kind, hostPlatform, startupLog);
var orchestratorOptions = sp.GetRequiredService<OrchestratorOptions>();
var pipelineTuning = sp.GetRequiredService<PipelineTuningSnapshot>();
startupLog.LogInformation(
"Sandbox admission control: provider={Provider}, MaxConcurrentSandboxes={MaxConcurrentSandboxes}",
inner.Name,
orchestratorOptions.MaxConcurrentSandboxes);
if (inner is ISandboxHostPoolSnapshot hostPool)
RemoteHostPoolCapacityLogger.Log(hostPool, startupLog);
LogSandboxProviderCapabilities(inner, startupLog);
startupLog.LogInformation(
"Sandbox provider registry: constructed kind '{Kind}' (provider={Provider}, MaxConcurrentSandboxes={MaxConcurrentSandboxes})",
kind,
inner.Name,
orchestratorOptions.MaxConcurrentSandboxes);
return SandboxAdmissionControlledProvider.Wrap(
inner,
orchestratorOptions.MaxConcurrentSandboxes,
loggerFactory.CreateLogger<SandboxAdmissionControlledProvider>(),
waitWarningThresholdProvider: () => pipelineTuning.Current.SandboxPermitWaitWarningThreshold);
}
/// <summary>
/// Logs the host-owned egress-enforcement classification for one constructed provider
/// kind, so an operator can see which of their providers actually contain network
/// egress and which do not. <c>NotEnforced</c> (every plugin kind, plus bubblewrap
/// and process) is logged as a warning stating where such a provider may be used.
/// A kind opted into <c>CodeyBox:EgressVerification</c> stays <c>NotEnforced</c>
/// here — verification is granted per sandbox by placement, never statically.
/// </summary>
static void LogSandboxEgressClassification(
string kind,
CodeyBox.Core.HostPlatformSupport.HostOperatingSystem hostPlatform,
ILogger startupLog)
{
var enforcement = CodeyBox.Core.HostPlatformSupport.GetEgressEnforcement(kind);
if (enforcement == CodeyBox.Core.EgressEnforcementLocation.EnforcedOnRemoteExecutorHost)
{
startupLog.LogInformation(
"Sandbox egress enforcement for provider '{Provider}' lives on the remote Linux executor host; " +
"the {Host} orchestrator host needs no packet filter, but the executor must have " +
"scripts/setup-host-networks.sh applied (see docs/concepts/host-platforms.md).",
kind,
hostPlatform.Name);
return;
}
if (enforcement == CodeyBox.Core.EgressEnforcementLocation.EnforcedOnOrchestratorHost)
{
startupLog.LogInformation(
"Sandbox egress enforcement for provider '{Provider}' lives on the {Host} orchestrator host " +
"(Linux nftables bridges; see scripts/setup-host-networks.sh).",
kind,
hostPlatform.Name);
return;
}
if (enforcement == CodeyBox.Core.EgressEnforcementLocation.EnforcedOnProviderHostVerified)
{
// Defensive: the static switch never returns the verified value (it is
// per-sandbox, via SandboxEgressPolicy.EffectiveEnforcement). Logged
// without the NotEnforced warning so a future static source of this
// value stays explicit — and still never above orchestrator-host
// enforcement.
startupLog.LogInformation(
"Sandbox egress enforcement for provider '{Provider}': {Classification}.",
kind,
CodeyBox.Core.SandboxEgressPolicy.DescribeEgressEnforcement(kind));
return;
}
startupLog.LogWarning(
"Sandbox provider '{Provider}': {Classification}. " +
"It may only serve sandboxes with no named network profile and must never be described as isolation.",
kind,
CodeyBox.Core.SandboxEgressPolicy.DescribeEgressEnforcement(kind));
}
static void LogSandboxProviderCapabilities(ISandboxProvider provider, ILogger startupLog)
{
IReadOnlyList<ISandboxProvider> registered = provider is ReloadableSandboxProvider reloadable
? reloadable.RegisteredProviders
: [provider];
var matrix = SandboxCapabilities.FormatMatrix(registered);
startupLog.LogInformation(
"Registered sandbox provider capabilities: {CapabilitiesMatrix}",
matrix);
}
static ISandboxProvider BuildSandboxProviderInner(
IServiceProvider sp,
CodeyBoxOptions opts,
IHostEnvironment environment,
ILogger startupLog,
ILoggerFactory loggerFactory,
string kind)
{
// Provider construction lives in the shared factory
// (SharedSandboxProviderFactory) so the orchestrator and the executor
// host cannot drift apart: adding a kind means editing the factory, and
// the arms below only attach orchestrator-side option shaping (plugins,
// disk guard, banners, transports). Kinds with no arm fall through to
// the factory with default options, so a new factory kind needs no edit
// here unless it needs orchestrator-side tuning.
return kind switch
{
SandboxProviderKinds.Process => BuildProcess(sp, opts, environment, startupLog, loggerFactory),
SandboxProviderKinds.Bubblewrap => SharedSandboxProviderFactory.Build(
SandboxProviderKinds.Bubblewrap,
new SandboxProviderBuildArgs
{
Loggers = loggerFactory,
BubblewrapOptions = () => new BubblewrapSandboxOptions(),
Timings = sp.GetService<ITimingStore>(),
}),
SandboxProviderKinds.Multipass => BuildMultipass(
opts,
sp,
loggerFactory,
startupLog,
sp.GetService<ITimingStore>(),
sp.GetService<ISandboxResourceUsageStore>()),
SandboxProviderKinds.Incus => BuildIncus(
sp,
loggerFactory,
sp.GetService<ITimingStore>(),
sp.GetService<ISandboxResourceUsageStore>()),
SandboxProviderKinds.MultipassRemote => BuildMultipassRemote(sp, loggerFactory),
SandboxProviderKinds.Sprites => BuildSprites(sp, loggerFactory, startupLog),
_ => SharedSandboxProviderFactory.Build(
kind,
new SandboxProviderBuildArgs
{
Loggers = loggerFactory,
ProcessRunner = sp.GetService<IProcessRunner>(),
Timings = sp.GetService<ITimingStore>(),
ResourceUsage = sp.GetService<ISandboxResourceUsageStore>(),
}),
};
}
static IE2eExecutionPool BuildE2eExecutionPool(IServiceProvider sp)
{
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
var e2eOptions = sp.GetRequiredService<IOptionsMonitor<E2eExecutionOptions>>();
var poolKind = (e2eOptions.CurrentValue.PoolKind ?? "remote-ssh").Trim().ToLowerInvariant();
var environment = sp.GetRequiredService<IHostEnvironment>();
var startupOptions = sp.GetRequiredService<IOptionsMonitor<CodeyBoxOptions>>().CurrentValue;
if (poolKind == "local" && !environment.IsDevelopment())
{
throw RequiredConfigurationValidator.CreateAggregateException(
sp.GetRequiredService<IConfiguration>(),
environment,
RequiredConfigurationValidator.E2eLocalPoolMessage);
}
if (poolKind == "remote-ssh" && e2eOptions.CurrentValue.Enabled)
{
ValidateEnabledRemoteE2eConfig(
e2eOptions.CurrentValue,
startupOptions,
sp.GetRequiredService<E2eRemotePoolConfigValidation>());
}
if (poolKind == "remote-ssh")
{
return BuildRemoteE2eExecutionPool(sp, loggerFactory, e2eOptions);
}
ISandboxProvider provider = poolKind switch
{
"local" => BuildE2eLocalSandboxProvider(sp, loggerFactory),
_ => throw new InvalidOperationException(
$"Unknown CodeyBox:E2eExecution:PoolKind '{e2eOptions.CurrentValue.PoolKind}'. Valid: local, remote-ssh"),
};
return new LocalE2eExecutionPool(
provider,
e2eOptions,
loggerFactory.CreateLogger<LocalE2eExecutionPool>(),
fallbackImageReference: () => sp.GetRequiredService<IOptionsMonitor<CodeyBoxOptions>>().CurrentValue.SandboxImageReference,
name: poolKind);
}
static IE2eExecutionPool BuildRemoteE2eExecutionPool(
IServiceProvider sp,
ILoggerFactory loggerFactory,
IOptionsMonitor<E2eExecutionOptions> e2eOptions)
{
var currentOptions = sp.GetRequiredService<IOptionsMonitor<CodeyBoxOptions>>().CurrentValue;
var hostConfigs = GetE2eRemoteHostConfigs(currentOptions);
if (hostConfigs.Count == 0)
{
var provider = BuildE2eMultipassRemote(sp, loggerFactory, hostIndex: 0);
return new LocalE2eExecutionPool(
provider,
e2eOptions,
loggerFactory.CreateLogger<LocalE2eExecutionPool>(),
fallbackImageReference: () => sp.GetRequiredService<IOptionsMonitor<CodeyBoxOptions>>().CurrentValue.SandboxImageReference,
name: "remote-ssh");
}
var hosts = hostConfigs