Skip to content

Feat/v5 - #49

Draft
mCodex wants to merge 61 commits into
mainfrom
feat/v5
Draft

Feat/v5#49
mCodex wants to merge 61 commits into
mainfrom
feat/v5

Conversation

@mCodex

@mCodex mCodex commented Jul 20, 2026

Copy link
Copy Markdown
Owner

No description provided.

mCodex added 4 commits July 17, 2026 11:26
…el catalog, model registry, online models, performance budget, replay, resource loot reward, runtime, safety envelope, snapshot builder, tactical blackboard, tactical states, target proposal, UI bridge, and UI presenter

- Implement tests for lifecycle initialization and termination
- Verify loader order for unified tick and event bus
- Ensure metrics maintain bounded counters, gauges, and samples
- Test model catalog registration and lifecycle
- Validate model registry behavior and evidence handling
- Check online models for streaming statistics and Markov state predictions
- Assess performance budget degradation of optional work
- Confirm deterministic replay functionality
- Evaluate resource and loot observation handling
- Test runtime initialization and lifecycle management
- Validate safety envelope for decision-making
- Ensure snapshot builder reconciles spectators correctly
- Test tactical blackboard for owner validation and expiration
- Validate tactical proposal states for lure and pull behaviors
- Ensure target proposal adapts legacy targets correctly
- Verify UI bridge exposes required sections
- Test UI presenter for state mapping and command execution

Update ring buffer utility to export globally and bump version to 5.0.0
…with v5 API updates

- Updated discovery_spec.lua to enhance test coverage for the Discovery orchestrator, including state transitions and policy states.
- Revised readiness_spec.lua to incorporate backward compatibility and new role-based readiness checks.
- Enhanced scheduler_spec.lua with additional tests for action processing, acknowledgment, and backoff mechanisms.
- Improved state_machine_spec.lua to reflect new state definitions and transition logic, including terminal state checks.
- Added comprehensive tests for tactical intelligence in tactical_intelligence_spec.lua, ensuring accurate model diagnostics and unified read models.
- Updated bot_doctor_spec.lua to include new checks for actionable intelligence issues and performance metrics.
- Modified ui_bridge_spec.lua to reflect changes in UI sections for the Tactical Intelligence window.
…ning to Tactical Intelligence

- Deleted HuntAnalyzer and its associated UI components.
- Updated analytics event names to reflect the new Tactical Intelligence framework.
- Refactored intelligence runtime to publish canonical events for session management and loot observation.
- Enhanced model catalog to use a neutral prior for fresh predictions.
- Improved monster profiling by integrating telemetry data into Tactical Intelligence.
- Updated documentation to reflect changes in analytics reporting and module integration.
- Added unit tests for new functionality and legacy cleanup.
@coderabbitai

coderabbitai Bot commented Jul 20, 2026

Copy link
Copy Markdown

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f94ece41-5e4e-41c2-95dc-979f2cb34f52

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/v5

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

mCodex and others added 25 commits July 20, 2026 11:50
Defines 20 closure reasons and 5 ambiguous reasons for episode
state machine validation. Provides isValid(), isAmbiguous(), and
all() API. Registered as nExBot.IntelligenceOutcomeReasons.
Defines IntelligenceEventSchema with SCHEMA_VERSION, TYPES enum,
REQUIRED_FIELDS, and validation helpers (isValidType, requiredFieldsFor,
hasField). Tests cover schema version, all 25 types, common fields,
per-type fields, unknown/nil rejection, and global registration.
Implements bounded event deduplication with LRU eviction for the
intelligence pipeline. Tracks both eventId and idempotencyKey with
proper cleanup on eviction. 16 tests covering all API surface.
Removed player:health, player:mana, container:update, and combat:target
from the second EventBus block — they were already handled by the
sectionTracker block above, causing double dirty-marking.
- OutcomeRecord.new(config): create instance
- record:create(config): create outcome with decisionId, actionId, closureReason
- record:validate(outcome): validate well-formed outcome
- record:measure(outcome, key, value): add measurement to outcome
- Validates closureReason against IntelligenceOutcomeReasons
- 20 passing tests, no regressions
Creates core/intelligence/records/decision_record.lua with create, close,
and validate methods. Follows outcome_record.lua patterns. Includes 29
busted tests covering required field validation, decisionType enum
checking, default prediction table, outcome attachment, and global
registration.
- EpisodeBase.new/create/close/validate/isOpen API
- Validates episode types: action, encounter, loot, route_segment, hunt
- Uses IntelligenceOutcomeReasons for closure validation
- Idempotent close (returns unchanged if already closed)
- Non-mutating close (returns copy)
- 24 passing tests
- Tracker.new(config) with episodeBase dependency
- start/close/get/getOpen/stats API
- 17 passing tests
- Tracker manages loot episode lifecycle via EpisodeBase
- API: start, close, get, getOpen, stats
- Validates required fields, rejects duplicate IDs
- Tracks lootLifecycle counters per episode
- 20 passing tests
- Initialize episodeBase, encounterTracker, lootEpisodeTracker,
  routeSegmentTracker, huntTracker in runtime init block
