-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathControlHttpServerTest.java
More file actions
1606 lines (1536 loc) · 123 KB
/
Copy pathControlHttpServerTest.java
File metadata and controls
1606 lines (1536 loc) · 123 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
package com.bencodez.votingplugin.control.http;
import com.bencodez.votingplugin.control.auth.CredentialStore;
import com.bencodez.votingplugin.control.artifact.ArtifactStore;
import com.bencodez.votingplugin.control.domain.InMemoryNodeRegistry;
import com.bencodez.votingplugin.control.protocol.ControlIdentity;
import com.bencodez.votingplugin.control.protocol.BackendServerIdentity;
import com.bencodez.votingplugin.control.protocol.NodeStatus;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Files;
import java.time.Clock;
import java.time.Duration;
import java.util.UUID;
import java.util.Map;
import java.util.HexFormat;
import java.security.MessageDigest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.TimeUnit;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpPrincipal;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.*;
class ControlHttpServerTest {
private static final String SESSION = "00000000-0000-0000-0000-000000000001";
@TempDir Path directory;
private ControlHttpServer server;
private CredentialStore credentials;
private String nodeToken;
private String adminToken;
private HttpClient client;
private ObjectMapper json;
private URI base;
@BeforeEach void start() throws Exception {
credentials = new CredentialStore(directory);
nodeToken = credentials.rotateNode("proxy-a");
adminToken = credentials.rotateAdmin();
server = new ControlHttpServer(new InetSocketAddress("127.0.0.1", 0),
new InMemoryNodeRegistry(Clock.systemUTC(), Duration.ofSeconds(90)),
new ControlIdentity(UUID.fromString("00000000-0000-0000-0000-000000000099"), "test", 1),
credentials, "00000000-0000-0000-0000-000000000123");
server.start();
base = URI.create("http://127.0.0.1:" + server.port());
client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
json = new ObjectMapper();
}
@AfterEach void stop() {
if (server != null) {
server.close();
}
}
@Test void deploymentEligibilityRendersEligibleBootstrapAndWarningStates() throws Exception {
org.junit.jupiter.api.Assumptions.assumeTrue(nodeAvailable(),
"Node.js is required to execute the WebUI behavior regression");
String app;
try (InputStream input = ControlHttpServerTest.class.getResourceAsStream("/web/app.js")) {
assertNotNull(input);
app = new String(input.readAllBytes(), StandardCharsets.UTF_8);
}
int start = app.indexOf("function deploymentTargets()");
int end = app.indexOf("function selectNodePage(", start);
assertTrue(start >= 0 && end > start, "deployment eligibility functions must remain discoverable");
String actualFunctions = app.substring(start, end);
String harness = """
const MAX_OPERATION_TARGETS = 100;
const MAX_DEPLOYMENT_BATCHES = 100;
let authenticated = true;
let logoutInFlight = false;
let deploymentInFlight = false;
const deploymentJar = {files: [{}]};
const deploymentEligibility = {textContent: '', className: ''};
const deployPlugin = {disabled: false};
function text(element, value) { element.textContent = value; return element; }
let allNodeItems = [];
""" + actualFunctions + """
function capture(nodes) {
allNodeItems = nodes;
renderDeploymentEligibility();
return {
text: deploymentEligibility.textContent,
className: deploymentEligibility.className,
disabled: deployPlugin.disabled
};
}
const capable = {online: true, acceptedCapabilities: ['plugin.deploy.v1']};
const oldA = {online: true, acceptedCapabilities: []};
const oldB = {online: true, acceptedCapabilities: ['config.files.v1']};
const mixed = capture([capable, oldA, oldB]);
const bootstrap = capture([oldA, oldB, {online: true, acceptedCapabilities: []}]);
const empty = capture([]);
process.stdout.write(JSON.stringify({mixed, bootstrap, empty}));
""";
Process process = new ProcessBuilder("node", "-e", harness).redirectErrorStream(true).start();
String output;
try {
if (!process.waitFor(5, TimeUnit.SECONDS)) fail("WebUI eligibility test timed out");
output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
assertEquals(0, process.exitValue(), output);
} finally {
terminateProcess(process);
}
JsonNode states = json.readTree(output);
assertEquals("1/3 connected nodes eligible · 2 connected nodes need a one-time VotingPlugin update with verified staging support",
states.path("mixed").path("text").asText());
assertEquals("pill online", states.path("mixed").path("className").asText());
assertFalse(states.path("mixed").path("disabled").asBoolean());
assertEquals("0/3 connected nodes eligible · 3 connected nodes need a one-time VotingPlugin update with verified staging support",
states.path("bootstrap").path("text").asText());
assertEquals("pill warning", states.path("bootstrap").path("className").asText());
assertTrue(states.path("bootstrap").path("disabled").asBoolean());
assertEquals("0/0 connected nodes eligible", states.path("empty").path("text").asText());
assertEquals("pill neutral", states.path("empty").path("className").asText());
assertTrue(states.path("empty").path("disabled").asBoolean());
}
private static boolean nodeAvailable() {
Process process = null;
try {
process = new ProcessBuilder("node", "--version").redirectErrorStream(true).start();
if (!process.waitFor(5, TimeUnit.SECONDS)) return false;
return process.exitValue() == 0;
} catch (IOException | InterruptedException failure) {
if (failure instanceof InterruptedException) Thread.currentThread().interrupt();
return false;
} finally {
terminateProcess(process);
}
}
private static void terminateProcess(Process process) {
if (process == null || !process.isAlive()) return;
process.destroyForcibly();
boolean interrupted = false;
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(1);
while (process.isAlive()) {
long remaining = deadline - System.nanoTime();
if (remaining <= 0) break;
try {
if (process.waitFor(remaining, TimeUnit.NANOSECONDS)) break;
} catch (InterruptedException failure) {
interrupted = true;
}
}
if (interrupted) Thread.currentThread().interrupt();
}
@Test void artifactInputClosesWhenResponseHeadersFail() {
AtomicBoolean closed = new AtomicBoolean();
InputStream input = new ByteArrayInputStream(new byte[] {1}) {
@Override public void close() throws IOException { closed.set(true); super.close(); }
};
ArtifactStore.Artifact artifact = new ArtifactStore.Artifact("a".repeat(64), "VotingPlugin.jar", 1);
assertThrows(IOException.class,
() -> ControlHttpServer.sendArtifact(new FailingHeadersExchange(), artifact, input));
assertTrue(closed.get());
}
@Test void healthRouteIsExactUnknownRoutesAreStructuredAndMethodsAreIntentional() throws Exception {
HttpResponse<String> web = get("/", null);
assertEquals(200, web.statusCode());
assertTrue(web.body().contains("VotingPlugin Control"));
assertTrue(web.body().contains("data-tab=\"overview\""));
assertTrue(web.body().contains("data-tab=\"network\""));
assertTrue(web.body().contains("id=\"server-picker\""));
assertTrue(web.body().contains("Full YAML"));
assertTrue(web.body().contains("Comment support unknown"));
assertTrue(web.body().contains("Sync site definitions across backends"));
assertTrue(web.body().contains("Target-only sites and every reward section stay local"));
assertFalse(web.body().contains("Load current values"));
assertTrue(web.body().contains("Retry read"));
assertTrue(web.body().contains("id=\"quick-party-enabled\""));
assertTrue(web.body().contains("id=\"deployment-jar\""));
assertTrue(web.body().contains("Upload and stage on eligible servers"));
assertTrue(web.headers().firstValue("Content-Security-Policy").orElseThrow().contains("default-src 'self'"));
HttpResponse<String> script = get("/app.js", null);
assertEquals(200, script.statusCode());
assertTrue(script.body().contains("offset=${offset}&limit=${PAGE_SIZE}"));
assertTrue(script.body().contains("async function loadAllNodes()"));
assertTrue(script.body().contains("let nodeLoadInFlight = null;"));
assertTrue(script.body().contains("async function loadNodesOnce()"));
assertTrue(script.body().contains("`${node.displayName} (${node.nodeId})`"),
"Skipped deployment targets must retain their unique node ID in status output.");
assertTrue(script.body().contains("nodeLoadQueued = true;"));
assertTrue(script.body().contains("let nodeLoadQueuedPromise = null;"));
assertTrue(script.body().contains("return nodeLoadQueuedPromise;"),
"A queued registry refresh must remain awaitable by its caller.");
assertTrue(script.body().contains("loadNodes().then(resolveQueued, rejectQueued);"),
"A queued registry refresh must settle only after the follow-up pass completes.");
assertTrue(script.body().contains("let operationHistoryLoadInFlight = null;"));
assertTrue(script.body().contains("let operationHistoryLoadQueued = false;"));
assertTrue(script.body().contains("async function loadOperationHistoryOnce()"));
assertTrue(script.body().contains("while (operationHistoryLoadQueued && authenticated)"));
assertTrue(script.body().contains(": tab === 'servers' ? nodeLoadInFlight != null"));
assertTrue(script.body().contains("rootStyleRule?.['style'].setProperty('--topbar-height', `${height}px`)"));
assertTrue(script.body().contains("function scrollToAnchor(target)"));
assertTrue(script.body().contains("syncTopbarOffset();\n target.scrollIntoView({behavior: 'smooth', block: 'start'});"));
assertTrue(script.body().contains("window.requestAnimationFrame(() => scrollToAnchor(document.getElementById(scrollTarget)))"));
assertTrue(script.body().contains("Math.max(topbarBounds.bottom, searchBounds.bottom)"));
assertTrue(script.body().contains("globalSearch.hidden = false;\n syncTopbarOffset();"));
assertTrue(script.body().contains("MAX_REGISTRY_SCAN_ATTEMPTS"));
assertTrue(script.body().contains("&revision=${revision}"));
assertTrue(script.body().contains("enrollmentIds.has(backend.backendId)"));
assertTrue(script.body().contains("Control enrollment unavailable"));
assertTrue(script.body().contains("Comments preserved for every target"));
assertTrue(script.body().contains("Backend topology is truncated"));
assertTrue(script.body().contains("function resetServerConfigurationForms(status, preserveDirtyDrafts = false)"));
assertTrue(script.body().contains("Network data is unavailable. Refresh and load current values before continuing."));
assertTrue(script.body().contains("backendTopologyTruncated = false;"));
assertTrue(script.body().contains("nextPage.addEventListener"));
assertTrue(script.body().contains("result.configuration?.content != null"));
assertTrue(script.body().contains("authenticationGeneration"));
assertTrue(script.body().contains("if (loginInFlight) return"));
assertTrue(script.body().contains("logoutInFlight && path !== '/api/v1/auth/logout'"));
assertTrue(script.body().contains("!authenticated || logoutInFlight || !file"));
assertTrue(script.body().contains("const deploymentRun = ++deploymentRunGeneration;"));
assertTrue(script.body().contains("if (deploymentRun === deploymentRunGeneration) {\n"
+ " deploymentInFlight = false;"),
"A failed logout must not leave a superseded deployment permanently in flight.");
assertTrue(script.body().contains("deploymentRunGeneration++;\n deploymentInFlight = false;"),
"Successful logout must invalidate the prior deployment completion guard.");
assertTrue(script.body().contains("if (error.code !== 'NODE_UNAVAILABLE') throw error;"));
assertTrue(script.body().contains("const unavailable = new Set((error.details || []).filter(nodeId => remaining.includes(nodeId)));"),
"Deployment retries must use the server's exact unavailable-node details when available.");
assertTrue(script.body().contains("remaining = remaining.filter(nodeId => !unavailable.has(nodeId));"),
"A temporarily unavailable node must not discard other eligible nodes in its batch.");
assertTrue(script.body().contains("attempt < MAX_OPERATION_TARGETS"),
"Deployment eligibility retries must remain bounded by the target limit.");
assertTrue(script.body().contains("Unavailable nodes skipped:"));
assertTrue(script.body().contains("No deployment batches were submitted."));
assertTrue(script.body().contains("backendItemsTruncated"));
assertTrue(script.body().contains("topologyComplete: !truncatedNodeIds.has(proxyId)"));
assertTrue(script.body().contains("proxyReady: network.proxyReady"));
assertTrue(script.body().contains("option.value = backend.backendId"));
assertTrue(script.body().contains("return allNodeItems.filter(node => isProxy(node)"));
assertTrue(script.body().contains("MAX_OPERATION_TARGETS = 100"));
assertTrue(script.body().contains("proxyMethodNetworkSignature(refreshedNetwork)"));
assertTrue(script.body().contains("proxyMethodCurrentSessionId !== (network.proxy?.sessionId || '')"));
assertTrue(script.body().contains("sessionId !== proxyMethodNetwork(readCapability).proxy?.sessionId"));
assertTrue(script.body().contains("function proxyBackendCommonCapability()"));
assertTrue(script.body().contains("selectedBackends.every(nodeId => nodeCapabilities.get(nodeId)?.includes(required))"));
assertTrue(script.body().contains("!proxyBackendCapabilityMismatch && primaryCapabilities.includes(quickCapability)"));
assertTrue(script.body().contains("refreshedNetwork.proxy?.sessionId !== network.proxy.sessionId"));
assertTrue(script.body().contains("if (approvedQuickPreview?.workflow === 'sync-vote-sites') approvedQuickPreview = null;"));
assertTrue(script.body().contains("if (quickPreset.value !== 'sync-vote-sites') return;"));
assertTrue(script.body().contains("await loadFileConfiguration(true);"),
"Successful file applies must refresh confirmed current state.");
assertTrue(script.body().contains("await loadQuickSetupValues(true);"),
"Successful guided applies must refresh confirmed current state.");
assertTrue(script.body().contains("configurationContent.setAttribute('aria-busy', 'true')"));
assertTrue(script.body().contains("readFileConfiguration.hidden = false;"));
assertTrue(script.body().contains("readQuickSetup.hidden = false;"));
assertTrue(script.body().contains("if (!quickSetupValuesLoaded()) {\n text(quickOperationStatus, 'The server or setup changed while reading."));
assertTrue(script.body().contains("voteParty.enabled = String(quickPartyEnabled.checked)"));
assertTrue(script.body().contains("quickPartyEnabled.checked = enabledAvailable && options.enabled === 'true'"));
assertTrue(script.body().contains("if (Object.hasOwn(profile, 'partyEnabled')) quickPartyEnabled.checked = Boolean(profile.partyEnabled);"),
"Legacy v1 profiles must preserve the live Vote Party enabled state when they omit that field.");
assertTrue(script.body().contains("if (quickSetupCapability() === 'config.quick-setup.v2'\n"
+ " && !quickPartyEnabled.disabled && !quickPartyEnabled.indeterminate) {\n"
+ " values.partyEnabled = quickPartyEnabled.checked;"),
"Profiles must omit an unavailable Vote Party Enabled value instead of fabricating false.");
assertTrue(script.body().contains("config.proxy-method.v2"));
assertTrue(script.body().contains("? votePartyCommonCapability() || 'config.quick-setup.unavailable' : 'config.quick-setup.v1';"),
"Vote Party must use v2 only when every selected backend supports it.");
assertTrue(script.body().contains("selectedVotePartyBackends().length > 0 && !votePartyCommonCapability()"));
assertTrue(script.body().contains("The selected backends do not share a Vote Party configuration capability."),
"Mixed v1-only/v2-only targets must be rejected explicitly instead of silently omitting a backend.");
assertTrue(script.body().contains("if (quickSetupCapability() === 'config.quick-setup.v2') voteParty.enabled"),
"Vote Party Enabled must never be sent under the incompatible v1 quick-setup contract.");
assertTrue(script.body().contains("quickPartyEnabled.indeterminate = !enabledAvailable;\n"
+ " quickPartyEnabled.disabled = !enabledAvailable;"),
"A legacy read must represent Enabled as unavailable instead of leaking another server's value.");
assertTrue(script.body().contains("function quickSetupTargets()"));
assertTrue(script.body().contains("nodeIds = quickSetupTargets()"));
assertTrue(script.body().contains("currentNodeIds = sync ? selectedVoteSitesTargets() : quickSetupTargets()"));
assertTrue(script.body().contains("autoLoadPending.add(tab);"));
assertTrue(script.body().contains("configurationOperationsInFlight === 0 && autoLoadPending.has('quick-setup')"));
assertTrue(script.body().contains("function quickReadConfigurationOptions()"));
assertTrue(script.body().contains("options: quickReadConfigurationOptions()"));
assertTrue(script.body().contains("loadedQuickSetup.selector === JSON.stringify(quickReadConfigurationOptions())"));
assertTrue(script.body().contains("reloadVotePartyWhenTargetCapabilityChanges(previousQuickCapability)"),
"Changing selected backend capability must reload capability-dependent Vote Party state.");
assertTrue(script.body().contains("quickSetupPreserveReadGeneration = inputGeneration;\n"
+ " text(quickOperationStatus,\n"
+ " 'Selected backend capabilities changed. Preserving unsaved Vote Party edits"),
"Capability changes must preserve unsaved common Vote Party fields during the confirmed read.");
assertTrue(script.body().contains("if (scheduleReload && tabFromHash() === 'quick-setup') void autoLoadTab('quick-setup');"),
"Vote Party capability transitions must use the quick-setup single-flight autoloader.");
assertFalse(script.body().contains("if (scheduleReload && tabFromHash() === 'quick-setup') void loadQuickSetupValues(true);"),
"Vote Party capability transitions must not start an overlapping direct READ.");
assertTrue(script.body().contains("const registry = await loadAllNodes();\n"
+ " const previousQuickCapability = quickSetupCapability();\n"
+ " const previousNodeIndex = nodeIndex;"));
assertTrue(script.body().contains("selectedNodes = filteredSelection;\n"
+ " // A registry refresh can change the effective Vote Party contract without a\n"
+ " // user selection event. Clear the old v2/v1 form before the normal tab\n"
+ " // auto-load runs so a delayed or failed READ cannot expose stale values.\n"
+ " reloadVotePartyWhenTargetCapabilityChanges(previousQuickCapability, false);"),
"Refresh-driven v2/v1 capability changes must clear stale Vote Party state before rereading.");
assertTrue(script.body().contains("const autoLoadGeneration = inputGeneration;"));
assertTrue(script.body().contains("if (inputGeneration !== autoLoadGeneration) {\n autoLoadPending.add(tab);\n return;\n }"),
"A stale dedicated read must fence the remainder of the automatic quick-setup sequence.");
assertTrue(script.body().contains("quickMethod.addEventListener('input', () => {\n if (quickPreset.value === 'proxy-backend' && quickPresetReadable()) {"));
assertTrue(script.body().contains("quickSetupDirty = true;\n if (quickSetupDirty) quickSetupPreserveReadGeneration = inputGeneration;\n void autoLoadTab('quick-setup');"),
"Changing a proxy-backend method must schedule a capability-correct reread.");
assertTrue(script.body().contains("const selectedProxyMethod = preserveDirty && preset === 'proxy-backend' ? quickMethod.value : null;"));
assertTrue(script.body().contains("if (selectedProxyMethod != null) quickMethod.value = selectedProxyMethod;"),
"The capability read must not overwrite the proxy method the operator selected for preview.");
assertTrue(script.body().contains("const editedProxyServer = preserveDirty && preset === 'proxy-backend' ? quickName.value : null;"));
assertTrue(script.body().contains("if (editedProxyServer != null) quickName.value = editedProxyServer;"),
"A capability read must preserve an edited proxy destination.");
assertTrue(script.body().contains("const editedVoteParty = preserveDirty && preset === 'vote-party'"));
assertTrue(script.body().contains("if (editedVoteParty.enabled != null && !quickPartyEnabled.disabled)"));
assertTrue(script.body().contains("quickPartyCommand.value = editedVoteParty.command;"),
"A capability refresh must restore every unsaved common Vote Party value.");
assertTrue(script.body().contains("for (const capability of ['config.proxy-method.v2', 'config.proxy-method.v1'])"),
"A fully v2-capable network must retain HTTP current-state visibility instead of downgrading to v1.");
assertTrue(script.body().contains("network.proxyReady && network.topologyComplete && network.unavailable.length === 0"),
"Proxy-method reads must negotiate one capability shared by the full reported network.");
assertTrue(script.body().contains("previewAutoSites.disabled = !quickReady || autoSitesState.textContent === 'Not loaded';"));
assertTrue(script.body().contains("previewVoteLogging.disabled = !quickReady || voteLoggingState.textContent === 'Not loaded';"));
assertTrue(script.body().contains("if (automatic && requestGeneration !== inputGeneration) void autoLoadTab('quick-setup');"),
"Discarded automatic dedicated reads must request a fresh read rather than leave defaults previewable.");
assertTrue(script.body().contains("if (observedSuccessfulApply) {\n invalidateConfigurationReads();\n invalidateGuidedSetupReads();"),
"Observed external applies must invalidate the dedicated setup cards as well as the main editor.");
assertTrue(script.body().contains("if (applied) {\n invalidateConfigurationReads();\n invalidateGuidedSetupReads();"),
"Locally completed applies must invalidate guided reads as well as the main editor.");
assertTrue(script.body().contains("if (tabFromHash() === 'quick-setup') window.setTimeout(() => void autoLoadTab('quick-setup'), 0);"),
"Invalidated dedicated settings must automatically reload while Quick Setup is visible.");
assertTrue(script.body().contains("nodeCapabilities.get(node)?.includes(quickSetupCapability())"),
"Quick approvals must remain valid only for their selected capability version.");
assertTrue(script.body().contains("'config.quick-setup.v1', 'config.quick-setup.v2', 'config.proxy-method.v2'"),
"Secondary versioned backends must remain selectable for HTTP and Vote Party setup.");
assertTrue(script.body().contains("'config.quick-setup.v2', 'config.proxy-method.v2', 'data.inspect.v1'"),
"HTTP capability transitions must invalidate cached guided configuration reads.");
assertTrue(script.body().contains("return {enabled: 'true'};"),
"The v2 read selector must be a constant capability hint, not editable Vote Party state.");
assertTrue(script.body().contains("proxyMethodCurrentReadCapability !== readCapability"),
"The active proxy method must be invalidated when its v1/v2 read capability changes.");
assertTrue(script.body().contains("proxyMethodCurrentReadCapability = readCapability;"),
"Successful proxy reads must remember the exact capability used.");
assertTrue(script.body().contains("const enabledAvailable = quickSetupCapability() === 'config.quick-setup.v2'"),
"Vote Party Enabled availability must come from v2 negotiation, not a legacy response field.");
assertTrue(script.body().contains("if (selectedCapabilitiesChanged) {\n invalidateGuidedSetupReads();"),
"Capability transitions must invalidate cached guided reads.");
assertTrue(script.body().contains("quickPresetReadable() && (!quickSetupDirty || quickSetupPreserveReadGeneration === inputGeneration)"));
assertTrue(script.body().contains("!dedicatedSetupDirty.has('auto-create-vote-sites') && autoSitesState.textContent === 'Not loaded'"));
assertTrue(script.body().contains("Configuration changed elsewhere; your unsaved guided edits were preserved."),
"External configuration changes must not overwrite unsaved guided edits.");
assertTrue(script.body().contains("dedicatedSetupDirty.add(preset);"));
assertTrue(script.body().contains("if (quickPreset.value !== 'vote-site') quickSetupDirty = true;"),
"The shared name field is a selector for vote sites but a dirty editable value for other presets.");
assertTrue(script.body().contains("function exposeDirtyVoteSiteReload()"));
assertTrue(script.body().contains("quickSetupDirty = true;\n exposeDirtyVoteSiteReload();"),
"Becoming dirty during the selector debounce must also expose reload.");
assertTrue(script.body().contains("The vote-site key changed; load its current values to discard your unsaved edits."),
"A dirty vote-site selector transition must expose an explicit discard and reload action.");
assertTrue(script.body().contains("const profileName = profilePicker.value;"));
assertTrue(script.body().contains("profilePicker.value !== profileName || !currentProfile || JSON.stringify(currentProfile) !== profileSignature"),
"Profile application must verify its selection after waiting for live values.");
assertTrue(script.body().contains("selector: JSON.stringify(quickReadConfigurationOptions())"),
"The retained selector must reflect the method returned by the live backend read.");
assertTrue(script.body().contains("loadedQuickSetup = {...loadedQuickSetup, selector: JSON.stringify(quickReadConfigurationOptions())};"),
"Applying a proxy profile must rebind the confirmed read cache to its restored method.");
assertTrue(script.body().contains("if (tabFromHash() === 'configurations') window.setTimeout(() => void autoLoadTab('configurations'), 0);"),
"A clean active YAML editor must automatically reload after apply invalidates its cache.");
assertTrue(web.body().contains("Add a simple vote reward"));
assertTrue(web.body().contains("First-run setup"));
assertTrue(web.body().contains("Node enrollment"));
assertTrue(script.body().contains("setupForm.addEventListener"));
assertTrue(script.body().contains("loadEnrollments"));
assertTrue(script.body().contains("enrollmentMutationInFlight"));
assertTrue(script.body().contains("enrollmentRefreshRequested"));
assertTrue(script.body().contains("let enrollmentRefreshPromise = null;"),
"Enrollment callers must be able to await a refresh queued behind an in-flight request.");
assertTrue(script.body().contains("if (!enrollmentRefreshPromise) {"),
"Concurrent enrollment refresh callers must share one bounded waiter promise.");
assertTrue(script.body().contains("return enrollmentRefreshPromise;"),
"A queued enrollment refresh must not let dashboard inspection proceed on stale enrollment state.");
assertFalse(script.body().contains("enrollmentRefreshWaiters"),
"Enrollment refresh waiters must not grow without a bound.");
assertTrue(script.body().contains("const reportedBackends = new Map();"),
"Node-level topology warnings must be aggregated before rendering attention items.");
assertTrue(script.body().contains("is unavailable to ${proxy.displayName}"),
"Availability warnings must remain distinct for every reporting proxy.");
assertTrue(script.body().contains(
"if (nodeId && nodeId === selectedServerId) {\n serverPicker.value = selectedServerId;\n return;\n }"),
"Selecting the current server again must not reset unsaved YAML or routing drafts.");
int primarySelector = script.body().indexOf("function selectPrimaryServer(nodeId)");
int sameServerGuard = script.body().indexOf(
"if (nodeId && nodeId === selectedServerId)", primarySelector);
assertTrue(primarySelector >= 0 && sameServerGuard > primarySelector
&& sameServerGuard < script.body().indexOf(
"confirmDiscardUnsavedConfiguration('switching servers')", sameServerGuard)
&& sameServerGuard < script.body().indexOf("resetServerContextValues(", sameServerGuard),
"The same-server guard must run before any draft-discard confirmation or context reset.");
assertTrue(script.body().contains(
"const registeredBukkitBackend = registered?.platform === 'BUKKIT';"),
"A proxy or non-Bukkit registry node must not satisfy a proxy backend report.");
assertTrue(script.body().contains(
"if (enrollmentsLoaded && registeredBukkitBackend && !enrollmentIds.has(backend.backendId))"),
"Enrollment health must only be evaluated for a registered Bukkit backend.");
assertTrue(script.body().contains("await loadEnrollments()"));
assertTrue(script.body().contains("enrollmentSubmit.disabled = true"));
assertTrue(script.body().contains("filteredSelection.size !== selectedNodes.size"));
assertTrue(script.body().contains("previewGeneration === inputGeneration"));
assertTrue(script.body().contains("let configurationContentPresent = false;"));
assertTrue(script.body().contains("const MAX_TRACE_EVENTS_PER_NODE = 100;"));
assertTrue(script.body().contains("const MAX_PLAYER_LAST_VOTES = 100;"));
assertTrue(script.body().contains(
"envelope.result?.truncated === true || received.length > MAX_TRACE_EVENTS_PER_NODE"));
assertTrue(script.body().contains(
"if (!Array.isArray(envelope.result?.events)) {\n unavailable.push(`${source}: malformed vote-trace events`);"));
assertTrue(script.body().contains(
"typeof envelope.result.voteId !== 'string' || envelope.result.voteId !== voteId"));
assertTrue(script.body().contains("event.voteId !== voteId"));
assertTrue(script.body().contains("const voteId = enteredVoteId.toLowerCase();"));
assertTrue(script.body().contains("&& enteredVoteId === voteTraceId.value.trim()"));
assertTrue(script.body().contains("columns.length < value.columns.length"));
assertTrue(script.body().contains("const traceAbortController = new AbortController();"));
assertTrue(script.body().contains("await Promise.allSettled(candidates.map(async node => {"));
assertTrue(script.body().contains("const response = await authorized(path, {...requestOptions, signal: options.signal});\n ensureActive();"));
assertTrue(script.body().contains("current.acceptedCapabilities.includes('data.inspect.v1')"));
assertTrue(script.body().contains(
"signal: traceAbortController.signal, contextCurrent, manageBusy: false"));
assertTrue(script.body().contains("window.clearTimeout(deadlineTimer);"));
assertFalse(script.body().contains("for (const node of candidates)"));
assertTrue(script.body().contains("let configurationDraftNodeId = '';"));
assertTrue(script.body().contains("let configurationDraftSessionId = '';"));
assertTrue(script.body().contains("function fileDraftMatchesCurrentContext()"));
assertTrue(script.body().contains("if (configurationDirty) {\n text(fileOperationStatus, fileDraftStatus("),
"Routine refresh must retain dirty drafts when the replacement has a different node role.");
assertTrue(script.body().contains("const fileDraftReady = fileReady && fileDraftMatchesCurrentContext();"));
assertTrue(script.body().contains(
"previewFileConfiguration.disabled = !fileDraftReady || !configurationContentPresent;"));
assertTrue(script.body().contains(
"applyFileConfiguration.disabled = !fileDraftReady || !approvedFilePreview;"));
assertTrue(script.body().contains(
"configurationContent.value = document.content;\n configurationContentPresent = true;"));
assertTrue(script.body().contains(
"resetServerContextValues('A selected server reconnected. Load current values before continuing.', true);"));
assertTrue(script.body().contains(
"configurationContent.addEventListener('input', () => {\n if (!configurationDirty) {\n configurationDraftNodeId = selectedServerId;"));
assertTrue(script.body().contains("quickPresetNeedsRead() && !quickSetupValuesLoaded()"));
assertFalse(script.body().contains("quickPresetReadable() && !loadedQuickSetup"),
"Quick-setup autoload must re-read when the loaded vote-site selector changes.");
assertTrue(script.body().contains("quickPresetReadable() && (!quickSetupDirty || quickSetupPreserveReadGeneration === inputGeneration)"),
"Quick-setup autoload must validate the loaded selector before deciding it is current.");
assertTrue(script.body().contains("loadedQuickSetup.sessionId === nodeIndex.get(selectedServerId)?.sessionId"));
assertTrue(script.body().contains("previousNodeIndex.get(selectedServerId)?.sessionId !== nodeIndex.get(selectedServerId)?.sessionId"));
assertTrue(script.body().contains("sessionId !== nodeIndex.get(nodeId)?.sessionId"));
assertTrue(script.body().contains("retained.sessionId === readSessionId"));
assertTrue(script.body().contains("operation.results?.[proxyId]?.sessionId !== proxySessionId"));
assertTrue(script.body().contains("confirmDiscardUnsavedConfiguration('switching servers')"));
assertTrue(script.body().contains("enteredVoteId === voteTraceId.value.trim()"));
assertTrue(script.body().contains("Pending offline votes"));
assertTrue(script.body().contains("Additional VoteSite history was omitted"));
assertTrue(script.body().contains("VoteSite history is unavailable because the node returned malformed history data."));
assertTrue(script.body().contains("function validPlayerLastVote(lastVote)"));
assertTrue(script.body().contains("exactObjectKeys(lastVote, ['displayName', 'serviceSite', 'siteKey', 'time'])"));
assertTrue(script.body().contains("const limits = {siteKey: 64, displayName: 100, serviceSite: 64};"));
assertTrue(script.body().contains("receivedLastVotes.some(lastVote => !validPlayerLastVote(lastVote))"));
assertTrue(script.body().contains("const lastVotes = malformedLastVotes ? [] : receivedLastVotes.slice(0, MAX_PLAYER_LAST_VOTES);"));
assertTrue(script.body().contains("function validPlayerColumn(column)"));
assertTrue(script.body().contains("suffix.length > 0 && suffix.length <= 64"));
assertTrue(script.body().contains("const legacyStorageMetadata = value.storageRowAvailable === undefined"));
assertTrue(script.body().contains("const columnsOmittedForUnavailableStorage = value.storageRowAvailable === false && value.columns === undefined;"));
assertTrue(script.body().contains("if (legacyStorageMetadata || columnsOmittedForUnavailableStorage) return;"));
assertTrue(script.body().contains("fields outside the allow-listed column schema"));
assertTrue(script.body().contains("Saved; proxy restart required"));
assertTrue(script.body().contains("configuration saved; proxy restart required"));
assertTrue(script.body().contains("Restart the proxy before treating the saved proxy configuration as active."));
assertTrue(script.body().contains("function validVoteTraceEvent(event, voteId)"));
assertTrue(script.body().contains("received.some(event => !validVoteTraceEvent(event, voteId))"));
assertTrue(script.body().contains("VOTE_LOG_STATUSES.has(event.status)"));
assertTrue(script.body().contains("Node result limit reached; this trace is incomplete"));
assertFalse(script.body().contains("This is the complete retained trace"));
assertTrue(script.body().contains("const traceReady = authenticated && connectedInspectionNodes().length > 0"));
assertTrue(script.body().contains("traceVote.disabled = !traceReady;"));
assertTrue(script.body().contains("const retainedRoutingDraft = preserveDirtyDrafts && routingDirty;"));
assertTrue(script.body().contains("routingDraftNodeId === selectedServerId"));
assertTrue(script.body().contains("readConfiguration.disabled = !routingReadReady;"));
assertTrue(script.body().contains("previewConfiguration.disabled = !routingDraftReady;"));
assertTrue(script.body().contains("applyConfiguration.disabled = !routingDraftReady || !approvedPreview;"));
assertTrue(script.body().contains("PREVIEW ONLY — nothing has been saved yet."));
assertTrue(script.body().contains("presentPreviewReady(operationStatus, applyConfiguration, operation);"));
assertTrue(script.body().contains("presentPreviewReady(fileOperationStatus, applyFileConfiguration, operation);"));
assertTrue(script.body().contains("presentPreviewReady(quickOperationStatus, applyQuickSetup, operation);"));
assertTrue(script.body().contains("presentPreviewReady(elements.status, elements.apply, operation);"));
assertTrue(script.body().contains("presentPreviewReady(rewardSimulationResult, applyReward, operation);"));
assertTrue(script.body().contains("Your unsaved proxy-routing draft is retained"));
assertTrue(script.body().contains("function invalidateConfigurationReads() {\n fileReadCache.clear();\n"
+ " lastFileReadOperation = null;\n clearApprovals();\n loadedQuickSetup = null;\n"
+ " if (!configurationDirty) {\n"
+ " configurationContent.value = '';\n configurationContentPresent = false;\n"
+ " text(fileOperationStatus, 'Configuration changed; read the current file before previewing changes.');\n"
+ " if (tabFromHash() === 'configurations') window.setTimeout(() => void autoLoadTab('configurations'), 0);\n"
+ " }\n lastOverview = null;\n lastDiagnostics = null;\n"
+ " dashboardConfigurationGeneration++;\n invalidateDashboardInspection();"),
"Every successful apply must invalidate file and dashboard reads even after the view context changes.");
assertTrue(script.body().contains("function clearApprovals() {\n approvedPreview = null;\n"
+ " approvedFilePreview = null;\n approvedQuickPreview = null;\n"
+ " dedicatedSetupApprovals.clear();\n inputGeneration++;\n updateConfigurationButtons();"),
"External applies must invalidate every approval and fence delayed configuration responses.");
assertTrue(script.body().contains("const serverConfigurationGeneration = finiteCount(body.configurationGeneration);"));
assertTrue(script.body().contains("serverConfigurationGeneration > observedServerConfigurationGeneration"));
assertTrue(script.body().contains("Math.max(observedServerConfigurationGeneration, serverConfigurationGeneration)"),
"A delayed older response must not move the observed server generation backwards.");
assertTrue(script.body().contains("if (observedSuccessfulApply) {\n invalidateConfigurationReads();"),
"Activity refreshes must invalidate cached health after observing an external successful apply.");
assertTrue(script.body().contains("if (applied) {\n invalidateConfigurationReads();"),
"Locally completed applies must use the same cache invalidation path.");
assertTrue(script.body().contains("const submittedContent = configurationContent.value;"));
assertTrue(script.body().contains("const submittedContextStillCurrent = approval.fileName === configurationFile.value\n"
+ " && configurationContent.value === submittedContent\n && fileDraftMatchesCurrentContext()"));
assertTrue(script.body().contains("approval.sessions.get(nodeId) === nodeIndex.get(nodeId)?.sessionId"),
"File apply completion must compare input generation, target scope, file, and node sessions.");
assertTrue(script.body().contains("The apply completed, but newer unsaved file edits remain. Preview again before applying them."),
"A file apply must not label edits made during polling as already saved.");
assertTrue(script.body().contains("const previewGeneration = inputGeneration;\n try {\n const nodeIds = backendQuickTargets();"));
assertTrue(script.body().contains("if (previewGeneration !== inputGeneration\n"
+ " || signature !== JSON.stringify"),
"Dedicated previews completed after another apply must not restore stale approvals.");
assertTrue(script.body().contains("dedicatedSetupApprovals.delete(preset);\n dedicatedSetupDirty.add(preset);\n"
+ " inputGeneration++;\n updateExtendedButtons();"),
"Dedicated setup edits must fence delayed reads before they can overwrite newer input.");
assertTrue(script.body().contains("const submittedOptions = JSON.stringify(dedicatedSetupOptions(preset));"));
assertTrue(script.body().contains("const inputsCurrent = submittedOptions === JSON.stringify(dedicatedSetupOptions(preset))"));
assertTrue(script.body().contains("The apply completed, but newer setup edits remain. Preview again before applying them."),
"Dedicated apply results must not label newer form values as saved.");
assertTrue(script.body().contains("The apply completed, but newer guided setup edits remain. Preview again before applying them."));
assertTrue(script.body().contains("const submittedQuickSetup = JSON.stringify"));
assertTrue(script.body().contains("The apply completed, but newer reward edits remain. Preview again before applying them."));
assertTrue(script.body().contains("const submittedReward = JSON.stringify"));
assertTrue(script.body().contains("dedicatedSetupApprovals.delete('reward-builder');\n inputGeneration++;"),
"Reward edits must fence delayed preview and apply results.");
assertTrue(script.body().contains("previewReward.addEventListener('click', async () => {\n"
+ " dedicatedSetupApprovals.delete('reward-builder');\n"
+ " const previewGeneration = inputGeneration;"),
"Reward previews must also be fenced when another apply invalidates their base revision.");
assertTrue(script.body().contains("Drift results were discarded; run the comparison again."),
"A drift read completed for stale context must show an explicit discarded-result status.");
assertTrue(script.body().contains("text(operationStatus, routingDraftStatus('The selected nodes changed during refresh."));
assertTrue(script.body().contains(
"The apply completed, but newer unsaved proxy-routing edits remain. Preview again before applying them."));
assertTrue(script.body().contains("Your unsaved ${configurationFile.value} draft is retained"));
assertTrue(script.body().contains("Discard unsaved routing changes and load current values?"));
assertTrue(script.body().contains("Discard the unsaved ${configurationFile.value} draft and read/reload the current file for this server?"));
assertTrue(script.body().contains("window.addEventListener('beforeunload'"));
assertTrue(script.body().contains("loadedQuickSetup = {nodeId, sessionId, preset,"));
assertTrue(script.body().contains("configurationOperationsInFlight"));
assertTrue(script.body().contains("if (selectedCapabilitiesChanged) {\n invalidateGuidedSetupReads();\n approvedPreview = null;"));
assertTrue(script.body().contains("approvedPreview.nodeIds.every"));
assertTrue(script.body().contains("selectedCapabilitiesChanged"));
assertTrue(script.body().contains("proxyFile ? !isProxy(restoreNode) : !isBackend(restoreNode)"));
assertTrue(script.body().contains("discardAuthenticationState"));
assertTrue(script.body().contains("text(operationStatus, '');"));
assertTrue(script.body().contains("text(fileOperationStatus, '');"));
assertTrue(script.body().contains("text(quickOperationStatus, '');"));
assertTrue(script.body().contains("configurationForm.reset();"));
assertTrue(script.body().contains("quickSetupForm.reset();"));
assertTrue(script.body().contains("rewardSimulationForm.reset();"));
assertTrue(script.body().contains("playerLookupForm.reset();"));
assertTrue(script.body().contains("voteLogForm.reset();"));
assertTrue(script.body().contains("voteTraceForm.reset();"));
assertTrue(script.body().contains("siteResolutionForm.reset();"));
assertTrue(script.body().contains("snapshotForm.reset();"));
assertTrue(script.body().contains("voteLogFilter.disabled = true;"));
assertTrue(script.body().contains("body.voteLoggingRestartSessions"));
assertTrue(script.body().contains("retainedOperations.slice(0, MAX_OPERATION_HISTORY)"));
assertTrue(script.body().contains("quickCommandSuggestions.replaceChildren();"));
assertTrue(script.body().contains("Sign out could not be confirmed"));
assertTrue(script.body().contains("result.success && result.configuration"));
assertTrue(script.body().contains("Not enrolled in Control"));
assertTrue(script.body().contains("Presence not available"));
assertTrue(script.body().contains("No connected proxy reports this backend ID"));
assertTrue(script.body().contains("'config.files.v1': 'Full configuration'"));
assertTrue(script.body().contains("'config.file-comments.v1': 'Comments preserved'"));
assertTrue(script.body().contains("'config.vote-sites-sync.v1': 'VoteSites sync'"));
assertTrue(script.body().contains("'config.transport-test.v1': 'Communication test'"));
assertTrue(script.body().contains("'config.proxy-method.v1': 'Proxy method'"));
assertTrue(script.body().contains("preset: 'sync-vote-sites'"));
assertTrue(script.body().contains("return allNodeItems.filter(node => isBackend(node)"));
assertTrue(script.body().contains("A sync target became unavailable"));
assertTrue(script.body().contains("MAX_SYNC_TARGETS = 100"));
assertTrue(script.body().contains("The sync source became unavailable"));
assertTrue(script.body().contains("sourceContent: source"));
assertTrue(script.body().contains("preset: 'communication-test'"));
assertTrue(script.body().contains("runTransportTest.addEventListener"));
assertTrue(script.body().contains("preset: 'proxy-method'"));
assertTrue(script.body().contains("proxyMethodButtons.forEach"));
assertTrue(script.body().contains("handleEditorKeydown"));
assertTrue(script.body().contains("receivedLastVotes.length > MAX_PLAYER_LAST_VOTES"));
assertTrue(script.body().contains(".slice(0, MAX_PLAYER_LAST_VOTES)"));
assertFalse(script.body().contains("if (!automatic) text(fileOperationStatus, error.message);"));
assertTrue(script.body().contains("const cell = document.createElement('td');"));
assertTrue(script.body().contains("const submittedProposal = JSON.stringify({proposal: proposal(), nodeIds: approval.nodeIds});"));
assertTrue(script.body().contains("const currentProposal = JSON.stringify({proposal: proposal(), nodeIds: targets('config.proxy-routing.v1')});"));
assertFalse(script.body().contains("'No backends reported.'"));
assertFalse(script.body().contains("'No Bukkit plugin inventory reported.'"));
HttpResponse<String> stylesheet = get("/app.css", null);
assertEquals(200, stylesheet.statusCode());
assertTrue(stylesheet.body().contains(".sidebar"));
assertTrue(stylesheet.body().contains("--topbar-height: 76px"));
assertTrue(stylesheet.body().contains("[id] { scroll-margin-top: calc(var(--topbar-height) + 20px); }"),
"Anchored shortcuts must clear the dynamically measured sticky header on desktop and mobile.");
assertTrue(stylesheet.body().contains("top: calc(var(--topbar-height) + 24px)"));
assertTrue(stylesheet.body().contains("max-height: calc(100vh - var(--topbar-height) - 44px)"));
assertTrue(stylesheet.body().contains("@media (max-width: 1360px) and (min-width: 921px)"));
assertTrue(stylesheet.body().contains("@media (max-width: 480px)"),
"The compact header must hide the brand before the 430px overflow range.");
assertTrue(stylesheet.body().contains(".topbar-actions { flex: 1 1 520px; min-width: 0; flex-wrap: wrap; }"));
assertFalse(stylesheet.body().contains("attr(data-topbar-height"));
assertTrue(stylesheet.body().contains("body::before { position: fixed; z-index: 25; top: var(--topbar-height)"));
assertTrue(stylesheet.body().contains(".sidebar { position: fixed; z-index: 30; top: var(--topbar-height)"));
assertTrue(web.body().contains("id=\"primary-navigation\""));
assertTrue(web.body().contains("id=\"attention-feed\""));
assertTrue(web.body().contains("id=\"global-search-input\""));
assertTrue(web.body().contains("Logged Votes · 30d"));
assertTrue(script.body().contains("async function refreshDashboard()"));
assertTrue(script.body().contains(
"dashboardLoading = true;\n inspectionInFlight = true;\n refreshDashboardButton.disabled = true;\n updateExtendedButtons();\n suppressNodeAutoLoad++"),
"Dashboard refresh must reserve the shared inspection lane before any awaited registry or metadata prefetch.");
assertTrue(script.body().contains(
"refreshDashboardButton.disabled = !authenticated || inspectionInFlight || dashboardLoading;"),
"Dashboard refresh must remain available to rediscover a reconnected inspection-capable node.");
assertTrue(script.body().contains(
"const unavailable = tab === 'overview' ? dashboardLoading || inspectionInFlight"),
"The overview header refresh must not be gated by stale cached node capabilities.");
assertTrue(script.body().contains("function dashboardIssues()"));
assertTrue(script.body().contains("operationHistoryStatus = 'failed';"));
assertTrue(script.body().contains("const historyGeneration = authenticationGeneration;"));
assertEquals(2, script.body().split(java.util.regex.Pattern.quote(
"if (!authenticated || historyGeneration !== authenticationGeneration) return;"), -1).length - 1,
"Delayed operation-history success and failure responses must not mutate a replaced session.");
assertTrue(script.body().contains(
"operationHistoryItems = [];\n deploymentHistoryItems = [];\n voteLoggingRestartPending = new Map();"),
"A failed history refresh must not leave stale operations or restart warnings on the dashboard.");
assertTrue(script.body().contains(
"text(operationHistory, error.message || 'Operation history could not be loaded.');\n updateSetupChecklist();"),
"Clearing restart state after a failed history refresh must update the setup checklist.");
assertTrue(script.body().contains("if (operationHistoryStatus === 'failed') issues.push(issue('warning'"),
"Unavailable operation history must downgrade dashboard health.");
assertTrue(script.body().contains("let enrollmentStatus = 'not-loaded';"));
assertTrue(script.body().contains("enrollmentStatus = 'failed';"));
assertTrue(script.body().contains("if (enrollmentStatus === 'failed') issues.push(issue('warning'"),
"Unavailable enrollment state must downgrade dashboard health.");
assertTrue(script.body().contains("openWorkspace('activity');\n return loadOperationHistory();"),
"Retry activity must reload operation history after navigating to its page.");
assertTrue(script.body().contains("openWorkspace('access');\n return loadEnrollments();"),
"Retry access must reload enrollments after navigating to its page.");
assertTrue(script.body().contains("dashboardConfigurationGeneration++"));
assertTrue(script.body().contains("|${dashboardConfigurationGeneration}`"));
assertTrue(script.body().contains("Configuration changed; refreshing server overview"));
assertTrue(script.body().contains("if (autoLoadPending.delete(tab)) void autoLoadTab(tab);"));
assertTrue(script.body().contains("await loadNodes();\n } finally {\n suppressNodeAutoLoad--;\n }\n await Promise.all([loadEnrollments(), loadOperationHistory()]);\n if (!inspectionCapableNode())"),
"Dashboard refresh must reload node connectivity before reloading metadata and checking inspection capability.");
assertTrue(script.body().contains("if (suppressNodeAutoLoad === 0) void autoLoadTab(tabFromHash());"),
"An internal dashboard registry refresh must not recursively queue another dashboard load.");
assertTrue(script.body().contains("await Promise.all([loadEnrollments(), loadOperationHistory()]);\n if (!inspectionCapableNode()"),
"An explicit dashboard refresh must reload enrollments and operation history before inspections.");
assertTrue(script.body().contains("Object.keys(operation.nodeStates || {}).length || results.length"),
"Running-operation progress must count all targets, not only completed results.");
assertTrue(script.body().contains("runInspection('overview', {}, null, {manageBusy: false})"));
assertTrue(script.body().contains("inspectionInFlight = false;\n renderMetrics();"),
"A dashboard refresh with no inspection-capable node must release the reserved lane.");
assertEquals(4, script.body().split(java.util.regex.Pattern.quote(
"if (requestedContext !== dashboardContext()) throw new Error('Dashboard context changed while inspecting.');"),
-1).length - 1);
assertFalse(web.body().contains("data-search-term="));
assertTrue(script.body().contains("result.enabledVoteSites > result.configuredVoteSites"));
assertTrue(script.body().contains("renderJsonResult(dataOverview, dashboardOverview);"));
assertTrue(script.body().contains("const summary = {items: [], total: 0, actionable: 0"));
assertTrue(script.body().contains("if (summary.items.length < 30) summary.items.push(item);"));
assertTrue(script.body().contains("const actionable = issueSummary.actionable;"));
assertTrue(script.body().contains("!selected.online || !current || hasWarning"));
assertFalse(script.body().contains("return issues.slice(0, 30);"));
assertTrue(script.body().contains(
"configurations: ['Compare configuration', () => {\n setConfigView('compare');\n runDriftCheck.click();"));
assertTrue(script.body().contains(
"dashboardLoadedContext = '';\n dashboardInspectionStatus.overview = 'failed';"));
assertTrue(script.body().contains("if (requestedContext === dashboardContext() && complete)"));
assertTrue(script.body().contains("disconnected from Control"));
assertTrue(script.body().contains("disconnectedNodes.forEach(node => {"),
"Every disconnected registered node must contribute to the actionable issue total.");
assertFalse(script.body().contains("disconnectedNodes.slice(0, 10)"),
"Disconnected-node issue totals must not stop at the first ten nodes.");
assertTrue(script.body().contains(
"(Array.isArray(proxy.backends) ? proxy.backends : []).forEach(backend => {"),
"Dashboard topology health must inspect every backend returned by the bounded nodes API.");
assertFalse(script.body().contains(
"(Array.isArray(proxy.backends) ? proxy.backends : []).slice(0, 100).forEach(backend => {"),
"Dashboard topology health must not silently omit backend summaries after the first 100 rows.");
assertTrue(script.body().contains("document.createElement('progress')"));
assertTrue(script.body().contains("const count = hasCount ? finiteCount(entry.count) : hasVotes ? finiteCount(entry.votes) : null;"));
assertTrue(script.body().contains("Math.max(...services.map(service => service.count), 1)"));
assertTrue(script.body().contains("track.value = service.count;"));
assertFalse(script.body().contains("service.votes"));
assertTrue(script.body().contains("dashboardInspectionStatus.voteSiteHealth = 'failed';"));
assertTrue(script.body().contains("dashboardInspectionStatus.voteSiteHealth = 'failed';\n dashboardLoadedContext = '';"));
assertTrue(script.body().contains("dashboardInspectionStatus.voteLog24h = 'failed';"));
assertTrue(script.body().contains("dashboardInspectionStatus.voteLog30d = 'failed';"));
assertTrue(script.body().contains("dashboardInspectionStatus.voteLog30d = 'failed';\n dashboardLoadedContext = '';"));
assertTrue(script.body().contains("Some dashboard checks could not be verified"));
assertTrue(script.body().contains("!current || hasWarning || hasIncompleteInspection ? 'Warning' : 'Healthy'"));
assertTrue(script.body().contains("function normalizeDashboardCollection(value, maximum, normalize)"));
assertTrue(script.body().contains("if (!Array.isArray(value)) return {items: [], incomplete: true};"));
assertTrue(script.body().contains("normalizeDashboardVoteSiteHealth"));
assertTrue(script.body().contains("dashboardHealthContradictsOverview(dashboardOverview, health.result)"));
assertTrue(script.body().contains("health.sites.length === configured"));
assertTrue(script.body().contains("health.sites.filter(site => site.enabled === true).length === enabled"));
assertTrue(script.body().contains("['truncated', 'detectedUnconfiguredServicesTruncated'].forEach"));
assertTrue(script.body().contains("typeof source[field] !== 'boolean' || source[field] === true"));
assertTrue(script.body().contains(
"else if (dashboardOverview.enabledVoteSites === 0) issues.push(issue('warning', 'All Vote Sites are disabled'"),
"A configured backend with every Vote Site disabled must not appear healthy.");
assertTrue(script.body().contains("const allConfiguredSitesDisabled = siteCountsKnown && configured > 0 && enabled === 0;"));
assertTrue(script.body().contains("+ (allConfiguredSitesDisabled ? 1 : 0)"),
"The Vote Sites summary must count the all-disabled warning as needing attention.");
assertTrue(script.body().contains("sites.filter(site => site.status === 'SERVICE_SITE_MISSING')"),
"Individually disabled Vote Sites must remain quiet when another site is enabled.");
assertTrue(script.body().contains("const voteSiteKeys = new Set();"));
assertTrue(script.body().contains("const canonicalKey = key.value.toLowerCase();"));
assertTrue(script.body().contains("const key = boundedDashboardString(entry.key, 64, true);"),
"Vote-site health must reject keys beyond the 64-character wire limit.");
assertTrue(script.body().contains("|| !key.value || voteSiteKeys.has(canonicalKey)"),
"Vote-site health must reject empty and duplicate site keys as incomplete data.");
assertFalse(script.body().contains("(!key.value && !displayName.value)"),
"A display name must not substitute for a missing vote-site key.");
assertTrue(script.body().contains("voteSiteKeys.add(canonicalKey);"));
assertTrue(script.body().contains("const serviceSite = boundedDashboardString(entry.serviceSite, 64, true);"),
"Vote-site health must enforce the node's 64-character ServiceSite wire bound.");
assertTrue(script.body().contains("const detectedServiceKeys = new Set();"));
assertTrue(script.body().contains("const configuredServiceKeys = new Set(sites.items.map(site => site.serviceSite.toLowerCase()));"));
assertTrue(script.body().contains("configuredServiceKeys.has(identity)"),
"Detected services must not duplicate a configured ServiceSite identity.");
assertTrue(script.body().contains(
"if (service.incomplete || configuredServiceKeys.has(identity) || unmatchedServiceKeys.has(identity)) return null;"),
"Unmatched services must not duplicate a configured ServiceSite identity.");
assertTrue(script.body().contains("const unmatchedServiceKeys = new Set();"));
assertTrue(script.body().contains("const service = boundedDashboardString(entry.serviceSite, 64);"),
"Unmatched VoteLog identities must use the same 64-character wire limit as other service values.");
assertTrue(script.body().contains("unmatchedServiceKeys.has(identity)"),
"Unmatched service identities must be rejected case-insensitively when duplicated.");
assertTrue(script.body().contains("unmatchedServiceKeys.add(identity)"));
assertTrue(script.body().contains("detectedServiceKeys.has(identity)"),
"Detected service identities must be rejected case-insensitively when duplicated.");
assertTrue(script.body().contains(
"if (source.voteLogReadable !== true && unmatched.items.length > 0) incomplete = true;"),
"Unmatched services must make unreadable VoteLog health data incomplete.");
assertTrue(script.body().contains("source.voteLogReadable === true ? unmatched.items : []"),
"Unreadable VoteLog data must not render non-authoritative unmatched services.");
assertTrue(script.body().contains("normalizeDashboardVoteSummary"));
assertTrue(script.body().contains("countRowsExceedTotal(services.items, total)"));
assertTrue(script.body().contains("countRowsExceedTotal(servers.items, total)"));
assertTrue(script.body().contains("function countRowsSumMatchesTotal(items, total)"));
assertTrue(script.body().contains(
"return items.length >= 20 || items.reduce((sum, entry) => sum + entry.count, 0) === total;"),
"Untruncated VoteLog category lists must account for every vote while retaining truncated-list behavior.");
assertTrue(script.body().contains("!countRowsSumMatchesTotal(services.items, total)"));
assertTrue(script.body().contains("!countRowsSumMatchesTotal(servers.items, total)"));
assertTrue(script.body().contains("total > 0 && (services.items.length === 0 || servers.items.length === 0"),
"A nonempty VoteLog total must include at least one top service and server.");
assertTrue(script.body().contains("!countRowsArePositive(services.items) || !countRowsArePositive(servers.items)"),
"VoteLog category rows must not include zero-count rows, including when the total is zero.");
assertFalse(script.body().contains("total > 0 && (services.items.length === 0 || servers.items.length === 0\n || !countRowsArePositive(services.items)"),
"Zero-total VoteLog summaries must not bypass positive category-count validation.");
assertTrue(script.body().contains("function countRowsArePositive(items)"));
assertTrue(script.body().contains("return items.every(entry => entry.count > 0);"));
assertTrue(script.body().contains("function countRowsAreNonIncreasing(items)"),
"VoteLog category rows must retain their descending-count order.");
assertTrue(script.body().contains("if (items[index].count > items[index - 1].count) return false;"));
assertTrue(script.body().contains("!countRowsAreNonIncreasing(services.items)"));
assertTrue(script.body().contains("!countRowsAreNonIncreasing(servers.items)"));
assertTrue(script.body().contains("function normalizeDashboardCountRows(value, maximum, label)"));
assertTrue(script.body().contains("boundedDashboardString(entry[label], 64, false)"),
"VoteLog service and server identities must enforce the 64-character wire limit.");
assertTrue(script.body().contains("const identities = new Set();"));
assertTrue(script.body().contains("const identity = name.value.toLowerCase();"));
assertTrue(script.body().contains("if (identities.has(identity)) return null;"));
assertTrue(script.body().contains("function invalidateDashboardInspection()"));
assertTrue(script.body().contains("lastOverview = diagnostics.result;\n invalidateDashboardInspection();"));
assertTrue(script.body().contains("lastOverview = envelope.result;\n invalidateDashboardInspection();"),
"Setup diagnostics must invalidate any cached dashboard evidence.");
assertTrue(script.body().contains("function invalidVoteLoggingState(value)"));
assertTrue(script.body().contains("Object.hasOwn(value, 'voteLogAvailable') ? value.voteLogAvailable : value.voteLoggingAvailable"));
assertTrue(script.body().contains("const proxyMethods = new Set(['PLUGINMESSAGING', 'REDIS', 'MQTT', 'MYSQL', 'SOCKETS', 'HTTP']);"));
assertTrue(script.body().contains("result.proxyMode === true && !proxyMethods.has(result.proxyMethod.toUpperCase())"));
assertTrue(script.body().contains("const requiredStrings = new Set(['pluginVersion', 'platform', 'serverSoftware', 'serverVersion', 'dataStorage']);"));
assertTrue(script.body().contains("field === 'proxyMethod'"));
assertTrue(script.body().contains("const platforms = new Set(['BUKKIT']);"));
assertTrue(script.body().contains("const dataStorages = new Set(['SQLITE', 'MYSQL']);"));
assertTrue(script.body().contains("immediate + cached !== total"));
assertTrue(script.body().contains("total > 0 && uniqueVoters <= 0"),
"A nonempty VoteLog summary must report at least one unique voter.");
assertTrue(script.body().contains("function dashboardVoteSummariesContradict(shortWindow, longWindow)"));
assertTrue(script.body().contains(
"const scalarContradiction = ['total', 'immediate', 'cached', 'uniqueVoters'].some(field =>"),
"All shared VoteLog counters must be monotonic across nested windows.");
assertTrue(script.body().contains("function dashboardCountRowIdentity(entry, label)"),
"VoteLog top-row comparisons must use the same normalized identity rules as row validation.");
assertTrue(script.body().contains("function dashboardCountRowsContradict(shortRows, longRows, label)"));
assertTrue(script.body().contains("longCounts.has(identity)"),
"Shared nested-window identities must be compared.");
assertTrue(script.body().contains("const widerWindowIsComplete = longRows.length < 20;"),
"An absent service/server is conclusive only when the wider top-row list is not truncated.");
assertTrue(script.body().contains("if (!longCounts.has(identity)) return widerWindowIsComplete;"),
"A 24-hour category omitted by an untruncated 30-day list must invalidate the summaries.");
assertTrue(script.body().contains("shortCount > longCounts.get(identity)"),
"A larger 24-hour count for a shared service/server identity must invalidate the summaries.");
assertTrue(script.body().contains(
"dashboardCountRowsContradict(shortWindow?.topServices, longWindow?.topServices, 'service')"));
assertTrue(script.body().contains(
"dashboardCountRowsContradict(shortWindow?.topServers, longWindow?.topServers, 'server')"));
assertTrue(script.body().contains("dashboardInspectionStatus.voteLog24h = 'incomplete';\n dashboardInspectionStatus.voteLog30d = 'incomplete';"));
assertTrue(script.body().contains("entry.count > remaining"));
assertTrue(script.body().contains("const expectedStatuses = entry.enabled === false"));
assertTrue(script.body().contains("typeof entry.hasRewards !== 'boolean'"),
"Readable Vote Site rows must include a typed reward-presence field.");
assertTrue(script.body().contains("function validDashboardVoteSiteAggregate(entry, status)"));
assertTrue(script.body().contains(
"aggregateFields.some(field => Object.hasOwn(entry, field))"),
"Unreadable VoteLog rows must reject non-authoritative aggregate fields.");
assertTrue(script.body().contains("const loggedVotes = finiteCount(entry.loggedVotes);"),
"Readable Vote Site health rows must validate every aggregate as a nonnegative safe integer.");
assertTrue(script.body().contains("immediateVotes + cachedVotes !== loggedVotes"),
"Readable Vote Site health rows must preserve the logged/immediate/cached sum.");
assertTrue(script.body().contains("loggedVotes === 0 ? lastVoteTime !== 0 : lastVoteTime === 0"),
"A Vote Site last-vote timestamp must be zero exactly when its readable aggregate is empty.");
assertTrue(script.body().contains("status === 'ACTIVE' && loggedVotes === 0"),
"ACTIVE Vote Site rows must contain at least one logged vote.");
assertTrue(script.body().contains("status === 'NO_RECENT_VOTES' && loggedVotes !== 0"),
"NO_RECENT_VOTES rows must contain no logged votes.");
assertTrue(script.body().contains("function dashboardHealthContradictsVoteSummary(health, summary)"));
assertTrue(script.body().contains("function dashboardHealthServicesContradictSummary(sites, topServices)"),
"Vote Site health must compare each normalized service aggregate with the 30-day ranking.");
assertTrue(script.body().contains("const topServicesComplete = topServices.length < 20;"),
"A short top-services list is complete, so an omitted configured service is contradictory.");
assertTrue(script.body().contains("const topServiceCounts = new Map();"));
assertTrue(script.body().contains("return loggedVotes > 0 && topServicesComplete;"),
"A zero-vote site may be omitted from a complete positive-count ranking.");
assertTrue(script.body().contains(
"if (!topServiceCounts.has(serviceIdentity)) return loggedVotes > 0 && topServicesComplete;"),
"A configured service with votes omitted from a complete top-services list must invalidate the snapshot.");
assertTrue(script.body().contains("return loggedVotes > topServiceCounts.get(serviceIdentity);"),
"Per-service logged VoteLog counts must not exceed their 30-day ranking counts.");
assertTrue(script.body().contains(
"if (dashboardHealthServicesContradictSummary(health.sites, summary.topServices)) return true;"),
"Per-service health and 30-day summary contradictions must invalidate both inspections.");
assertTrue(script.body().contains("[['loggedVotes', 'total'], ['immediateVotes', 'immediate'], ['cachedVotes', 'cached']]"),
"Each readable per-site VoteLog aggregate must be bounded by its corresponding 30-day summary total.");
assertTrue(script.body().contains("siteCount > summaryCount"),
"Sequentially inconsistent per-site and overall VoteLog reads must be treated as incomplete.");
assertTrue(script.body().contains("function dashboardHealthAggregateExceedsSummary(sites, siteField, summaryCount)"),
"Retained readable VoteLog site aggregates must be bounded in aggregate by summary counters.");
assertTrue(script.body().contains("const countedServices = new Set();"));
assertTrue(script.body().contains("countedServices.has(serviceIdentity)"),
"Aliases sharing a canonical ServiceSite must not double-count the same VoteLog aggregate.");
assertTrue(script.body().contains("return serviceIdentity.length >= 64;"),
"Duplicate ServiceSite values at the node serialization bound must remain unchecked as possibly truncated.");
assertTrue(script.body().contains("aggregate += siteCount;"));
assertTrue(script.body().contains("const serviceAggregates = new Map();"),
"Aliases sharing a ServiceSite must be checked against the same aggregate snapshot.");
assertTrue(script.body().contains("function dashboardVoteSiteAggregatesMatch(left, right)"),
"ServiceSite aliases with contradictory aggregates must invalidate the health snapshot.");
assertTrue(script.body().contains("!dashboardVoteSiteAggregatesMatch(previousAggregate, aggregate)"),
"Contradictory ServiceSite aliases must not be silently deduplicated.");
assertTrue(script.body().contains(
"dashboardHealthAggregateExceedsSummary(\n health.sites, siteField, summaryCount)"));
assertTrue(script.body().contains("dashboardHealthContradictsVoteSummary(dashboardVoteSiteHealth, dashboardVoteSummary30d)"));
assertTrue(script.body().contains("dashboardInspectionStatus.voteSiteHealth = 'incomplete';\n dashboardInspectionStatus.voteLog30d = 'incomplete';"),
"Conflicting 30-day health and summary evidence must make both dashboard inspections unhealthy.");
assertTrue(script.body().contains("lastOverview = null;\n text(dataOverview, 'Refreshing server overview…');"));
assertTrue(script.body().contains("async function refreshOverview(target = dataOverview) {\n invalidateDashboardInspection();"));
assertTrue(script.body().contains(".result, 1);"));
assertTrue(script.body().contains("hasCount && hasVotes && count !== legacyCount"));
assertTrue(script.body().contains("days == null || days !== expectedDays || total == null"));
assertTrue(script.body().contains("topServices: services.items, topServers: servers.items"));
assertTrue(script.body().contains("typeof value === 'number' && Number.isSafeInteger(value) && value >= 0"),
"Dashboard counts must reject null, booleans, whitespace strings, and fractional values.");
assertFalse(script.body().contains("const count = Number(value);"));
assertFalse(script.body().contains("Number(dashboardOverview.configuredVoteSites) === 0"));
assertTrue(script.body().contains("const siteCountsKnown = configured != null && enabled != null;"));
assertTrue(script.body().contains("text(metricVoteSites, !siteCountsKnown ? '—'"));
assertTrue(script.body().contains(
"+ dashboardVoteSiteHealth.unmatchedLoggedServices.length"),
"Unmatched services must contribute to the Vote Sites warning count.");
assertFalse(script.body().contains(
"SERVICE_SITE_MISSING').slice(0, 10)"),
"All bounded missing ServiceSite entries must contribute to the health summary.");
assertFalse(script.body().contains(
"detectedUnconfiguredServices.slice(0, 10)"),
"All bounded detected-service entries must contribute to the health summary.");
assertFalse(script.body().contains(
"unmatchedLoggedServices.slice(0, 10)"),
"All bounded unmatched-service entries must contribute to the health summary.");
assertFalse(script.body().contains(
"['FAILED', 'COMPLETED_WITH_ERRORS'].includes(operation.state)).slice(0, 5)"),
"All bounded failed operations must contribute to the dashboard issue total.");
assertTrue(script.body().contains("runDriftCheck.addEventListener('click', async () => {\n setConfigView('compare');"));
assertTrue(script.body().contains("voteSitesConfigured: configuredVoteSites == null ? null : configuredVoteSites > 0"));
assertTrue(script.body().contains("voteSitesConfiguredKnown: configuredVoteSites != null"));
int exactShortcut = script.body().indexOf("const exactShortcut = GLOBAL_PAGE_SHORTCUTS.get(normalized);");
int fuzzySetting = script.body().indexOf("const setting = SETTINGS_SCHEMA.find");
assertTrue(exactShortcut >= 0 && exactShortcut < fuzzySetting);
assertTrue(script.body().contains("['rewards', {tab: 'quick-setup', scrollTarget: 'reward-builder-card'}]"));
assertTrue(script.body().contains("['vote sites', {tab: 'data', scrollTarget: 'site-health-card'}]"));
assertTrue(script.body().contains("['network doctor', {tab: 'network', scrollTarget: 'network-doctor-card'}]"));
assertTrue(script.body().contains("['configuration compare', {tab: 'configurations', configView: 'compare'"));
assertTrue(script.body().contains("openGlobalShortcut(GLOBAL_PAGE_SHORTCUTS.get('configuration compare'))"));
assertTrue(script.body().contains("globalSearchInput.value = '';\n globalSearchOptions.replaceChildren();"));
assertTrue(web.body().contains("data-tab=\"configurations\" data-config-shortcut=\"compare\""));
assertTrue(script.body().contains("if (button.dataset.configShortcut) setConfigView(button.dataset.configShortcut);"));
assertTrue(script.body().contains("if (setting) {\n settingsFilter.value = query;"));
int openWorkspace = script.body().indexOf("function openWorkspace(tab, scrollTarget = '', preset = '', navigationButton = null)");
int presetBeforeTab = script.body().indexOf("quickPreset.value = preset;", openWorkspace);
int activateAfterPreset = script.body().indexOf("setActiveTab(tab, true);", openWorkspace);
assertTrue(openWorkspace >= 0 && presetBeforeTab > openWorkspace && activateAfterPreset > presetBeforeTab,
"Nested shortcuts must establish their preset before tab autoload starts.");
assertTrue(script.body().contains("if (preset && quickPreset.value !== preset) {\n"
+ " quickPreset.value = preset;\n loadedQuickSetup = null;\n"
+ " quickSetupDirty = false;\n quickSetupPreserveReadGeneration = -1;\n"
+ " pendingDetectedVoteSite = null;"),
"A shortcut replacing the preset must discard dirty state from the previous form before autoloading.");
assertTrue(script.body().contains("pendingDetectedVoteSite = {nodeId: selectedServerId, key, service: String(service).slice(0, 200)};\n"
+ " selectedNodes = new Set(selectedServerId ? [selectedServerId] : []);\n"
+ " loadedQuickSetup = null;\n quickSetupDirty = false;\n"
+ " quickSetupPreserveReadGeneration = -1;"),
"Detected-site navigation must discard dirty state from the previous preset before autoloading.");
assertTrue(script.body().contains("if (autoLoadInFlight.has(tab)) {\n autoLoadPending.add(tab);"));
assertTrue(script.body().contains("if (autoLoadPending.delete(tab)) void autoLoadTab(tab);"),
"A preset change during an older read must queue a fresh autoload.");
assertTrue(script.body().contains("quickPresetReadable() && !await loadQuickSetupValues(true)"),
"Loading a saved profile must read live values before enabling the template.");
assertTrue(script.body().contains("applyProfileValues(profile);"),
"The saved template must be restored after the live read rather than overwritten by it.");
assertTrue(script.body().contains("node.acceptedCapabilities.includes('config.proxy-method.v1')\n || node.acceptedCapabilities.includes('config.proxy-method.v2')"),
"An HTTP v2-only proxy must be selectable while each method action still checks its exact capability.");
assertTrue(script.body().contains("const methodNetwork = proxyMethodNetwork(proxyMethodCapabilityFor(button.dataset.proxyMethod));"),
"Method actions must retain their exact per-method capability check.");
assertTrue(script.body().contains("const readCapability = proxyMethodReadCapability();"));
assertTrue(script.body().contains("readCapability === 'config.proxy-method.v2' ? 'HTTP' : 'PLUGINMESSAGING'"),
"A v2-only proxy must read its current method through the capability it advertises.");
assertTrue(script.body().contains("readCapability !== proxyMethodReadCapability()"),
"A proxy-method read must be discarded when the negotiated capability changes while it is in flight.");
assertTrue(script.body().contains("autoLoadPending.clear();"));
int globalShortcut = script.body().indexOf("function openGlobalShortcut(destination)");
int selectConfigView = script.body().indexOf("setConfigView(destination.configView);", globalShortcut);
int openShortcutTab = script.body().indexOf("openWorkspace(destination.tab", globalShortcut);
assertTrue(globalShortcut >= 0 && selectConfigView > globalShortcut && openShortcutTab > selectConfigView,
"Nested search shortcuts must establish their subview before tab autoload starts.");
int globalNodeSearch = script.body().indexOf("if (node) {");
int locateNodePage = script.body().indexOf(
"selectNodePage(Math.floor(nodePosition / PAGE_SIZE) * PAGE_SIZE);", globalNodeSearch);
int openServersForSearch = script.body().indexOf("openWorkspace('servers');", globalNodeSearch);
int selectServerForSearch = script.body().indexOf("selectPrimaryServer(node.nodeId);", globalNodeSearch);
int renderSearchedPage = script.body().indexOf("renderNodeViews();", selectServerForSearch);
assertTrue(globalNodeSearch >= 0 && locateNodePage > globalNodeSearch
&& openServersForSearch > locateNodePage
&& selectServerForSearch > openServersForSearch && renderSearchedPage > selectServerForSearch,
"Global server search must show the matching page, then navigate before selecting the node.");
int selectNodePage = script.body().indexOf("function selectNodePage(offset)");
assertTrue(selectNodePage >= 0
&& script.body().indexOf("text(pageNumber, `Page ${Math.floor(pageOffset / PAGE_SIZE) + 1}`);",
selectNodePage) > selectNodePage
&& script.body().indexOf("previousPage.disabled = pageOffset === 0;", selectNodePage)
> selectNodePage
&& script.body().indexOf(
"nextPage.disabled = pageOffset + visibleNodeItems.length >= allNodeItems.length;",
selectNodePage) > selectNodePage,