-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSimpleNavCoverageSweep.cs
More file actions
2346 lines (2195 loc) · 127 KB
/
Copy pathSimpleNavCoverageSweep.cs
File metadata and controls
2346 lines (2195 loc) · 127 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 System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using UnityEngine;
namespace DateEverythingAccess
{
// In-game coverage sweep harness. A DIAGNOSTIC TOOL whose only job is to surface upstream
// bugs (in the bake or the route planner) fast — it is not tuned for its own sake.
//
// Two modes, selected by the manifest's `mode` (ModConfig.CoverageSweepRunId picks the run):
//
// * WALK mode (run-id "default"): teleport ONCE to the manifest start, then walk to the
// nearest untested CELL, then the next, covering the whole reachable floor set. A stall is
// recorded as an impassable cell — clean upstream data, no recovery machinery.
//
// * OBJECTS mode (run-id "objects"): a walk CHAIN over interactable objects. The player
// starts wherever they are when the sweep toggles on, walks to the nearest unvisited
// object, then from there to the next nearest, exactly as a player would. Arrived = pass.
// A leg that can't reach its object is recorded once WITH ITS REASON (the upstream datum);
// the object stays in the pool to be retried from a different angle later. There is NO
// teleport anywhere in objects mode (per-leg source teleport, same-leg retry/un-wedge, and
// the recovery relocate were all removed — the first two papered over teleport landings and
// dominated the 2026-06-12 log as thrash; the relocate masked broken paths and reached
// genuinely inaccessible outside objects). If one blocker boxes the player into a room, the
// objects it can't reach just record failures and drain via the per-object give-up cap. That
// pile of failures is the point: a path broken enough to trap the player is what most needs
// fixing, so the sweep surfaces it rather than driving around it.
//
// Both stamp the player's cell + 4-neighbour ring into a per-floor verified-reachable bitmap.
//
// Toggle hotkey: Ctrl+Alt+Shift+F8 (wired in Main.cs).
//
// Results emit to artifacts/navigation/sweep/<run-id>/sweep_results.json. Outcomes are flat:
// arrived, no_path, skipped_already_covered, stalled (autowalk gave up), looped (circled a
// small area), door_failed, budget, input_failed (game-state gate), exception. The summary
// collapses to one outcome per object (arrival wins over an earlier failure).
internal static class SimpleNavCoverageSweep
{
// Sweep artifacts live in the project source tree, not in BepInEx/plugins, because the
// route catalogue is many thousands of files (~100 MB) we don't want to duplicate on
// every build. The harness reads them directly from the source path. If the project
// moves, override this via the COVERAGE_SWEEP_DIR env var.
private const string DefaultSweepSourceDir = @"C:\Users\amock\mod template\artifacts\navigation\sweep";
// Walk-mode only: settle wait after the single start teleport (objects-mode no longer
// teleports per leg, so it doesn't use this).
private const float WaitAfterTeleportSeconds = 0.25f;
// Loop detector: player position sampled every ~0.5s; if N consecutive samples sit
// inside a small radius, we call it a loop. Decided 2026-05-20 with the user.
private const float LoopSampleIntervalSeconds = 0.5f;
private const int LoopSampleWindow = 16; // 16 samples × 0.5s = 8s
private const float LoopRadiusMeters = 1.5f;
// Budget ceiling per route: cost_m / 1.5 + 5s. A safety net, not the primary signal.
private const float BudgetMetersPerSecond = 1.5f;
private const float BudgetSlackSeconds = 5f;
// Door-failed detector: if any tagged door on the current segment is still closed
// after this much time (excluding swing-in-progress periods), mark door_failed.
private const float DoorOpenTimeoutSeconds = 4f;
// A leg counts as a GENUINE WALK only if the player actually moved this far (XZ) from the
// route's first waypoint. The walk chain picks the nearest object next, so many legs start
// ON or beside the goal cell — those finish in a fraction of a second WITHOUT testing any
// walk path. They still run the camera-aim LOS raycast, so their LOS verdict is real, but
// crediting them as walk-successes inflates the pass rate (77% of "verified" were such
// no-ops in run 195613).
//
// Below this, the walk is UNTESTED — but for an object whose LOS-interact PASSED, that is
// NOT a gap. An LOS pass proves the goal CELL is a valid interaction standpoint for the
// object. The specific source->cell walk that happened is unrepeatable (the player's real
// start varies and can't be guessed), so it's not bankable — but it doesn't need to be:
// the only runtime requirement is that the planner can route the player TO that cell, which
// is the planner's standing job for ANY cell, independent of this object. So a validated
// interaction cell exists => if the planner plans to that cell for that object, it is valid.
// The walk path is the variable; proving it is not this object's burden.
// See the walk/LOS axis split in ReportWalkLosAxes.
private const float GenuineWalkMeters = 3f;
private enum Phase
{
Idle,
LoadingManifest,
BetweenRoutes,
Running,
// Objects-mode: the follower stopped (arrival OR stall) and we're turning to face
// the object to confirm we can actually interact with it from here. See StepVerifying.
Verifying,
WritingResults,
// Walk-mode phases: one continuous traversal hitting every reachable cell.
WalkPickLeg, // pick next unvisited reachable cell, plan a leg to it.
WalkRunningLeg, // leg's autowalk is in flight; same detectors as Running.
}
// Walk-mode per-cell state. 0=untested, 1=walkable (player stood on it), 2=impassable.
// Stored row-major (ix * nz + iz) per floor, parallel to the manifest's reachable bitmap.
private const byte CellUntested = 0;
private const byte CellWalkable = 1;
private const byte CellImpassable = 2;
private static readonly Dictionary<string, byte[]> _walkState =
new Dictionary<string, byte[]>(StringComparer.OrdinalIgnoreCase);
private static readonly Dictionary<string, bool[]> _walkReachable =
new Dictionary<string, bool[]>(StringComparer.OrdinalIgnoreCase);
private static List<ImpassRecord> _impassRecords;
private static int _walkLegIndex;
private static string _walkTargetFloor;
private static int _walkTargetIx;
private static int _walkTargetIz;
// Cell-snap radius around the current player position. After arriving at a leg target,
// every cell within this many cells of the player counts as walkable too. Set to match
// the player capsule's physical footprint (~0.8m diameter at cell_size=0.2m → 4 cells)
// so the next-leg target picker doesn't return a cell already inside the arrival disc
// and produce zero-distance legs.
private const int WalkVerifyRadiusCells = 4;
private static Phase _phase = Phase.Idle;
// True whenever a sweep is running. The sweep is a diagnostic tool, so the
// follower instrumentation it depends on (wall-slide escape fires, blocked
// reasons) must capture unconditionally while it runs — never gated behind the
// manual DebugMode toggle, or a sweep can't report on its own escape logic.
public static bool IsActive => _phase != Phase.Idle;
// Suppress the in-game phone for the whole sweep. The phone IS the game's pause: opening it
// freezes the player (playerState=CantMove) and plays an open/close animation, during which
// the controller refuses navigation input. An unattended sweep has no reason to open the
// phone, but a stray keypress (Esc/the phone button) during a run did — and every leg that
// tried to start while it was up/animating failed as input_failed, with the chain frozen in
// place until it cleared. Setting PhoneManager.BlockPhoneOpening makes the game's own input
// handler refuse to open the phone, so the pause state can't occur mid-run. This is the
// game's sanctioned mechanism (AtticDoorUnlocker / CinematicBars use it identically). We
// restore the prior value on every sweep teardown so manual play is unaffected afterward.
private static bool _phoneBlockSet;
private static bool _phoneBlockPrev;
private static void SetPhoneBlockedForSweep(bool blocked)
{
try
{
var phone = Singleton<PhoneManager>.Instance;
if (phone == null) return;
if (blocked)
{
if (_phoneBlockSet) return; // already engaged for this run
_phoneBlockPrev = phone.BlockPhoneOpening;
phone.BlockPhoneOpening = true;
_phoneBlockSet = true;
}
else
{
if (!_phoneBlockSet) return; // nothing to restore
phone.BlockPhoneOpening = _phoneBlockPrev;
_phoneBlockSet = false;
}
}
catch { /* never let a phone-state hiccup break sweep start/teardown */ }
}
private static SweepManifest _manifest;
private static int _entryIndex;
private static string _runDir;
// Per-run stamp set once at StartSweep. The run dir is fixed (it holds the input manifest,
// keyed by run-id), so the canonical sweep_results.json is OVERWRITTEN every run — a game
// relaunch right after a sweep clobbers the prior run's detail before it can be reviewed.
// We additionally write a timestamped copy (sweep_results.<stamp>.json) that no later run
// touches, so every run's per-result data survives. Canonical name is kept for tooling.
private static string _runStamp;
private static float _nextActionTime;
private static List<RouteResult> _results;
// Active-route state
private static SimpleNavRoute _currentRoute;
private static int _currentManifestIndex;
private static float _routeStartUnscaledTime;
private static float _routeBudgetSeconds;
private static float _nextLoopSampleTime;
private static readonly Queue<Vector3> _loopWindow = new Queue<Vector3>(LoopSampleWindow + 1);
private static float _doorCloseObservedSince; // 0 = not currently waiting on a door
// Objects-mode is a WALK CHAIN, not a teleport-per-leg harness (reworked 2026-06-12).
// The sweep's only job is to confirm each object can be ARRIVED AT and, when it can't,
// record WHY for upstream (bake/planner) triage — not to be tuned itself. So: the player
// starts wherever they are when the sweep turns on and walks to the nearest unvisited
// object, then from there to the next nearest, and so on — exactly how a player would
// traverse. A leg that fails is recorded once with its reason; no per-leg teleport, no
// un-wedge, no recovery re-plan (all of which existed only to paper over teleport
// landings, and which DOMINATED the 2026-06-12 failure log as thrash).
//
// NO teleport at all (removed 2026-06-17). The sweep walks the whole run from wherever the
// player starts. If one blocker boxes the player into a room, every object it can't reach
// simply records a failure and drains from the pool via the per-object give-up cap — that
// pile of failures IS the signal: a path out so broken the player can get stuck is exactly
// what most needs fixing, and a recovery teleport (which also reached genuinely
// inaccessible outside objects) only masked it. Termination no longer depends on relocation;
// it rests entirely on MaxObjectFailures draining the pool.
// Objects already arrived-at (pass) — by manifest index — so the nearest-unvisited picker
// skips them. A FAILED object is NOT added here: it stays in the pool to be retried from
// every region until reached (its failure reason is recorded each time for triage).
private static readonly HashSet<int> _objectVisited = new HashSet<int>();
// Objects failed during the CURRENT failure streak — skipped by the picker so the strikes
// sample different nearby objects. Cleared on any arrival and on relocate (fresh streak).
private static readonly HashSet<int> _recentlyFailed = new HashSet<int>();
// Per-object lifetime failure count. An object reachable from nowhere would otherwise keep
// the pool from ever draining (it's never marked visited), so once it has failed from
// MaxObjectFailures distinct attempts we give up on it: mark it visited (= leave the pool)
// with its failures already recorded. This is what GUARANTEES the sweep terminates.
private static readonly Dictionary<int, int> _objectFailCount = new Dictionary<int, int>();
private const int MaxObjectFailures = 3;
// Per-floor verified-reachable bitmap. cells[ix * nz + iz] = true once any traversal
// has put the player's cell-ring on that cell. Allocated lazily per floor.
private static readonly Dictionary<string, bool[]> _verified =
new Dictionary<string, bool[]>(StringComparer.OrdinalIgnoreCase);
/// <summary>Toggle the sweep on/off. Wired to the Ctrl+Alt+Shift+F8 hotkey.</summary>
public static void RequestToggle()
{
if (_phase == Phase.Idle) StartSweep();
else AbortSweep("user toggle");
}
/// <summary>Per-frame tick. Cheap when idle.</summary>
public static void Tick()
{
if (_phase == Phase.Idle) return;
try
{
switch (_phase)
{
case Phase.LoadingManifest: /* handled in StartSweep */ break;
case Phase.BetweenRoutes: StepBetweenRoutes(); break;
case Phase.Running: StepRunning(); break;
case Phase.Verifying: StepVerifying(); break;
case Phase.WritingResults: /* handled in finish */ break;
case Phase.WalkPickLeg: WalkStepPickLeg(); break;
case Phase.WalkRunningLeg: WalkStepRunningLeg(); break;
}
}
catch (Exception ex)
{
if (Main.Log != null) Main.Log.LogError("SimpleNavCoverageSweep tick threw: " + ex);
RecordCurrentRouteAsException(ex.Message);
AdvanceToNextEntry();
}
}
private static void StartSweep()
{
// Run-id selects which sweep manifest to drive: "default" (walk-mode cell sweep)
// or "objects" (object-reachability sweep). Configurable via ModConfig so the same
// hotkey can run either without a rebuild.
string runId = ModConfig.CoverageSweepRunId;
string sweepBase = Environment.GetEnvironmentVariable("COVERAGE_SWEEP_DIR");
if (string.IsNullOrEmpty(sweepBase) || !Directory.Exists(sweepBase))
sweepBase = DefaultSweepSourceDir;
_runDir = Path.Combine(sweepBase, runId);
_runStamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture);
string manifestPath = Path.Combine(_runDir, "sweep_manifest.json");
if (!File.Exists(manifestPath))
{
if (Main.Log != null) Main.Log.LogError("SimpleNavCoverageSweep: manifest missing at " + manifestPath);
ScreenReader.Say("Coverage sweep manifest not found", remember: false);
return;
}
_manifest = LoadManifest(manifestPath);
if (_manifest == null)
{
ScreenReader.Say("Coverage sweep manifest unreadable", remember: false);
return;
}
bool walkMode = string.Equals(_manifest.mode, "walk", StringComparison.OrdinalIgnoreCase);
// Dispersed mode requires an entries list; walk mode requires a reachable bitmap.
if (!walkMode && (_manifest.entries == null || _manifest.entries.Length == 0))
{
ScreenReader.Say("Coverage sweep manifest empty", remember: false);
return;
}
if (walkMode && _manifest.reachable_bitmap_rows == null)
{
ScreenReader.Say("Coverage walk-sweep manifest has no reachable bitmap", remember: false);
return;
}
// Allocate verified bitmap per floor; reset the objects-mode walk-chain state.
_verified.Clear();
_objectVisited.Clear();
_recentlyFailed.Clear();
_objectFailCount.Clear();
if (_manifest.floor_frames != null)
{
foreach (var kv in _manifest.floor_frames)
{
int cells = kv.Value.nx * kv.Value.nz;
_verified[kv.Key] = new bool[cells];
}
}
_results = new List<RouteResult>(_manifest.entries?.Length ?? 0);
_entryIndex = 0;
// Block the phone for the whole run (both modes) so a stray keypress can't open the
// game's pause mid-sweep and strand the chain. Restored in every teardown path.
SetPhoneBlockedForSweep(true);
if (walkMode)
{
InitWalkMode();
_phase = Phase.WalkPickLeg;
if (Main.Log != null) Main.Log.LogInfo("SimpleNavCoverageSweep: walk-mode started, reachable cells per floor: " + DescribeReachable());
ScreenReader.Say("Coverage walk-sweep started", remember: false);
_nextActionTime = 0f;
return;
}
_phase = Phase.BetweenRoutes;
_nextActionTime = 0f;
// Close every door once at the start (as walk-mode does). The chain then begins with
// all doors shut and opens them only as the player walks through — so every door is
// tested: can it be opened from where the route planner parks the player on the
// approach side, before passing through? Doors stay in whatever state the chain leaves
// them, so this tests each from the first direction the player reaches it. (Testing
// the reverse direction too is a later pass; one direction is the simple first cut.)
ForceCloseAllDoors();
bool objectMode = string.Equals(_manifest.mode, "objects", StringComparison.OrdinalIgnoreCase);
if (Main.Log != null) Main.Log.LogInfo("SimpleNavCoverageSweep: started, mode=" +
(_manifest.mode ?? "dispersed") + " entries=" + _manifest.entries.Length);
ScreenReader.Say((objectMode ? "Object reachability sweep started, " : "Coverage sweep started, ")
+ _manifest.entries.Length + (objectMode ? " objects" : " routes"), remember: false);
}
private static void InitWalkMode()
{
_walkState.Clear();
_walkReachable.Clear();
_impassRecords = new List<ImpassRecord>(64);
_walkLegIndex = 0;
_walkPlannerFailureCount = 0;
if (_manifest.reachable_bitmap_rows == null || _manifest.floor_frames == null) return;
foreach (var kv in _manifest.floor_frames)
{
FloorFrame frame = kv.Value;
int cells = frame.nx * frame.nz;
_walkState[kv.Key] = new byte[cells];
bool[] reachable = new bool[cells];
string[] rows = _manifest.reachable_bitmap_rows.ForFloor(kv.Key);
if (rows != null && rows.Length == frame.nx)
{
for (int ix = 0; ix < frame.nx; ix++)
{
string row = rows[ix];
if (row == null) continue;
int rowBase = ix * frame.nz;
int upper = Math.Min(row.Length, frame.nz);
for (int iz = 0; iz < upper; iz++)
if (row[iz] == '1') reachable[rowBase + iz] = true;
}
}
_walkReachable[kv.Key] = reachable;
}
}
private static string DescribeReachable()
{
var sb = new System.Text.StringBuilder();
foreach (var kv in _walkReachable)
{
int n = 0; for (int i = 0; i < kv.Value.Length; i++) if (kv.Value[i]) n++;
if (sb.Length > 0) sb.Append(", ");
sb.Append(kv.Key); sb.Append('='); sb.Append(n);
}
return sb.ToString();
}
private static void AbortSweep(string reason)
{
if (Main.Log != null) Main.Log.LogInfo("SimpleNavCoverageSweep: abort reason=" + reason + " completed=" + (_results?.Count ?? 0));
// If a route was in flight, stop the autowalk cleanly.
try { SimpleNavBridge.EndStep(); } catch { }
FlushResults();
FlushWalkResults();
SetPhoneBlockedForSweep(false);
_phase = Phase.Idle;
_manifest = null;
_currentRoute = null;
_results = null;
_verified.Clear();
_objectVisited.Clear();
_recentlyFailed.Clear();
_objectFailCount.Clear();
_walkState.Clear();
_walkReachable.Clear();
_impassRecords = null;
_walkStartTeleported = false;
ScreenReader.Say("Coverage sweep stopped", remember: false);
}
// ---- Phase: BetweenRoutes ---------------------------------------------------------
// Walk-chain leg picker: from the player's CURRENT position, find the nearest unvisited
// object and plan a live route to it. No per-leg source teleport — the leg starts wherever
// the previous leg ended. Offline-planner failures (status != ok) are recorded once up
// front. When every object is visited (or only unreachable ones remain after we've
// exhausted relocation), the sweep finishes.
private static void StepBetweenRoutes()
{
// Make sure any previous run is fully torn down.
try { SimpleNavBridge.EndStep(); } catch { }
// Record offline-planner verdicts once, up front, and treat them as visited so the
// nearest-object picker never selects them (the offline planner already said no_path).
for (; _entryIndex < _manifest.entries.Length; _entryIndex++)
{
var e = _manifest.entries[_entryIndex];
if (e == null) continue;
if (string.Equals(e.status, "ok", StringComparison.Ordinal)) continue;
// Upgradeable offline no_path (no_collider / no_los) with a resolvable target:
// do NOT veto it up front. Leave it unvisited so the picker drives it and the
// LIVE planner decides — the offline raycaster can't see a collider the live
// component-walk resolves, nor live physics LOS. Only record the offline verdict
// for genuinely-unrouteable entries. See
// [[project-navigation-no-collider-root-cause-2026-06-17]].
if (e.drive_offline_no_path && e.object_xyz != null && e.object_xyz.Length >= 3)
continue;
_results.Add(new RouteResult
{
manifest_index = _entryIndex,
floor = e.floor,
cell = e.cell,
outcome = e.status, // e.g. "no_path"
name = e.name,
});
_objectVisited.Add(_entryIndex);
}
if (BetterPlayerControl.Instance == null) { AbortSweep("objects: no player"); return; }
Vector3 playerPos = BetterPlayerControl.Instance.transform.position;
if (!PickNearestUnvisitedObject(playerPos, out int idx))
{
// Nothing left to reach.
FinishSweep();
return;
}
_currentManifestIndex = idx;
BeginCurrentLeg(playerPos);
}
// Begin a leg: plan a live route from the player's CURRENT position to the picked object
// and drive it. No source teleport — `fromPos` is wherever the player already is. Doors
// are left in whatever state prior legs left them (a walking player doesn't re-close doors
// between objects); the route opens any door it needs.
private static void BeginCurrentLeg(Vector3 fromPos)
{
if (BetterPlayerControl.Instance == null)
{
RecordCurrentRouteAsException("no-player");
AdvanceToNextEntry();
return;
}
PlanAndDriveFrom(fromPos);
}
// Pick the nearest unvisited object (by straight-line distance from `fromPos`) whose live
// transform we can resolve. "Unvisited" = not yet arrived-at AND not an offline no_path.
// Failed-but-reachable-elsewhere objects stay eligible, so a later chain can reach them
// from a different angle. Within a failure streak we also skip objects we JUST failed
// (_recentlyFailed), so the consecutive strikes sample DIFFERENT nearby objects — that
// makes "N failures in a row" a real "this region is boxed in" probe rather than the same
// unreachable object re-failing in place N times. If skipping them leaves nothing, we fall
// back to allowing them (better to re-test than to stall the chain). Returns false only
// when no eligible object exists at all.
private static bool PickNearestUnvisitedObject(Vector3 fromPos, out int idx)
{
if (PickNearestUnvisitedObject(fromPos, true, out idx)) return true;
return PickNearestUnvisitedObject(fromPos, false, out idx);
}
private static bool PickNearestUnvisitedObject(Vector3 fromPos, bool excludeRecentlyFailed, out int idx)
{
idx = -1;
float bestD2 = float.PositiveInfinity;
for (int i = 0; i < _manifest.entries.Length; i++)
{
if (_objectVisited.Contains(i)) continue;
if (excludeRecentlyFailed && _recentlyFailed.Contains(i)) continue;
var e = _manifest.entries[i];
if (e == null) continue;
// Eligible: an "ok" entry, OR an upgradeable offline no_path (no_collider /
// no_los) we want the live planner to re-decide. Both need a resolvable target.
bool eligible = string.Equals(e.status, "ok", StringComparison.Ordinal)
|| (e.drive_offline_no_path && e.object_xyz != null && e.object_xyz.Length >= 3);
if (!eligible) continue;
if (e.object_xyz == null || e.object_xyz.Length < 3) continue;
float dx = e.object_xyz[0] - fromPos.x;
float dy = e.object_xyz[1] - fromPos.y;
float dz = e.object_xyz[2] - fromPos.z;
float d2 = dx * dx + dy * dy + dz * dz;
if (d2 < bestD2) { bestD2 = d2; idx = i; }
}
return idx >= 0;
}
// Resolve the live DEST object, plan to it from `startWorld` exactly as in-game WalkTo
// does, face the first heading, and hand the route to the driver.
private static void PlanAndDriveFrom(Vector3 startWorld)
{
ManifestEntry entry = _manifest.entries[_currentManifestIndex];
Transform playerTransform = BetterPlayerControl.Instance.transform;
SimpleNavRoute route = PlanLegToObject(entry, startWorld);
if (route == null)
{
// C# planner refused from the player's current position — a planner verdict, not a
// drive stall. Record the SPECIFIC reason so an interactability defect doesn't hide
// inside the generic no_path bucket: TargetNoLineOfSight means the object is
// reachable but occluded from every navigable cell (a placement/occluder problem to
// investigate), distinct from genuinely can't-get-there. Then chain on.
FinishLeg(SimpleNavPlanner.LastFailure == SimpleNavPlanner.PlanFailure.TargetNoLineOfSight
? "no_los"
: "no_path");
return;
}
_currentRoute = route;
// Face the second waypoint so the first input doesn't waste a turn.
if (route.Waypoints != null && route.Waypoints.Count > 1)
{
Vector3 toNext = route.Waypoints[1] - startWorld;
toNext.y = 0f;
if (toNext.sqrMagnitude > 0.0001f)
playerTransform.rotation = Quaternion.LookRotation(toNext.normalized, Vector3.up);
}
// No teleport to settle — start driving immediately from where the player stands.
_routeStartUnscaledTime = Time.unscaledTime;
_routeBudgetSeconds = ComputeBudgetSeconds(route);
_loopWindow.Clear();
_nextLoopSampleTime = Time.unscaledTime + LoopSampleIntervalSeconds;
_doorCloseObservedSince = 0f;
if (!AccessibilityWatcher.TryStartCoverageSweepRoute(route, out string detail))
{
// Game wasn't in a controllable state (dialogue/menu/CantMove). Record the reason
// and chain on — it counts toward the consecutive-failure relocation budget.
FinishLeg("input_failed:" + detail);
return;
}
_phase = Phase.Running;
}
// Resolve the live DEST object and plan to it with the C# planner exactly as the in-game
// WalkTo does — so the sweep validates the routes the game itself would choose. We resolve
// by name + nearest position because the object id in the manifest is a serialized id, not
// the runtime GetInstanceID the planner keys on; the live object's own InstanceID is used.
private static SimpleNavRoute PlanLegToObject(ManifestEntry entry, Vector3 startWorld)
{
float tx = entry.object_xyz != null && entry.object_xyz.Length > 0 ? entry.object_xyz[0] : 0f;
float ty = entry.object_xyz != null && entry.object_xyz.Length > 1 ? entry.object_xyz[1] : 0f;
float tz = entry.object_xyz != null && entry.object_xyz.Length > 2 ? entry.object_xyz[2] : 0f;
InteractableObj dst = ResolveLiveObject(entry.unique_id, entry.unique_ids, entry.name, tx, ty, tz);
Vector3 targetPos = dst != null && dst.transform != null ? dst.transform.position : new Vector3(tx, ty, tz);
int goId = dst != null && dst.gameObject != null ? dst.gameObject.GetInstanceID() : 0;
string goName = dst != null && dst.gameObject != null ? dst.gameObject.name : entry.name;
float radius = entry.interaction_radius > 0.5f ? entry.interaction_radius : 1.0f;
bool isDatable = dst != null && !string.IsNullOrWhiteSpace(dst.inkFileName);
string inkFile = dst != null ? dst.inkFileName : null;
return SimpleNavPlanner.Plan(startWorld, targetPos, radius, goName, goId, isDatable, inkFile);
}
// Resolve the live InteractableObj for a manifest leg. PREFERRED: an exact match on the
// stable scene id (uniqueId / any uniqueIds member == InteractableObj.Id). FALLBACK:
// the legacy bridge — name match + nearest transform position (names aren't unique, so
// position disambiguates). The id path is exact and instance-correct; the fallback covers
// older manifests that predate the unique-id field.
private static InteractableObj ResolveLiveObject(string uniqueId, string[] uniqueIds, string name, float x, float y, float z)
{
bool haveId = !string.IsNullOrWhiteSpace(uniqueId) || (uniqueIds != null && uniqueIds.Length > 0);
if (string.IsNullOrEmpty(name) && !haveId) return null;
InteractableObj[] all = UnityEngine.Object.FindObjectsOfType<InteractableObj>();
// Exact stable-id bridge first.
if (haveId)
{
for (int i = 0; i < all.Length; i++)
{
InteractableObj o = all[i];
if (o == null || o.gameObject == null) continue;
string id;
try { id = o.Id; } catch { id = null; }
if (string.IsNullOrWhiteSpace(id)) continue;
if (!string.IsNullOrWhiteSpace(uniqueId) && string.Equals(id, uniqueId, StringComparison.OrdinalIgnoreCase))
return o;
if (uniqueIds != null)
{
for (int j = 0; j < uniqueIds.Length; j++)
{
if (!string.IsNullOrWhiteSpace(uniqueIds[j]) &&
string.Equals(id, uniqueIds[j], StringComparison.OrdinalIgnoreCase))
return o;
}
}
}
}
// Fallback: name match + nearest position.
if (string.IsNullOrEmpty(name)) return null;
InteractableObj best = null;
float bestD2 = float.PositiveInfinity;
for (int i = 0; i < all.Length; i++)
{
InteractableObj o = all[i];
if (o == null || o.gameObject == null) continue;
// Match the cleaned/base name OR the raw GameObject name — the manifest stores the
// picker's display name, which may be a stripped form of the GameObject name.
if (!NameMatches(o.gameObject.name, name)) continue;
Vector3 p = o.transform.position;
float dx = p.x - x, dy = p.y - y, dz = p.z - z;
float d2 = dx * dx + dy * dy + dz * dz;
if (d2 < bestD2) { bestD2 = d2; best = o; }
}
return best;
}
private static bool NameMatches(string goName, string manifestName)
{
if (string.IsNullOrEmpty(goName) || string.IsNullOrEmpty(manifestName)) return false;
if (string.Equals(goName, manifestName, StringComparison.OrdinalIgnoreCase)) return true;
// The manifest name is the picker's stripped label; accept a contains-match either way
// so "glass" matches "glass_MODEL_UPDATE" and stripped forms match their raw names.
return goName.IndexOf(manifestName, StringComparison.OrdinalIgnoreCase) >= 0
|| manifestName.IndexOf(goName, StringComparison.OrdinalIgnoreCase) >= 0;
}
// ---- Phase: Running ---------------------------------------------------------------
// Watch the autowalk. Stamp player position into the verified bitmap every frame.
// Decide outcome whenever one of the detectors fires.
private static void StepRunning()
{
if (BetterPlayerControl.Instance == null)
{
FinishLeg("exception:no-player");
return;
}
Vector3 playerPos = BetterPlayerControl.Instance.transform.position;
// Stamp the player's cell + 4-neighbour ring into the verified bitmap on the
// floor whose Y-band the player is currently in.
StampCoverage(playerPos);
// 1. Arrival vs stall: did the route succeed, or did the autowalk give up?
// Both end with HasActiveRoute=false; disambiguate by checking proximity to target.
//
// SWEEP ARRIVAL = reaching the route's final waypoint (the goal STAND-CELL), NOT
// SimpleNavBridge.HasArrivedAtRouteTarget. That shared method's object-target branch
// also requires being within the OBJECT TRANSFORM's interaction radius — but sweep
// objects sit on shelves / walls / beds whose transform is up to ~12m (median ~7.4m)
// from the nearest reachable floor cell, so 251/757 routes can NEVER satisfy it even
// standing perfectly on the goal cell. That made every driven leg fall through to the
// progress-timeout and log "stalled" (arrived=0/1045). The sweep's question is "can
// the player REACH the navigable stand-cell next to this object", i.e. the final
// waypoint the planner already placed at the closest reachable floor. Use that.
// On EITHER outcome — reached the goal cell, or the follower gave up — hand off to
// the interaction probe before recording. Geometric arrival is only a proxy; the
// probe turns to face the object and asks the game whether we can actually interact
// from here. Re-probing on STALL too is deliberate: a follower that times out 1.5m
// short may already be in range (a false-negative stall), and the probe promotes it
// rather than recording a phantom failure. The geometric verdict is carried as
// context so the probe's result can be mapped to the right outcome. See StepVerifying.
if (HasReachedGoalWaypoint(playerPos))
{
BeginVerify(geometricallyAtCell: true);
return;
}
if (!SimpleNavBridge.HasActiveRoute)
{
// Autowalk ended the step but we're not within the tight 1.35m goal cell. Two very
// different reasons land here and the sweep MUST distinguish them, or it miscounts
// legitimate arrivals as stalls (the dominant artifact in the 2026-06-13 run):
// - The follower ARRIVED: it stopped because the player is within the object's
// InteractionRadius (HasArrivedAtRouteTarget), which for a large-radius object
// (charcoal/log/food, radius up to 7.5m) is routinely >1.35m from the goal cell.
// This is a real arrival by the game's own rule — verify selection from here.
// - The follower GAVE UP: a progress timeout stopped it short. That's a stall.
// LastSweepDriveArrived carries which one it was. Either way we re-probe (a true
// arrival still needs the interaction/LOS check; a short stall may yet be in range),
// but the geometric verdict controls how a GaveUp probe is recorded:
// arrived_unconfirmed vs stalled. See [[project-navigation-stalls-are-proximity-miscount-2026-06-13]].
BeginVerify(geometricallyAtCell: AccessibilityWatcher.LastSweepDriveArrived);
return;
}
// 2. Door-open failure.
if (SimpleNavBridge.ActiveDoor != null)
{
DoorPortal door = SimpleNavBridge.ActiveDoor;
bool open = door.open;
bool moving = SimpleNavBridge.IsActiveDoorMoving();
if (!open && !moving)
{
if (_doorCloseObservedSince <= 0f) _doorCloseObservedSince = Time.unscaledTime;
else if (Time.unscaledTime - _doorCloseObservedSince > DoorOpenTimeoutSeconds)
{
FinishLeg("door_failed:" + (door.gameObject != null ? door.gameObject.name : "<null>"));
return;
}
}
else
{
_doorCloseObservedSince = 0f;
}
}
else
{
_doorCloseObservedSince = 0f;
}
// 3. Loop detector — sampled, not per-frame.
if (Time.unscaledTime >= _nextLoopSampleTime)
{
_nextLoopSampleTime = Time.unscaledTime + LoopSampleIntervalSeconds;
Vector3 sample = new Vector3(playerPos.x, 0f, playerPos.z);
_loopWindow.Enqueue(sample);
while (_loopWindow.Count > LoopSampleWindow) _loopWindow.Dequeue();
if (_loopWindow.Count == LoopSampleWindow && AllSamplesWithinRadius(_loopWindow, LoopRadiusMeters))
{
FinishLeg("looped");
return;
}
}
// 4. Budget ceiling — safety net.
if (Time.unscaledTime - _routeStartUnscaledTime > _routeBudgetSeconds)
{
FinishLeg("budget");
return;
}
// 5. Steering stall: the autowalk's own progress detector kicks in when the player
// hasn't moved; it will call StopNavigationBlocked, which ends the route via the
// HasActiveRoute=false branch above. Nothing extra to do here — the autowalk's
// _lastAutoWalkProgressTime detector is the stall signal.
}
// ---- Phase: Verifying -------------------------------------------------------------
// The follower stopped. Confirm the object is actually INTERACTABLE from here by turning
// to face it and asking the game's own precondition (InteractableManager.IsPlayerInRange
// with the object selected). This re-partitions the geometric arrival/stall verdict into
// ground truth:
// - in range → arrived_verified (the object is reachable AND usable)
// - in range, gated → arrived_gated (positioned fine; dateable eligibility gate
// refuses — not a nav failure)
// - turn timed out:
// was at goal cell → arrived_unconfirmed (reached the cell but couldn't select the
// object — a geometric FALSE POSITIVE)
// stopped short → stalled (a genuine nav failure)
// Stamps coverage while turning so the verified bitmap still credits the spot.
// True when the follower reached the goal cell before this probe (vs. gave up short).
private static bool _verifyGeometricallyAtCell;
private static void BeginVerify(bool geometricallyAtCell)
{
_verifyGeometricallyAtCell = geometricallyAtCell;
// Tear the autowalk drive down but keep the route installed — the probe needs the
// route's target to resolve the look point and the in-range match.
try { SimpleNavBridge.EndStep(); } catch { }
AccessibilityWatcher.ProbeSweepInteraction(_currentRoute, reset: true);
_phase = Phase.Verifying;
}
private static void StepVerifying()
{
if (BetterPlayerControl.Instance != null)
StampCoverage(BetterPlayerControl.Instance.transform.position);
AccessibilityWatcher.SweepProbeState state =
AccessibilityWatcher.ProbeSweepInteraction(_currentRoute, reset: false);
switch (state)
{
case AccessibilityWatcher.SweepProbeState.Turning:
return; // keep turning next frame
case AccessibilityWatcher.SweepProbeState.InRange:
FinishLeg("arrived_verified");
return;
case AccessibilityWatcher.SweepProbeState.InRangeGated:
FinishLeg("arrived_gated");
return;
case AccessibilityWatcher.SweepProbeState.GaveUp:
// Couldn't select the object from where we stopped. If we'd reached the goal
// cell, the cell is a geometric false-positive (reached, not interactable);
// if we stopped short, it's a real stall.
FinishLeg(_verifyGeometricallyAtCell ? "arrived_unconfirmed" : "stalled");
return;
}
}
// Sweep arrival: the player is within one cell-and-a-bit of the route's FINAL waypoint
// (the goal stand-cell), on the same floor level. XZ-only proximity plus a Y gate that
// rejects mid-stair poses (player still descending reads close in XZ but is meters up in
// Y). Deliberately independent of the object transform — see the StepRunning note.
private const float GoalWaypointArrivalRadiusM = 1.35f; // mirrors WaypointArrivalRadius
private const float GoalWaypointMaxYDeltaM = 1.5f; // mirrors ArrivalMaxYDeltaM
private static bool HasReachedGoalWaypoint(Vector3 playerPos)
{
if (_currentRoute == null || _currentRoute.Waypoints == null || _currentRoute.Waypoints.Count == 0)
return false;
Vector3 goal = _currentRoute.Waypoints[_currentRoute.Waypoints.Count - 1];
if (Mathf.Abs(playerPos.y - goal.y) > GoalWaypointMaxYDeltaM)
return false;
float dx = goal.x - playerPos.x;
float dz = goal.z - playerPos.z;
return (dx * dx + dz * dz) <= GoalWaypointArrivalRadiusM * GoalWaypointArrivalRadiusM;
}
// A drive stall is worth retrying only if THIS attempt actually got the player moving
// before it stalled — i.e. the follower made progress down the corridor and then wedged
// A game-state gate (not a nav result): the player controller wasn't in CanControl, a
// menu/dialogue/popup/phone was up, or the view wasn't HOUSE when the leg tried to start.
// Transient (the prior leg's interaction is still settling) and says nothing about whether
// the route is walkable, so it's bucketed separately from real nav failures in the summary
// and doesn't stamp a failure cell. See GetNavigationUnavailableReason for the full set.
private static bool IsTransientGateOutcome(string outcome)
{
return !string.IsNullOrEmpty(outcome) && outcome.StartsWith("input_failed");
}
// A SUCCESSFUL arrival: the object was reached AND interaction was confirmed (or only the
// dateable eligibility gate refused, which is positioning-fine). These mark the object
// visited and end the failure streak. NOT included: arrived_unconfirmed — that reached
// the goal cell but could not select the object (a geometric false-positive), so it's
// treated like a failure (stays in the pool, counts toward the give-up cap) until a
// later approach from a different angle either confirms it or exhausts the retries.
private static bool IsArrivalOutcome(string outcome)
{
return outcome == "arrived" || outcome == "arrived_verified" || outcome == "arrived_gated";
}
// End the current leg: record its outcome once, then chain to the next nearest object from
// wherever the player now stands. There is no recovery relocation — if a blocker boxes the
// player in, the trapped objects record failures and drain via the per-object give-up cap.
private static void FinishLeg(string outcome)
{
// Tear down the autowalk regardless of what we do next.
try { AccessibilityWatcher.StopCoverageSweepRoute(); } catch { }
RecordLegResult(outcome);
if (IsArrivalOutcome(outcome))
{
// Reached: mark visited so the picker won't re-select it. Making progress clears the
// recently-failed skip set so those objects become eligible again from this new
// position.
_objectVisited.Add(_currentManifestIndex);
_recentlyFailed.Clear();
}
else
{
// Failed: the object stays in the pool to be retried from another angle — UNLESS it
// has now failed MaxObjectFailures times, in which case we give up on it (mark
// visited so it leaves the pool; its failures are recorded). The per-object cap
// counts EVERY failure including transient gates, so an object we can never even
// start a route to still eventually leaves the pool — this is what guarantees the
// sweep terminates. _recentlyFailed makes the picker sample DIFFERENT nearby objects
// after a failure rather than re-failing the same one in place.
_recentlyFailed.Add(_currentManifestIndex);
int fails = _objectFailCount.TryGetValue(_currentManifestIndex, out int f) ? f + 1 : 1;
_objectFailCount[_currentManifestIndex] = fails;
if (fails >= MaxObjectFailures) _objectVisited.Add(_currentManifestIndex);
}
_currentRoute = null;
// Periodically flush so a crash doesn't lose hours of progress.
if ((_results.Count % 50) == 0) FlushResults();
// Always chain on from where the player stands — no relocation. A long failure streak
// just means a region is boxed in; those objects keep recording failures until the
// per-object give-up cap drains them from the pool (which is what terminates the sweep).
_phase = Phase.BetweenRoutes;
}
private static void RecordLegResult(string outcome)
{
var entry = _manifest.entries[_currentManifestIndex];
Vector3 endPos = BetterPlayerControl.Instance != null
? BetterPlayerControl.Instance.transform.position
: Vector3.zero;
Vector3 startPos = _currentRoute != null && _currentRoute.Waypoints != null && _currentRoute.Waypoints.Count > 0
? _currentRoute.Waypoints[0]
: Vector3.zero;
float displacement = Vector3.Distance(new Vector3(startPos.x, 0, startPos.z),
new Vector3(endPos.x, 0, endPos.z));
var result = new RouteResult
{
manifest_index = _currentManifestIndex,
floor = entry.floor,
cell = entry.cell,
outcome = outcome,
cost_m = entry.cost_m,
elapsed_s = Time.unscaledTime - _routeStartUnscaledTime,
displacement_m = displacement,
name = entry.name,
};
if (!IsArrivalOutcome(outcome))
{
RuntimeBlockerProbe probe = RuntimeBlockerProbe.Last;
RuntimeBlockerProbe.Hit hit = probe?.Nearest();
if (hit != null)
{
result.blocker_path = hit.Path;
result.blocker_layer = hit.Layer;
result.blocker_distance = hit.Distance;
result.blocker_mode = ClassifyBlockerMode(hit);
}
// Probe is one-shot; clear so the next route doesn't see a stale value.
RuntimeBlockerProbe.Last = null;
// Reliable stall triage: classify the navmesh state at where the player ACTUALLY
// got stuck (endPos), independent of the unreliable nearest-collider blocker label.
// Resolve the floor from the player's real Y, NOT entry.floor: entry.floor is the
// TARGET's floor, but a cross-floor leg can stall before the player gets there (still
// downstairs, or mid-stair at an in-between Y) — classifying that stuck position
// against the wrong floor's grid gives garbage. The player's Y picks the right grid.
string stuckFloor = entry.floor;
SimpleNavPlanner.TryGetPlayerFloorLabel(endPos.y, out string resolvedFloor);
if (!string.IsNullOrEmpty(resolvedFloor)) stuckFloor = resolvedFloor;
result.stall_class = SimpleNavPlanner.ClassifyStallCell(stuckFloor, endPos.x, endPos.z);
}
_results.Add(result);
if (Main.Log != null)
// entry.cell is null for driven offline-no_path entries (no_collider / no_los —
// they carry object_xyz instead of a baked cell); guard the deref so logging a
// successfully-driven such leg doesn't NPE into a bogus exception result.
Main.Log.LogInfo("SimpleNavCoverageSweep result idx=" + _currentManifestIndex +
" floor=" + entry.floor +
" cell=" + (entry.cell != null && entry.cell.Length >= 2
? "(" + entry.cell[0] + "," + entry.cell[1] + ")" : "(none)") +
" outcome=" + outcome +
" elapsed=" + (Time.unscaledTime - _routeStartUnscaledTime).ToString("0.0") +
" start=" + startPos.ToString("F2") + " end=" + endPos.ToString("F2") +
" moved=" + displacement.ToString("0.00") + "m");
}
private static void RecordCurrentRouteAsException(string detail)
{
if (_currentManifestIndex < 0 || _currentManifestIndex >= _manifest.entries.Length) return;
var entry = _manifest.entries[_currentManifestIndex];
_results.Add(new RouteResult
{
manifest_index = _currentManifestIndex,
floor = entry.floor,
cell = entry.cell,
outcome = "exception:" + detail,
name = entry.name,
});
_objectVisited.Add(_currentManifestIndex); // don't re-pick an object we can't resolve
}
private static void AdvanceToNextEntry()
{
_currentRoute = null;
_phase = Phase.BetweenRoutes;
if ((_results.Count % 50) == 0) FlushResults();
}
private static void FinishSweep()
{
FlushResults();
WriteVerifiedBitmaps();
// The walk chain can record the SAME object several times — a failure, then (after a
// relocate) a later pass from a different angle. The summary is about OBJECTS, not
// attempts, so collapse to one outcome per manifest_index, with "arrived" winning over
// any earlier failure (the object is reachable; the earlier failure is kept in the raw
// results for triage). A real nav failure beats a transient gate; gate beats nothing.
var finalOutcome = new Dictionary<int, string>();
for (int i = 0; i < _results.Count; i++)
{
int idx = _results[i].manifest_index;
string o = _results[i].outcome ?? "";
if (!finalOutcome.TryGetValue(idx, out string prev))
{
finalOutcome[idx] = o;
continue;
}
finalOutcome[idx] = BetterOutcome(prev, o);
}
int passed = 0, skipped = 0, failed = 0, noPath = 0, noLos = 0, offFloor = 0, gated = 0, unconfirmed = 0;
foreach (string o in finalOutcome.Values)
{
if (IsArrivalOutcome(o)) passed++;