- Add combat:target_changed handler to start encounter episodes
- Add loot:received handler to start loot episodes
- Set/clear sessionId and huntId on session start/end events
- Use dofile fallbacks for test compatibility
- Cost.new(config) with optional initialCosts
- getCost(action, context), recordCost(action, cost), getAverage(action)
- 7 passing tests
- Add optional eventFactory/eventContext params to LootObserver.new()
- Emit loot_item_observed on each item in observe()
- Add moveAttempted() emitting loot_move_attempted
- Add moveVerified() emitting loot_move_verified
- Register as nExBot.IntelligenceLootObserver
- 13 tests passing, no regressions
- Initialize rewardVector and rewardNormalizer after episode tracker
- Add intelligence:encounter_closed event handler
- Update test fixtures to load reward modules
- target_value_model, route_reliability_model, resource_efficiency_model
- timing_model, risk_assessment_model, loot_opportunity_model
- ensemble_meta_model (combines other model predictions)

Each model extracts contextual features and maintains per-model state.
Dynamic dispatch wrappers ensure method overrides work through registry.

Co-Authored-By: opencode <[email protected]>
TDD: 6 tests covering construction, gate evaluation, promotion
eligibility, and insufficient data handling.
mCodex added 30 commits July 21, 2026 09:31
…n explanations

- Explainer.new(config) constructor
- explain(decision) returns explanation table with baseline, selected, adjustment, confidence, factors, guardrails, pricesKnown, modelVersion
- format(explanation) returns readable string
- Handles missing fields gracefully
Replace obsolete model names (NavigationCostModel, MonsterBehaviorModel,
TargetUtilityModel, TargetSwitchModel, LureSafetyModel, PullContinuationModel,
WavePredictionModel) with equivalents from the rewritten model catalog
(RouteReliabilityModel, TargetValueModel, RiskAssessmentModel,
ResourceEfficiencyModel, TimingModel).
All 28 new modules created during the v5 ML redesign were missing
from the loader, causing runtime.lua to fail when trying to load
them via dofile() fallback. Added them in dependency order before
intelligence/runtime.
…vider, kill_switch

Three modules used bare globals instead of nExBot.X registration,
causing runtime.lua to fail loading when the loader couldn't find them.
This cascade-failed everything downstream (applyContextAdjustment,
advanceGeneration, etc.)
OTClient uses Lua 5.1/LuaJIT where unpack is a global function,
not table.unpack (which doesn't exist pre-5.2).
OTClient's sandbox apparently strips both unpack and table.unpack
from globals. The existing shim in event_bus.lua only fires if
unpack exists (which it doesn't here). Replaced with a simple
ipairs-based copy function.
…on tests

- ReleaseReason enum with validation and hard-release classification
- ReachabilityState enum with 9 states (attackable, temporary, hard-release)
- CombatFrameRecorder with bounded 256-entry ring buffer
- CombatFixture test helper for deterministic combat simulation
- 7 characterization regression tests documenting target abandonment bugs
  - 5 pass against current code (documenting correct behavior)
  - 2 fail (documenting bugs: quarantine invalidation, stale callbacks)
- 17 unit tests for enums and combat frame (all passing)
…TargetCommitmentManager

- ReachabilityService: multi-state returns (9 states), evidence accumulation
  per creature, CONFIRMED_HARD_UNREACHABLE requires 3+ failures across
  different positions or 5+ consecutive over 3s, LRU eviction (64 entries)
- TargetCommitmentManager: formal target lease system with acquire/release,
  blocksRelease for non-hard reasons during minimumHoldMs, generation tokens,
  single active commitment
- 22 unit tests (10 reachability + 12 commitment) all passing
…andidateEvaluator

- AttackFSM: sole attack owner with 8 states (IDLE, ACQUIRING, ATTACKING,
  CONFIRMING_ATTACK, LOCKED, REPOSITIONING, TEMPORARILY_BLOCKED,
  RECOVERING_TARGET, RELEASING), generation tokens prevent stale callbacks,
  failed replacement preserves current target, commitment-aware transitions
- TargetCandidateEvaluator: structured lexicographic scoring with
  safetyTier, commitmentTier, killCompletionScore, reachabilityConfidence,
  attackContinuityScore; commitment-tier targets cannot be preempted
- 23 unit tests (10 FSM + 13 evaluator) all passing
…ment bugs

PRIMARY BUG FIX (attack_coordinator.lua):
- Remove AttackStateMachine.stop() call when invalid replacement candidate
  fails reachability validation. The candidate is now rejected without
  touching the current valid target.

SECONDARY BUG FIXES (attack_state_machine.lua):
- Active monitor: use ReachabilityService to distinguish temporary vs hard
  failures. Temporary failures no longer cancel attack or clear target.
- ENGAGING/LOCKED handlers: boundary failures only release target on hard
  reachability states (DIFFERENT_FLOOR, HARD_UNREACHABLE), not on single
  temporary failures.

QUARANTINE FIX (monster_reachability.lua):
- player:position EventBus handler now clears quarantines in addition to
  path cache. Stale quarantines no longer persist after player moves.

LOAD ORDER (core/cavebot.lua):
- Domain layer (release_reasons, reachability_states, reachability_service,
  target_commitment, target_evaluator) loaded before application layer.
- Application layer (combat_frame, attack_fsm) loaded after ASM.

TEST FIXES:
- Combat fixture: added EventBus mock, BotCore mock
- All 7 characterization regression tests now pass
- Full suite: 898 successes, 0 failures, 0 errors
…tion

- LurePlanner: executable lure plans with destination, progress tracking,
  deferred when finish commitment active
- DynamicLurePlanner: state machine (INACTIVE→PLANNING→GATHERING→COMPLETED),
  participant tracking by ID, entry/exit dwell hysteresis
- PullPlanner: executable pull plans requiring destination+path,
  progress/stall/abort detection
- RepositionPlanner: attack-ring tile search with scoring (distance,
  escape routes, congestion, oscillation penalty), 300ms cache
- 34 tactical unit tests, full suite: 932 successes / 0 failures
…extual ML models

Phase 4 — Arbitration:
- FeatureArbitrator: compatibility matrix (COMPATIBLE/MERGEABLE/
  MUTUALLY_EXCLUSIVE/PREEMPTABLE/HARD_OVERRIDE), precedence ordering,
  commitment enforcement, manual override, safety filter
- MovementArbitrator: single-movement-per-tick guarantee, wraps
  FeatureArbitrator, validates executable positions, commitment-aware

Phase 5 — ML Contextual Models:
- ContextualFeatures: extracts combat feature vectors with deterministic hash
- KillCompletionModel: P(target dies) via online logistic regression
- TargetSwitchRiskModel: P(alive after switch), commitment override returns 1.0
- LureSuccessModel: P(lure formation safe)
- PullSuccessModel: P(creature follows)
- RepositionTileModel: tile ranking via regularized linear scoring
- All models: SHADOW mode default, L2 regularization, bounded weights,
  minSamples gate, reset support
- 35 new tests (20 arbitration + 15 ML), full suite: 967/0/0
…tests

Integration tests (10):
- Full pipeline: discover → commit → attack → release
- Feature interaction: Lure + Pull + FinishKill simultaneously
- CaveBot coordination: pause/resume around commitment
- Reachability evidence accumulation across positions
- Evaluator structured comparison with commitment
- ML shadow mode isolation, reposition target preservation
- DynamicLurePlanner + commitment, MovementArbitrator single-output
- Release reason validation

Property-based tests (12):
- Invalid replacement never invalidates current target
- Committed target requires valid release reason
- Temporary failures stay temporary (3+ needed for hard)
- ML never overrides safety or commitment
- FeatureArbitrator ≤1 output, evaluator transitivity
- Lure/Pull commitment and destination invariants

Soak test (10,000 ticks):
- Unfinished target rate < 1%
- Evidence bounded ≤ 64 entries
- Decision throughput < 2ms per evaluation

Performance benchmarks:
- Evaluator: 0.0008ms avg
- Arbitrator: 0.001-0.018ms by intent count
- Reachability: 0.0018ms per evaluation
- ML prediction: 0.002ms per prediction

Full suite: 992 successes / 0 failures / 0 errors
Documents: layered architecture, ownership table, module reference,
AttackFSM states, reachability states, feature compatibility matrix,
ML governance rules
… handlers

EventBus handlers in monster_ai.lua, movement_coordinator.lua, and
monster_scenario.lua call TargetBot.isOff() but are registered before
target_coordinator.lua (which defines the real isOff) loads.

Add a safe stub in core.lua (loaded first) that delegates to isOn().
The real definition in target_coordinator.lua overrides it on load.
OTClient does not expose _G as a global. Use direct global reference
instead, which is already loaded by core/cavebot.lua before this file.
…leanup

analyzer.lua still references styles defined in these .otui files
(MainAnalyzerWindow, HuntingAnalyzer, LootAnalyzer, etc.). The
legacy cleanup removed them assuming the analyzer was replaced by
Tactical Intelligence, but analyzer.lua was never removed.

Updated legacy_cleanup_spec.lua to assert the files exist rather
than asserting they don't.
- Renamed IntelligenceConsoleWindow to IntelligenceDashboardWindow and updated dimensions in ui_bridge.otui.
- Replaced MultilineTextEdit with a Panel for content display in the UI.
- Enhanced attack_fsm.lua to manage target switching and hold acquisition more effectively, introducing new state variables and logic for pending switches.
- Updated attack_coordinator.lua to streamline attack requests through a unified AttackFSM interface.
- Improved reachability_service.lua to invalidate targets on player and creature movement events.
- Modified event_targeting.lua to delegate path validation to TargetReachability and emit events for target sightings.
- Adjusted targeting architecture tests to ensure proper connections between sighting and acquisition processes.
- Updated model_catalog_spec.lua to reflect changes in the number of registered capabilities.
- Enhanced remediation_spec.lua to verify character context normalization and hunt metrics calculations.
- Refined target_proposal_spec.lua to ensure correct targeting logic with the new AttackFSM structure.
- Updated ui_bridge_spec.lua to reflect changes in the UI structure and ensure proper rendering of reports.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant