Module: Lich::Gemstone::Combat::Processor

Defined in:
documented/gemstone/combat/processor.rb

Overview

Note:

This module is called from Common::Events#on_chunk when combat lines arrive. Script authors do not call it directly.

Combat event parser and state machine for converting game output into structured attack/damage/crit events.

Parses game lines chunk by chunk (segments cut on prompt boundaries) using a state machine that transitions: SEEKING_ATTACK -> SEEKING_DAMAGE -> (repeat). Resolves spawn-tree lineage (parent/child attack relationships), emits events for persistence, and applies damage/wounds/statuses to creature instances.

Constant Summary collapse

POSITION_STATUSES =

The floor positions are mutually exclusive: a creature is prone OR sitting OR kneeling (or none), never several at once, and the stand-up messagings are shared between them.

%w[prone sitting kneeling].freeze
SPELL_RELEASING_FLARES =

Trailing-effect / DoT tick defs whose line names the VICTIM but never the CASTER (pestilence's per-round boils, web's ensnare). They exist so the tick damage is not dropped - but when the tick arrives with no cast in the blob (a nearby player's DoT ticking on a creature we can see, or one we walked in on), it is NOT ours. Marked :unowned so the damage still lands on the creature (its received-total is real) while staying out of our damage-dealt rollup, and sits in the recorder's other/unknown bucket for later adjudication - missing def vs genuine drive-by (owner ruling 2026-09-06). A tick IS ours only when our own cast of that spell is visible in the same blob (see cast_owner tracking below). :bleed has no cast at all, so it is always unowned (owner 2026-09-07). Flares that RELEASE a spell instead of dealing damage themselves (Holy Weapon 1625: the infused spell fires at the start of a swing). The cast that follows is the flare's spell, and it lands in the MIDDLE of the swing - before the swing's own AS/DS. It is handled like an inbound attack cutting in: the swing is saved as interrupted_own, the spell runs as its own event, and the first PHYSICAL roll (AS/DS, UAF/UDF - a warding cast never rolls one) resumes the swing, which then owns that roll and its damage. Before this the cast's event held the swing's roll and damage, and a pummel bracket was dropped as an "unexpected attack" by its own weapon's spell (Dreadt log 2026-09-11 594-613).

%i[weapon_cast].freeze
ROLL_BEFORE_ROUND_ASSAULTS =

Assaults whose per-round roll PRECEDES the round line (barrage: an aim SMR before each arrow, claimed at the arrow's creation - see the roll-routing notes). While one is open a held maneuver roll is ours; every other assault rolls after its round line.

%i[barrage].freeze
UNOWNED_TICK_ATTACKS =

Attack names that are trailing DoT/effect ticks naming the victim but not the caster.

When one of these arrives with no owning cast visible in the same chunk (a nearby player's DoT ticking on a creature we can see, or one we walked in on), it is marked :unowned so the damage still lands on the creature's received total but stays out of our damage-dealt rollup, filed instead in the recorder's other/unknown bucket for later adjudication by the log owner.

A tick IS ours only when our own cast of that spell is visible in the same blob (see cast_owner tracking in parse_events). :bleed has no cast at all, so it is always unowned.

See Also:

%i[pestilence web bleed rot spiritual_malady poison_tick].freeze
SUMMARY_DAMAGE_ATTACKS =

Initiations whose inline "causing N points of damage!" restates the "... N points of damage!" line that follows (that line carries the crit) - applying both doubled the tick (hunt log 2026-09-07 23:20).

%i[spiritual_malady].freeze
SINGLE_HIT_ATTACKS =

Side effects of another attack that land exactly ONE hit and then hand the line back to the attack they interrupted: a mount toppled by our briar pins its rider ("X is pinned beneath Y as it falls!", one damage line + crit), then the briar's own grapple damage on the mount prints. Without this the mount's damage landed on the pin row and the nettles line spawned an empty pin copy on the mount (hunt log 2026-09-08 00:25).

%i[mount_collapse].freeze
SEQUENCE_ROUND_NAMES =

Sequence brackets (Definitions::Sequences) whose rounds are attack events of the SAME name: a round that prints no initiation line of its own (a missed volley arrow: roll + dodge only) is still one.

%i[volley].freeze
PROMPT_TIME_PATTERN =

Regexp matching the server timestamp in a chunk's tag.

Extracts the game server's epoch second (captured group 1) so duration estimates (stun expiry, status timestamps) can be anchored to server time rather than local Time.now, correcting for clock skew between the server and the local machine (tracked by XMLData.server_time_offset).

Examples:

"  <prompt time=\"1234567890\" /> done." =~ PROMPT_TIME_PATTERN
#=> 2; $1 == "1234567890"

See Also:

  • #prompt_time
/<prompt time="(\d+)"/.freeze
ECHO_FLARES =

Flares whose announce spawns a fresh own swing of the same attack (the image/afterimage "echoes your attack with one of its own").

%i[mirror_image hunters_afterimage].freeze
NARRATION_PATTERN =

Creature-linked lines that carry no combat fact and must not drive the target switcher (see the skip in parse_events).

Regexp.union(
  / leaps from the back of .+? as .+? topples, narrowly avoiding being pinned/,
  / looks a little bit more wary after that display!/,
  # a hidden creature revealed by an AoE flare - printed BEFORE the
  # bloom line that names it, so it switched the target early and the
  # bloom's damage landed on a phantom `fire` (hunt log 2026-09-07
  # 22:14:27, the cannibal)
  / is forced out of hiding!/,
  # post-kill/rage emotes naming the creature
  / gurgles out an animalistic shriek of rage, /,
  # a sanguine ooze splitting on the hit - names the new oozeling
  # between the damage line and the next arrow (hunt log 2026-09-07
  # 23:19: phantom fires on the oozeling, volley rounds split)
  / splatter across the ground, wobbling disconcertingly as they twitch together to form /,
  / pulses larger, bubbling grotesquely with new mass\./,
  / pulses monstrously as .+? swells to its full size!/,
  /\AYou are now targeting /
).freeze
DEATH_WATCH_MAX =

A touched creature stays watched until it dies or leaves the registry. It used to expire after three sweeps ("a much later death is not this event's"), which left creatures we fought and someone else finished minutes later marked alive (hunt log 2026-09-07: two mastodons dead in the room feed, both "Alive: true"). Credit is the recorder's call - a dead status outside any attack window credits nobody - so watching longer only fixes killed_at. Bounded FIFO.

256

Class Method Summary collapse

Class Method Details

.apply_crit(creature, crit, event, flare: nil) ⇒ Object

Applies one parsed crit to a creature: primary wound, secondary wound, amputation, fatal. Shared by swing crits and flare crits (flares crit through the same tables their damage type uses).



2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
# File 'documented/gemstone/combat/processor.rb', line 2191

def apply_crit(creature, crit, event, flare: nil)
  if crit[:wound_rank] && crit[:wound_rank] > 0
    # Map CritRanks location to creature body part format
    body_part = map_critranks_to_body_part(crit[:location])
    if body_part
      creature.add_injury(body_part, crit[:wound_rank])
      Lich::Common::Events.emit('combat.wound', id: creature.id, name: creature.name,
                             attack: event[:name], flare: flare, location: crit[:location],
                             body_part: body_part, rank: crit[:wound_rank])
      record_delta(creature) { |d| d[:wounds] << "#{body_part}:#{crit[:wound_rank]}" }
      respond "  +wound: #{body_part} rank #{crit[:wound_rank]}" if Tracker.debug?(:verbose)
    else
      # Surfaced in summary too: a crit that parsed but could not be
      # mapped is exactly the drift worth spotting against game text.
      record_delta(creature) { |d| d[:wounds] << "?#{crit[:location]}:#{crit[:wound_rank]}" }
      respond "  !unknown body part: #{crit[:location]}" if Tracker.debug?(:verbose)
    end
  end

  # A crit can wound a second location (e.g. a strike that carries
  # through); previously only the primary was registered.
  if (secondary = crit[:secondary_wound])
    apply_secondary_wound(creature, secondary, event)
  end

  # Amputation is a distinct terminal state, not accumulated rank.
  if crit[:amputated] && (part = map_critranks_to_body_part(crit[:location]))
    creature.amputate!(part)
    Lich::Common::Events.emit('combat.amputation', id: creature.id, name: creature.name,
                                attack: event[:name], flare: flare, location: crit[:location],
                                body_part: part)
    record_delta(creature) { |d| d[:wounds] << "#{part}:AMPUTATED" }
    respond "  +AMPUTATED: #{part}" if Tracker.debug?(:verbose)
  end

  # Check for fatal critical hit
  if crit[:fatal]
    creature.mark_fatal_crit!
    Lich::Common::Events.emit('combat.fatal_crit', id: creature.id, name: creature.name,
                                attack: event[:name], flare: flare, location: crit[:location])
    record_delta(creature) { |d| d[:statuses] << 'FATAL' }
    respond "  +FATAL CRIT: #{crit[:location]} - creature died from crit, not HP loss" if Tracker.debug?(:verbose)
  end
end

.apply_crit_statuses(creature, event) ⇒ Object

Applies the status effects a critical hit carries.

Deliberately not gated behind :track_ucs. The crit tables only populate roundtime/slowed/silenced/dazed for UCS attacks, but the underlying states are general - silence from Silence (210) or a silencing flare, slow from Slow (506), daze from various maneuvers. Gating the state on the UCS flag would mean a non-UCS character sees silenced? return false for a genuinely silenced creature, which is worse than having no answer at all.

Units differ inside one CritRanks hash: stunned is in ROUNDS, roundtime is already in SECONDS.



2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
# File 'documented/gemstone/combat/processor.rb', line 2292

def apply_crit_statuses(creature, event)
  at = event[:at] || Time.now

  # Direct-hit crits land on the swing's creature (nil for a targetless
  # inbound/self parent - its only creature-bound facts are its flares).
  if creature
    event[:hits].each do |hit|
      crit = hit[:crit] or next

      apply_hit_crit_statuses(creature, crit, event, at, crit_line: hit[:_crit_line])
    end
  end

  # Flare crits land on the FLARE's creature (an AoE flare can strike a
  # different creature than the swing). Flare damage and flare wounds
  # are already applied in persist_event; their crit-derived statuses
  # (stun/roundtime/knockdown/silence/...) were being dropped - a
  # silencing or stunning flare recorded its wound but never its state.
  (event[:flares] || []).each do |flare|
    f_target = flare[:target_info] || event[:target] || {}
    f_creature = f_target[:id] ? Creature[f_target[:id].to_i] : creature
    next unless f_creature

    (flare[:hits] || []).each do |hit|
      crit = hit[:crit] or next

      apply_hit_crit_statuses(f_creature, crit, event, at, flare: flare[:name],
                                                           crit_line: hit[:_crit_line])
    end
  end
end

.apply_hit_crit_statuses(creature, crit, event, at, flare: nil, crit_line: nil) ⇒ Object

Apply one crit's status effects (stun/roundtime/position/silence/...) to a creature. Shared by direct-hit and flare-hit crits so both paths stay identical; flare tags the observer/debug provenance.



2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
# File 'documented/gemstone/combat/processor.rb', line 2327

def apply_hit_crit_statuses(creature, crit, event, at, flare: nil, crit_line: nil)
  if crit[:stunned].to_i > 0
    # The boolean stays owned by <crtrStatus>/messaging; this records
    # the table-derived duration estimate beside it.
    creature.add_status('stunned')
    creature.add_stun_estimate(crit[:stunned], at: at)
    Lich::Common::Events.emit('combat.stun', id: creature.id, name: creature.name,
                          attack: event[:name], flare: flare, rounds: crit[:stunned],
                          seconds: crit[:stunned].to_i * CreatureInstance::STUN_ROUND_SECONDS)
    record_delta(creature) { |d| d[:statuses] << "stunned(#{crit[:stunned]}r)" }
  end

  # roundtime is in seconds already - do not scale it.
  if crit[:roundtime].to_i > 0
    creature.add_status('roundtime', crit[:roundtime].to_i)
    Lich::Common::Events.emit('combat.roundtime', id: creature.id, name: creature.name,
                               attack: event[:name], flare: flare, seconds: crit[:roundtime].to_i)
    record_delta(creature) { |d| d[:statuses] << "roundtime(#{crit[:roundtime].to_i}s)" }
  end

  # Position changes carry better provenance than the messaging
  # equivalents: /It is knocked to the ground!/ has no target
  # capture, while this crit is already bound to a creature id.
  # A recovery message later in this chunk already said the creature
  # is up. Messages apply during the parse and crits during persist,
  # so without this the EARLIER knockdown would overwrite the LATER
  # stand-up and latch the creature prone.
  if (pos = crit[:position]) && !position_recovered?(creature.id, crit_line)
    # Tables report "PRONE"/"KNEELING"/"SITTING"; the status
    # canon (messaging, <crtrStatus>, consumers) is lowercase.
    # add_status canonicalizes too, but the observer payload
    # must match what subscribers compare against.
    status = pos.to_s.downcase
    (POSITION_STATUSES - [status]).each { |s| creature.remove_status(s) }
    creature.add_status(status)
    Lich::Common::Events.emit('combat.status', id: creature.id, name: creature.name,
                            status: status, action: :add)
    record_delta(creature) { |d| d[:statuses] << status }
  end

  %i[silenced slowed dazed sleeping crippled limb_favored].each do |flag|
    next unless crit[flag]

    creature.add_status(flag.to_s)
    Lich::Common::Events.emit('combat.status', id: creature.id, name: creature.name,
                            status: flag.to_s, action: :add)
    record_delta(creature) { |d| d[:statuses] << flag.to_s }
    respond "  +status: #{flag} (from crit#{flare ? ", flare: #{flare}" : ''})" if Tracker.debug?(:verbose)
  end
end

.apply_secondary_wound(creature, secondary, event) ⇒ Object

Registers a crit's secondary wound, when it has one.

Crits that injure two body parts at once carry the second as { :location => ..., :wound_rank => ... } - e.g. "Massive electrical bolt burns a hole through the back and kidneys" wounds back (primary) and nerves (secondary). Populated on 156 of ~2400 table rows and nil on the rest; observed locations are head, nerves, back, abdomen, neck, chest, right leg and "both eyes".



2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
# File 'documented/gemstone/combat/processor.rb', line 2244

def apply_secondary_wound(creature, secondary, event)
  # bare (non-Hash) value with no location is ambiguous - skip
  # rather than guess
  return unless secondary.is_a?(Hash)

  location = secondary[:location] || secondary['location']
  # The tables key this :wound_rank ({ :location => "head",
  # :wound_rank => 3 }); reading :rank made every secondary wound
  # a silent no-op. :rank kept as a fallback for older data.
  rank = (secondary[:wound_rank] || secondary['wound_rank'] ||
          secondary[:rank] || secondary['rank']).to_i
  return unless rank > 0

  # "both eyes" is a real table location with no single body part -
  # it is two wounds, one per eye.
  parts = if location.to_s.downcase.gsub(/[^a-z]/, '') == 'botheyes'
            %w[leftEye rightEye]
          else
            [map_critranks_to_body_part(location)].compact
          end
  if parts.empty?
    record_delta(creature) { |d| d[:wounds] << "?#{location}:#{rank}" }
    respond "  !unknown secondary wound location: #{location}" if Tracker.debug?(:verbose)
    return
  end

  parts.each do |part|
    creature.add_injury(part, rank)
    Lich::Common::Events.emit('combat.wound', id: creature.id, name: creature.name,
                           attack: event[:name], location: location,
                           body_part: part, rank: rank, secondary: true)
    record_delta(creature) { |d| d[:wounds] << "#{part}:#{rank}*" }
    respond "  +secondary wound: #{part} rank #{rank}" if Tracker.debug?(:verbose)
  end
end

.apply_status_to_target(status, target_name_or_id, target_id = nil, action = :add, flare_seq: nil, event: nil, line: nil) ⇒ Object

Apply status effect directly to a creature (outside combat events) flare_seq / event: which flare (1-based position) of which parse event the status rode on; process() turns the event ref into an :attack_uid for the recorder. line: where the status message sat in the chunk, so a later knockdown crit can outrank an earlier stand-up.



2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
# File 'documented/gemstone/combat/processor.rb', line 2424

def apply_status_to_target(status, target_name_or_id, target_id = nil, action = :add, flare_seq: nil, event: nil, line: nil)
  # Handle both name lookup and direct ID
  if target_id
    creature = Creature[target_id.to_i]
  else
    # Try to find creature by name - this is less reliable
    # but might work for some cases
    return unless defined?(Creature)
    creatures = Creature.all.select { |c| c.name&.downcase&.include?(target_name_or_id.downcase) }
    creature = creatures.first if creatures.size == 1
  end

  if creature
    if action == :remove
      # Position is one mutually-exclusive channel. The stand-up
      # messagings are shared between prone and sitting, and parse
      # returns the FIRST match (:prone, defined earlier) - so
      # removing only the reported status left 'sitting' (and
      # kneeling, which has no removal def at all) latched forever.
      # A creature that stood up is in no floor position, whichever
      # one the pattern happened to name.
      if POSITION_STATUSES.include?(status.to_s)
        POSITION_STATUSES.each { |s| creature.remove_status(s) }
        # Message statuses apply HERE, during the parse; crit-derived
        # statuses apply later, in persist_event. A creature knocked
        # down by a crit and standing up afterwards in the same chunk
        # would be re-proned by that later pass, because the crit is
        # earlier in the chunk but applied last. Note the recovery so
        # the crit pass leaves it standing (see apply_hit_crit_statuses).
        # The line is what lets a LATER knockdown crit still win.
        note_position_recovery(creature.id, line)
      else
        creature.remove_status(status)
      end
      respond "[Combat] Removed status #{status} from #{creature.name} (#{creature.id})" if Tracker.debug?(:verbose)
    else
      # ...and adding one displaces the others: knocked prone while
      # sitting is prone, not both.
      if POSITION_STATUSES.include?(status.to_s)
        (POSITION_STATUSES - [status.to_s]).each { |s| creature.remove_status(s) }
        # A later knockdown MESSAGE outranks an earlier recovery, so
        # the crit pass is free to act again (stood up, then knocked
        # down again inside one chunk).
        clear_position_recovery(creature.id)
      end
      creature.add_status(status)
      respond "[Combat] Applied status #{status} to #{creature.name} (#{creature.id})" if Tracker.debug?(:verbose)
    end
    payload = { id: creature.id, name: creature.name,
                status: status, action: action == :remove ? :remove : :add }
    payload[:flare_seq] = flare_seq if flare_seq
    payload[:_event] = event if event
    emit_fact(:status, payload)
  else
    respond "[Combat] Could not find creature for status: #{status} -> #{target_name_or_id}" if Tracker.debug?(:verbose)
  end
end

.apply_ucs_to_target(ucs_result, current_target = nil) ⇒ Object

Apply UCS event to a creature



2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
# File 'documented/gemstone/combat/processor.rb', line 2379

def apply_ucs_to_target(ucs_result, current_target = nil)
  target_id = ucs_result[:target_id]

  # For tierup events, use current combat target if no ID in the event
  target_id ||= current_target[:id] if current_target && ucs_result[:type] == :tierup

  return unless target_id

  creature = Creature[target_id.to_i]
  return unless creature

  case ucs_result[:type]
  when :position
    creature.set_ucs_position(ucs_result[:value])
    respond "[Combat] Set UCS position #{ucs_result[:value]} on #{creature.name} (#{creature.id})" if Tracker.debug?(:verbose)

  when :position_inbound
    # Per-swing metadata (the creature's tier against us) - no
    # creature state to update; it exists for observers/recorder.
    respond "[Combat] #{creature.name} (#{creature.id}) has #{ucs_result[:value]} positioning against us" if Tracker.debug?(:verbose)

  when :tierup
    creature.set_ucs_tierup(ucs_result[:value])
    respond "[Combat] Set UCS tierup #{ucs_result[:value]} on #{creature.name} (#{creature.id})" if Tracker.debug?(:verbose)

  when :smite_on
    creature.smite!
    respond "[Combat] Applied smite to #{creature.name} (#{creature.id})" if Tracker.debug?(:verbose)

  when :smite_off
    creature.clear_smote
    respond "[Combat] Cleared smite from #{creature.name} (#{creature.id})" if Tracker.debug?(:verbose)
  end
  emit_fact(:ucs, id: creature.id, name: creature.name,
                  kind: ucs_result[:type], value: ucs_result[:value],
                  tier: ucs_result[:tier])
rescue => e
  respond "[Combat] Error applying UCS: #{e.message}" if Tracker.debug?(:verbose)
end

.attack_events_requested? ⇒ Boolean

Include attack details for persistent recording or transient observers.

Returns:

  • (Boolean) —

    whether attack events are currently requested



104
105
106
# File 'documented/gemstone/combat/processor.rb', line 104

def attack_events_requested?
  Tracker.settings[:emit_attacks] || Lich::Common::Events.any_for?('combat.attack')
end

.bare_cast?(event) ⇒ Boolean

A fact-less bare gesture: attack-born :cast with no hits, outcomes or statuses yet. Flares that themselves carry no hit or outcome (a mirror image echoing the gesture - "Nothing happens.") do not make it a real cast; they travel with it to the superseding event. The WRAPPER the spell-specific def supersedes (see the attack branch), and the shape held across a chunk boundary.

Returns:

  • (Boolean)


310
311
312
313
314
315
# File 'documented/gemstone/combat/processor.rb', line 310

def bare_cast?(event)
  event && event[:_attack_born] && event[:name] == :cast &&
    event[:hits].empty? && event[:outcomes].empty? &&
    event[:flares].all? { |f| f[:hits].empty? && f[:outcomes].empty? } &&
    event[:statuses].empty? && !event[:_had_status]
end

.clear_position_recovery(id) ⇒ Object

A later knockdown MESSAGE outranks the recovery: the crit pass may act again.

Parameters:



2064
2065
2066
2067
2068
# File 'documented/gemstone/combat/processor.rb', line 2064

def clear_position_recovery(id)
  return unless id

  @position_recovered&.delete(id.to_i)
end

.combined_observation_source(first, later) ⇒ Object

Combining cross-chunk facts must retain their oldest receipt and reject missing or changed bindings, never stamp older facts anew.



126
127
128
129
130
# File 'documented/gemstone/combat/processor.rb', line 126

def combined_observation_source(first, later)
  return nil unless first && later && %i[connection_id game character room_epoch].all? { |key| first[key] == later[key] }

  first[:received_at] <= later[:received_at] ? first : later
end

.creature_dead?(creature) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns true when a creature is marked dead in the registry.

Checks both the legacy :crtrStatus dead classification flag and the has_status?('dead') boolean, returning false on any error (creature methods may not respond to the check, or the creature may have been garbage-collected).

Parameters:

  • creature (Object) —

    a creature instance (typically a CreatureInstance)

Returns:

  • (Boolean) —

    true if the creature is dead; false otherwise or on error

See Also:

  • #sweep_death_watch


2146
2147
2148
2149
2150
2151
# File 'documented/gemstone/combat/processor.rb', line 2146

def creature_dead?(creature)
  (creature.respond_to?(:crtr_flag?) && creature.crtr_flag?(:dead)) ||
    (creature.respond_to?(:has_status?) && creature.has_status?('dead'))
rescue StandardError
  false
end

.emit_debug_summary(event) ⇒ Object

One line per creature this event touched: what changed, nothing else.

Deliberately the delta rather than the creature's running totals - the point is to diff a single attack against the game text that produced it. Cumulative state is a click away via the creature link.



2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
# File 'documented/gemstone/combat/processor.rb', line 2170

def emit_debug_summary(event)
  return unless @delta && !@delta.empty?

  @delta.each_value do |d|
    creature = d[:creature] or next

    parts = ["#{d[:damage]} dmg"]
    parts << "wounds: #{d[:wounds].join(', ')}" unless d[:wounds].empty?
    parts << "statuses: #{d[:statuses].uniq.join(', ')}" unless d[:statuses].empty?

    link = Lich::Messaging.make_cmd_link("#{creature.name} (#{creature.id})",
                                         ";e echo Creature[#{creature.id}]")
    _respond "[Combat] #{link} | #{event[:name]} | #{parts.join(' | ')}"
  end
ensure
  @delta = nil
end

.emit_fact(type, payload) ⇒ Object

-- parse-phase fact emits --------------------------------------------

Message statuses ("You blinded X!"), UCS facts and spell losses are recognised while a chunk PARSES, but the chunk's :attack emits only happen afterwards in persist_event. Emitting them immediately put every such fact in front of the attack it belongs to, so a recorder keying on "the attack currently open" filed it under the PREVIOUS attack (real-feed 2026-09-07: every blind stamped 1-3s before its attack). Inside process() they queue and flush after the attacks; a bare parse_events (tests, tools) still emits at once.



213
214
215
216
217
218
219
220
# File 'documented/gemstone/combat/processor.rb', line 213

def emit_fact(type, payload)
  if @deferred_emits
    @deferred_emits << [type, payload]
  else
    payload.delete(:_event)
    Lich::Common::Events.emit("combat.#{type}", payload)
  end
end

.event_savable?(event, include_attack_events: attack_events_requested?) ) ⇒ Boolean

Whether an event survives to persist_event. Registry-wise only events with data matter, but a recorder subscribed to :attack needs more: a clean miss IS data, and an ATTACK-BORN event with nothing attached still records "this attack was initiated" (a wand wave whose crystal roll we cannot parse yet). What must NOT emit is a fact-less SWITCH ARTIFACT: guard-intercept and UCS-positioning lines spawn empty inherited events that used to emit as phantom attacks (real-feed replay, logs/examples/fury.txt).

Returns:

  • (Boolean)


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
# File 'documented/gemstone/combat/processor.rb', line 335

def event_savable?(event, include_attack_events: attack_events_requested?)
  return false unless event

  unless event[:target][:id]
    # Inbound (creature -> us) and foreign-target (creature -> a
    # third party) events carry no creature-target id BY
    # CONSTRUCTION - the subject is the attacker. They used to be
    # dropped here wholesale, which was correct for the registry
    # (nothing to apply damage to) but starved the recorder: the
    # replay corpus showed the entire ambush family (and every
    # other inbound family) never emitting (2026-09-05, 237/1000
    # blobs missing their attack). Save them when attack-born or
    # carrying facts; persist_event still returns early on the
    # missing target id, so nothing is ever applied to a creature
    # from these - they exist for :attack subscribers only.
    # ...and the same for OUR OWN targetless events (assault
    # middle rounds arriving in chunks that never name the
    # target - barrage re-nocks lost 101-damage hits): an
    # attack-born event is a fact regardless of whether the
    # chunk let us bind a target. Switch artifacts remain
    # excluded - they are never _attack_born.
    return false unless event[:inbound] || event[:foreign_target] ||
                        event[:_attack_born]

    return include_attack_events &&
           (event[:_attack_born] || !event[:outcomes].empty? ||
            !event[:resolutions].empty? || !event[:hits].empty?)
  end

  event_worth_saving?(event) ||
    (include_attack_events &&
     (event[:_attack_born] ||
      !event[:outcomes].empty? || !event[:resolutions].empty? ||
      !event[:flares].empty? || event[:_had_status]))
end

.event_worth_saving?(event) ⇒ Boolean

An event is worth persisting only if it has a target to apply data to and any data to apply. Single predicate so every save site agrees (previously three sites used three different criteria).

Returns:

  • (Boolean)


320
321
322
323
324
325
# File 'documented/gemstone/combat/processor.rb', line 320

def event_worth_saving?(event)
  return false unless event && event[:target][:id]

  !event[:hits].empty? || !event[:statuses].empty? ||
    event[:flares].any? { |f| !f[:hits].empty? }
end

.flare_contradicts_weapon?(flare, event) ⇒ Boolean

Whether a flare positively belongs to a DIFFERENT attack than the one currently open.

Only a weapon name can prove that, and only when the open event already holds a flare from another weapon. That is the back-to-back signature: two weapons' flares arriving with no attack line between them (dual-wield rounds where the game printed the rolls but not the swings). Without this the second flare would silently join the first flare's attack and its damage would be credited to the wrong weapon.

A weapon MISMATCH against the swing text is deliberately NOT sufficient: bow flares name the bow while the swing names the arrow, and a second flare on one swing legitimately names the other held weapon. Both are the same attack.

Returns:

  • (Boolean)


395
396
397
398
399
400
401
402
403
# File 'documented/gemstone/combat/processor.rb', line 395

def flare_contradicts_weapon?(flare, event)
  fw = flare[:weapon] && flare[:weapon][:name]
  return false unless fw

  event[:flares].any? do |prior|
    pw = prior[:weapon] && prior[:weapon][:name]
    pw && pw != fw
  end
end

.flare_matches_weapon?(flare, weapon_text) ⇒ Boolean

A flare's weapon (linked on its announce line) against a swing's weapon text: "slim short sword" is a substring of "kelyn-edged slim short sword". Flares without weapon info match any swing.

Returns:

  • (Boolean)


374
375
376
377
378
# File 'documented/gemstone/combat/processor.rb', line 374

def flare_matches_weapon?(flare, weapon_text)
  return true unless flare[:weapon] && weapon_text

  weapon_text.include?(flare[:weapon][:name])
end

.flush_deferred_emits ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Emits all deferred fact events (statuses, UCS, spell losses) that were queued during chunk parse.

Parse-phase fact emissions (from #emit_fact) are held during #process so they emit AFTER the chunk's :attack events (not before), correcting the timing window for recorders keying on "the attack currently open". A bare parse_events call (tests, tools) still emits at once.



232
233
234
235
236
237
238
239
# File 'documented/gemstone/combat/processor.rb', line 232

def flush_deferred_emits
  pending = @deferred_emits
  @deferred_emits = nil
  pending&.each do |type, payload|
    payload.delete(:_event) # unresolved (no events emitted this chunk)
    Lich::Common::Events.emit("combat.#{type}", payload)
  end
end

.map_critranks_to_body_part(location) ⇒ Object

Map CritRanks location strings to creature body part constants



2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
# File 'documented/gemstone/combat/processor.rb', line 2483

def map_critranks_to_body_part(location)
  return nil unless location

  case location.to_s.downcase.gsub(/[^a-z]/, '')
  when 'leftarm', 'larm' then 'leftArm'
  when 'rightarm', 'rarm' then 'rightArm'
  when 'leftleg', 'lleg' then 'leftLeg'
  when 'rightleg', 'rleg' then 'rightLeg'
  when 'lefthand', 'lhand' then 'leftHand'
  when 'righthand', 'rhand' then 'rightHand'
  when 'leftfoot', 'lfoot' then 'leftFoot'
  when 'rightfoot', 'rfoot' then 'rightFoot'
  when 'lefteye', 'leye' then 'leftEye'
  when 'righteye', 'reye' then 'rightEye'
  when 'head' then 'head'
  when 'neck' then 'neck'
  when 'chest' then 'chest'
  when 'abdomen', 'abs' then 'abdomen'
  when 'back' then 'back'
  when 'nerves' then 'nerves'
  else
    # Try the location as-is in case it's already correct
    location.to_s if CreatureInstance::BODY_PARTS.include?(location.to_s)
  end
end

.note_position_recovery(id, line) ⇒ Object

The recovery records WHERE in the chunk the stand-up was read, not merely that one happened. A bare flag cannot answer the question the crit pass actually asks - "did the creature stand up after THIS crit?" - so a second, genuine knockdown crit landing later in the same chunk was suppressed by an earlier stand-up.

Parameters:

  • id (Integer, String, nil) —

    the creature a message stood up

  • line (Integer, nil) —

    index of the stand-up line in this chunk



2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
# File 'documented/gemstone/combat/processor.rb', line 2048

def note_position_recovery(id, line)
  return unless id

  @position_recovered ||= {}
  # A caller that cannot say WHERE the recovery was read still asserts
  # that one happened. Infinity keeps that meaning "after every crit",
  # the safe reading: never re-prone a creature the game stood up.
  at = line.nil? ? Float::INFINITY : line
  # Keep the LATEST recovery: it is the one a crit must beat.
  prev = @position_recovered[id.to_i]
  @position_recovered[id.to_i] = at if prev.nil? || at >= prev
end

.observation_source(value) ⇒ Hash?

Scalar allowlist copied before any event retains it. Metadata is not invented for legacy/replay callers which supply no ingestion source.

Parameters:

  • value (Object) —

    proposed ingestion metadata

Returns:

  • (Hash, nil) —

    frozen validated context, or nil when incomplete



112
113
114
115
116
117
118
119
120
121
122
# File 'documented/gemstone/combat/processor.rb', line 112

def observation_source(value)
  return nil unless value.is_a?(Hash)
  integers = %i[connection_id room_epoch sequence]
  return nil unless integers.all? { |key| value[key].is_a?(Integer) && value[key] >= 0 } && value[:connection_id].positive? && value[:sequence].positive?
  return nil unless %i[game character].all? { |key| value[key].is_a?(String) && !value[key].empty? }
  at = value[:received_at]
  return nil unless at.is_a?(Numeric) && at.real? && at.finite? && at >= 0

  value.slice(*integers, :game, :character, :received_at)
       .transform_values { |item| item.is_a?(String) ? item.dup.freeze : item }.freeze
end

.parse_events(lines, source: nil, include_attack_events: nil) ⇒ Array<Hash>

Parse combat lines into events without inventing ingestion provenance.

Parameters:

  • lines (Array<String>) —

    game lines for one parser chunk

  • source (Hash, nil) (defaults to: nil) —

    optional ingestion context to validate and copy

  • include_attack_events (Boolean, nil) (defaults to: nil) —

    fixed transient attack demand for this parse, or nil to snapshot current demand

Returns:

  • (Array<Hash>) —

    parsed attack and related outcome events



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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
# File 'documented/gemstone/combat/processor.rb', line 411

def parse_events(lines, source: nil, include_attack_events: nil)
  source = observation_source(source)
  include_attack_events = attack_events_requested? if include_attack_events.nil?
  # Position recoveries are per chunk: a stand-up here must not
  # suppress a knockdown crit in the NEXT chunk.
  @position_recovered = nil
  events = []
  # Identity-guarded push: an event RESUMED after an inbound
  # interruption (see interrupted_own) was already saved once.
  save_event = lambda do |ev|
    next if events.any? { |e| e.equal?(ev) }

    events << ev
    # A cast this swing's Holy Weapon proc released that PRINTED
    # BEFORE the swing (proc -> spell -> swing) was pulled out of the
    # emit order when the swing adopted it: the recorder resolves
    # lineage at insert time and a parent must emit first, so the
    # child follows its parent here.
    Array(ev.delete(:_released_children)).each { |c| events << c unless events.any? { |e| e.equal?(c) } }
  end
  # Our own event that an inbound attack cut into mid-swing. A
  # creature's reactive cast (cloak of shadows: our arrow lands, its
  # tendril lashes back, CS/TD, "Warded off!") prints BETWEEN our hit
  # and our bow's flares; without this the phosphorescence and its
  # damage/crit attached to the creature's cast as damage to US (hunt
  # log 2026-09-07 23:18, flayed gigas disciple). Our next own flare
  # line resumes the interrupted event.
  interrupted_own = nil
  # The own swing a flare-released spell cut into (see
  # SPELL_RELEASING_FLARES): stashed at the cast's open so the fresh
  # event can be parented to it, then cleared.
  released_parent = nil
  # The other ordering: the release line prints FIRST (pre-flare,
  # no swing open yet), the spell casts, THEN the swing line prints.
  # The cast is remembered here and parented to the swing that
  # claims the pending release flare (see the pre-flare claim).
  pending_release_cast = nil
  # Every cast deferred behind its swing (see save_event); flushed
  # at the end in case the swing itself never got saved.
  deferred_casts = []
  # Attacker of the last inbound event saved this blob. A creature's
  # warding spell that lands prints its effect as an attackerless
  # spell-result line right after the cast's "Warding failed!"
  # (disciple's wither: "A nebulous haze shimmers into view around
  # you", hunt log 2026-09-07 23:50) - the effect is that caster's.
  last_inbound_attacker = nil
  # the event a SINGLE_HIT_ATTACKS side effect cut in front of (see decl)
  single_hit_parent = nil
  # Weapon named by a "You nock <ammo> in your <bow>." line this chunk,
  # cleared by the swing that follows. A pre-emptive evade ("bounds
  # to safety as you move to attack it") prints INSTEAD of the fire
  # line, so the only clue that the swing was a fire is the nock
  # (hunt log 2026-09-09 16:00: the shroud then rode an "unknown").
  nocked = nil
  current_event = nil
  parse_state = :seeking_attack
  current_target = nil

  # Flare state (all chunk-local; see defs/flares.rb):
  #   flare_ctx     - the flare whose damage/crit lines are arriving
  #   pending_flares - flares seen before the swing they belong to
  #                    (pre-flares); claimed by weapon on the next swing
  #   spawn_pending / active_spawn - a spawn-class flare (Blink) casts
  #                    an imbedded spell as a separate attack; its
  #                    sequence brackets mark those events as children
  flare_ctx = nil
  pending_flares = []
  spawn_pending = nil
  active_spawn = nil
  # Echo flares seen in this blob whose spawned swing has not arrived
  # yet, in announce order: [{ flare:, owner: event }]. Consumed FIFO
  # by the bare own swings that follow (see echo lineage below).
  pending_echoes = []
  # Spawn lineage within THIS blob. The whole attack (initiating shot,
  # its flares, any spawned echo attacks and their own flares) resolves
  # inside one prompt-bounded chunk before roundtime - so the blob is a
  # closed spawn tree with a single root. spawn_root holds the current
  # tree's root event (our own initiating attack); every later OWN
  # attack in the blob that is spawn-born (a mirror/afterimage echo, or
  # a bracketed blink cast) points its :root at it. Foreign/inbound/
  # orphan events are their own root and reset it. Only lineage we can
  # assert is stamped: blink via its bracket (:parent + confidence
  # :bracket); ambiguous mirror/afterimage immediate-parent is left
  # nil (root still known) rather than guessed. See recorder root/
  # parent_attack_id.
  spawn_root = nil
  # The sequence bracket (Definitions::Sequences) currently open in
  # this blob, when its rounds are events of the same name (volley).
  active_sequence = nil
  # Rolls that could not claim a virgin sink. An array: several can
  # stack up (volley's per-arrow SMRs, trailing rider maneuvers) and
  # the old single slot silently overwrote all but the last.
  pending_resolutions = []
  # Armed by an ambush prefix line; claimed by the next attack (or
  # by an outcome when the ambush is wholly negated and no attack
  # line is ever printed).
  pending_ambush = nil
  # Armed by a guardian redirect prefix ("<shield-maiden> throws
  # herself between you and the <mastodon> to intercept your
  # attack!"); claimed by the next own attack, whose target IS the
  # guardian. Records that the DS rolled against was the
  # guardian's, not the intended victim's (see REDIRECT_PREFIXES).
  pending_redirect = nil
  # Dispel-family flares seen in THIS chunk, by stripped target id
  # (:any when the flare line names no target). Used to attribute
  # spell_loss cause - a wear-off riding a dispel strip means
  # something different from natural expiry or death cleanup.
  chunk_dispels = []
  # Creatures THIS chunk killed (fatal crit, coup kill), by exist id.
  # The registry learns of the death only when the chunk persists,
  # but the wear-off lines that follow a death line are already in
  # this chunk - without this a skald's 303 dropping on her death
  # was a cause-less loss (owner 2026-09-09: "spells falling off
  # during death versus being removed by a dispel").
  chunk_deaths = []
  # Ownership of DoT/effect casts we saw in this blob, keyed PER VICTIM
  # as [spell_name, target_key] (target_key = the victim's exist id, or
  # its name when unresolved). :self when our 2p cast line fired ("You
  # exhale a virulent green mist toward X..."), so X's trailing ticks
  # are ours; a player name when a foreign cast opener fired. A tick
  # whose (spell, victim) is NOT in here is unowned - a fact about the
  # creature, not a claim on our ledger (see UNOWNED_TICK_ATTACKS).
  #
  # Per-victim is load-bearing: keying by spell name alone let our
  # pestilence cast on creature A mark a DIFFERENT player's pestilence
  # tick on creature B as ours, in the same chunk (overlapping same-
  # family AoE DoTs are normal in group hunts). The victim dimension
  # keeps each cast's ownership bound to the creature it targeted.
  cast_owner = {}
  # [spell_name, victim] key: id when we have it, else the printed name.
  cast_owner_key = lambda do |name, tgt|
    [name, (tgt && (tgt[:id] || tgt[:name]))]
  end
  # Foreign-attacker latch: a nearby player's AoE (pulverize, and
  # other openers that name the actor but whose per-target swing
  # lines do NOT) fans out into actor-less swing/effect lines. Their
  # opener sets this to the player's name; while set, actor-less
  # attack events inherit foreign_caster so the whole chain stays off
  # our ledger (real-feed, GSIV-Nisugi 2026-09-06: Heavenscent's
  # pulverize dumped ~825 swing damage into our web event). Cleared
  # the instant WE act (a 2p "You ..." attack reclaims ownership).
  # Chunk-local, so a prompt boundary clears it for free.
  foreign_latch = nil
  # Facts with NO recognized initiation anywhere in the chunk
  # (bespoke initiations we have no def for - the burnt-arms
  # snatch, the wraith-shark charge). The def layer sees their
  # damage and outcomes; without this sink the state machine
  # silently dropped them (replay 2026-09-05, grasp_arms blobs).
  # Wrapped at end-of-chunk as a targetless :unknown orphan -
  # persist_event never applies it (no target id), recorders see
  # the facts.
  orphan_hits = []
  orphan_outcomes = []

  # A bare gesture held over from the previous chunk (see the hold at
  # the end of this method). Re-open it as the current event so the
  # spell-result line that begins THIS chunk can supersede it exactly
  # as it would in-blob. _held marks it so it is emitted, not re-held,
  # if nothing supersedes it here; _line is cleared so the switch-
  # artifact check cannot mistake it for an event born on this chunk's
  # first line.
  if (held = @held_cast)
    @held_cast = nil
    held[:source] = combined_observation_source(held[:source], source)
    held[:_held] = true
    held[:_line] = nil
    current_event = held
    current_target = held[:target] if held[:target] && held[:target][:id]
    parse_state = :seeking_damage
  end
  # Pre-flares held over from the previous chunk (see the end of this
  # method): a bow's dispel fires on the NOCK, resolves (SMR, damage,
  # crit) and the chunk ends at the prompt before "You fire" prints.
  # Re-seed them so this chunk's swing claims them like any pre-flare
  # (hunt log 2026-09-07: eight dispels recorded as their own
  # "dispel" attacks instead of riding the shot).
  if (held_flares = @held_pre_flares)
    @held_pre_flares = nil
    held_flares.each do |f|
      f[:_held] = true
      f[:source] = combined_observation_source(f[:source], source)
    end
    pending_flares.concat(held_flares)
  end

  lines.each_with_index do |line, index|
    next if line.strip.empty?
    # Room-window components (objs/players) are full of bold creature
    # links; feeding them to the target-switcher spawns phantom events
    # for bystander creatures that were never attacked.
    next if line.include?('<component id=')
    # Narration that links creatures but is no combat fact: a rider
    # leaping clear of its toppling mount, bystanders growing wary
    # after a kill, our own target-set echo. Fed to the target
    # switcher these split the open attack into phantom per-creature
    # events (real-feed 2026-09-07: one briar lash recorded as three
    # tangleweed rows because the rider dismounted mid-lash).
    next if NARRATION_PATTERN.match?(line)

    # Extract creature target once per line; reused by the status
    # handler and the target-switch logic below.
    #
    # On an INBOUND line (a creature attacking US) the only creature
    # link is the ATTACKER. Feeding it to the switcher would retarget
    # the event onto that creature, so the damage and crits it dealt
    # to us get applied to it instead - the same misattribution the
    # parser fallback caused, arriving by a second route.
    # ONE attack scan per line, shared by the two consumers below.
    #
    # inbound_attack? used to re-run the whole ATTACK_LOOKUP loop that
    # the attack branch runs again 250 lines down, and threw away
    # everything but a boolean. That duplicate scan measured 3.2s of a
    # 11.4s parse (98,800 lines) - the two calls together were 56% of
    # total parse time, half of it pure repetition. parse_attack
    # already reports :inbound, so hoisting it serves both.
    line_attack = Parser.parse_attack(line)
    inbound_line = line_attack ? line_attack[:inbound] : false
    line_target = inbound_line ? nil : Parser.extract_target_from_line(line)
    # Guardian redirect announce (see pending_redirect decl). Hoisted
    # here because the line BOLDS THE GUARDIAN, and the target
    # switcher below would otherwise read that link as a switch off
    # the open attack - saving it fact-less and spawning an inherited
    # phantom on the guardian (the UAC shape then re-switched back on
    # the positioning line: three events for one kick).
    line_redirect = Definitions::Attacks.redirect_prefix(line)
    # The id a status applied to on THIS line: after the switch/attack
    # handling below, the event holding that target is flagged - a
    # status IS a fact, and a per-target line whose only payload is
    # the status (pindown's immobilize) must keep its event alive
    # through event_savable? (statuses live on the creature, not the
    # event, so the fields alone can't show it).
    line_status_id = nil
    # An outcome printed ON an initiation line (tangleweed's "lashes
    # out at X, but is unable to grasp her") belongs to the event that
    # line opens below, not to whatever event is open now.
    same_line_outcome = nil

    # Always check for status effects on every line (even outside combat)
    if Tracker.settings[:track_statuses]
      if (status_result = Parser.parse_status(line))
        # Which of this event's flares the status rides on, as a
        # 1-based position in event[:flares] (the recorder maps it
        # to the flare row): the active damaging flare when it names
        # this creature (or names nobody and the creature is the
        # swing target), else the latest flare that named it - a
        # glowbark bloom's "You blinded <bloom creature>!" follows
        # the bloom. Without this every blind sat on the swing row
        # (owner 2026-09-07: "tagged to the root attack instead of
        # the bloom flare").
        status_flare_seq = lambda do |cid|
          next nil unless current_event && cid
          flares = current_event[:flares] || []
          # A line that is itself a flare AND a status (nature's
          # decay's "earthy, sweet aroma ... grows more pervasive")
          # rides the flare it announces - which the flare branch
          # below has not appended yet, so it is the NEXT position.
          # Without this the status sat on the flare before it
          # (breeze, hunt log 2026-09-07 23:50). Not when the flare
          # is about to resume an interrupted swing (see
          # interrupted_own): the positions belong to another event.
          if (lf = Parser.parse_flare(line)) && !(current_event[:inbound] && interrupted_own)
            lf_id = lf[:target].to_s[/exist="(-?\d+)"/, 1]&.to_i
            if lf_id == cid || (lf_id.nil? && current_event[:target] && current_event[:target][:id] == cid)
              next flares.size + 1
            end
          end
          f = if flare_ctx && flare_ctx[:target_info]
                flare_ctx if flare_ctx[:target_info][:id] == cid
              elsif flare_ctx && current_event[:target] && current_event[:target][:id] == cid
                flare_ctx
              end
          # Only flares that printed AFTER the swing line: a status
          # right after the swing's crit ("Strike pierces forearm!
          # The mutant is stunned!") is the swing's, even when a
          # pre-flare (dispel, ensorcell) named the creature first
          # (hunt log 2026-09-07 23:51).
          f ||= flares.reverse.find { |x| !x[:_pre] && x[:target_info] && x[:target_info][:id] == cid }
          f && (i = flares.index(f)) ? i + 1 : nil
        end
        # The event a status rides on (the recorder's attack_uid) -
        # ONLY when that event touched the subject: it is the
        # target, the attacker of an inbound swing, a flare named
        # it, or the flare-and-status line about to be appended
        # did (seq). An ambient line sharing the chunk ("A troll
        # shakes off the stun!" while we shoot an orc) belongs to
        # no event and stays an independent observation - the
        # recorder must not be told otherwise (review 2026-09-10).
        status_event_for = lambda do |cid, seq|
          next nil unless current_event && cid
          next current_event if seq
          ids = [current_event[:target] && current_event[:target][:id],
                 current_event[:attacker].is_a?(Hash) ? current_event[:attacker][:id] : nil]
          ids.concat((current_event[:flares] || []).map { |x| x[:target_info] && x[:target_info][:id] })
          ids.compact.include?(cid) ? current_event : nil
        end
        if line_target && line_target[:id]
          # Use ID-based lookup - this is most reliable
          line_status_id = line_target[:id]
          if status_result.is_a?(Hash)
            seq = status_flare_seq.call(line_target[:id])
            apply_status_to_target(status_result[:status], line_target[:name], line_target[:id], status_result[:action],
                                   flare_seq: seq, event: status_event_for.call(line_target[:id], seq), line: index)
          else
            # Legacy format - status_result is just the status symbol
            apply_status_to_target(status_result, line_target[:name], line_target[:id], :add, line: index)
          end
        elsif status_result.is_a?(Hash) && status_result[:target]
          # Fallback to name-based lookup only if no ID available
          apply_status_to_target(status_result[:status], status_result[:target], nil, status_result[:action],
                                 line: index)
        elsif status_result.is_a?(Hash) && !line.match?(/\A\s*Your?\b/) &&
              (subject = (current_target && current_target[:id] ? current_target : nil) ||
                         (flare_ctx && flare_ctx[:target_info]))
          # Pronoun status lines ("It is knocked to the ground!")
          # carry no link and no name capture - they describe the
          # creature we are fighting, so bind them to the current
          # target. During an INBOUND event there is no current
          # target, but an active flare's own target still binds
          # (shield-spike knockdown: our spike jabs the attacker
          # and ITS pronoun knockdown follows - replay 2026-09-05).
          # 2p lines ("You are stunned!") describe US, never
          # the creature - the Your?/You guard keeps them out.
          line_status_id = subject[:id]
          seq = status_flare_seq.call(subject[:id])
          apply_status_to_target(status_result[:status], subject[:name],
                                 subject[:id], status_result[:action],
                                 flare_seq: seq, event: status_event_for.call(subject[:id], seq), line: index)
        elsif status_result.is_a?(Hash) && line.match?(/\A\s*Your?\b/)
          # 2p: the status is OURS ("You are stunned!"). Never a
          # creature application - but it IS a fact (inbound
          # attacks stun US), so emit it for recorders with the
          # :self subject instead of dropping it (replay
          # 2026-09-05: every 2p status was invisible).
          emit_fact(:status, id: nil, name: 'self',
                             status: status_result[:status],
                             action: status_result[:action])
        end
        respond "[Combat] Found status effect: #{status_result}" if Tracker.debug?(:verbose)
      end

      # Spell wear-off lines (third-person, pinned spells only -
      # defs/spell_losses.rb). Observer feed, not creature state:
      # the loss is a fact about a spell, not a status, and the
      # subject may be a player in view rather than a creature.
      #
      # cause distinguishes the three ways a spell leaves (owner
      # ruling 2026-09-04): :dispel when a dispel-family flare
      # struck this chunk (untargeted flares count for any
      # subject), :death when the subject creature is already
      # known dead (death cleanup strips the whole stack - not a
      # meaningful expiry), nil when neither is visible (natural
      # expiry, or cause outside this chunk).
      if (loss = Parser.parse_spell_loss(line))
        cause = nil
        if chunk_dispels.include?(loss[:id]) || chunk_dispels.include?(:any)
          cause = :dispel
        elsif chunk_deaths.include?(loss[:id]) ||
              (loss[:id] && defined?(Creature) && (c = Creature[loss[:id]]) &&
               (c.dead? || (c.respond_to?(:crtr_flag?) && c.crtr_flag?(:dead))))
          cause = :death
        end
        emit_fact(:spell_loss, id: loss[:id], name: loss[:name],
                               spell: loss[:spell], spell_name: loss[:spell_name],
                               cause: cause)
        respond "[Combat] Spell loss: #{loss[:spell]} #{loss[:spell_name]} off #{loss[:name]}#{cause ? " (#{cause})" : ''}" if Tracker.debug?(:verbose)
      end
    end

    # Always check for UCS events on every line
    if Tracker.settings[:track_ucs]
      if (ucs_result = Parser.parse_ucs(line))
        apply_ucs_to_target(ucs_result, current_target)
        respond "[Combat] Found UCS event: #{ucs_result}" if Tracker.debug?(:verbose)
      end
    end

    # Flare announce lines. A flare attaches to the current event when
    # its weapon matches the swing's (post-flare); otherwise it is held
    # for the next matching swing (pre-flare, e.g. dispel gloves that
    # resolve before the attack). Position is ground truth for timing.
    if (flare = Parser.parse_flare(line))
      flare[:source] = source
      flare[:hits] = []
      flare[:outcomes] = []
      flare[:resolutions] = []
      flare[:target_info] = line_target if line_target
      # arm spell_loss cause attribution for the rest of the chunk
      if %i[dispel sigil_dispel dispel_flux sigil_bane].include?(flare[:name])
        chunk_dispels << (line_target ? line_target[:id] : :any)
      end
      # Some flare announce lines carry damage INLINE ("the miasma
      # around X flares causing 58 points of damage!") - the same
      # shape as inline attack damage (replay 2026-09-05)
      if (inline = Parser.parse_damage(line))
        flare[:hits] << { damage: inline, crit: nil, line: index }
        respond "[Combat] Found inline flare damage: #{inline}" if Tracker.debug?(:verbose)
      end

      # A flare belongs to the attack that is open when it fires.
      # Weapon info DISAMBIGUATES rather than gates: it is only
      # consulted to reject a flare whose named weapon contradicts
      # the open swing, and 63% of attacks name no weapon at all
      # (spells, volley), so requiring a match orphaned them.
      #
      # Gating on the match cost real attributions: a second flare
      # on one swing ("Your slim short sword glows..." after a
      # baselard swing) and every bow flare whose swing line names
      # the ARROW ("ghezyte long bow" vs "firewheel arrow") were
      # held as pre-flares and emitted as standalone events - 229
      # cases in a 60-file replay. Both belong to the open attack.
      #
      # The reject clause still matters: when two weapons' flares
      # fire back to back with no attack line between them, the
      # weapon name is the ONLY thing telling them apart.
      # Our own flare arriving while a creature's inbound attack is
      # the open event: it belongs to the own swing that attack
      # interrupted - resume it (see interrupted_own). Not only the
      # "your <weapon>" lines: the disciple's cloak-of-shadows cast
      # also cut in front of our nature's decay ("Soot brown specks
      # ... in the wake of <creature>"), breeze and arcane reflex
      # ("Vital energy infuses you") lines, which name no weapon
      # (hunt log 2026-09-07 23:50). A creature's cast has no flares
      # of its own; anything the swing could own resumes it.
      # A one-hit side effect (mount collapse) has its hit: the flare
      # that follows is the interrupted swing's (see SINGLE_HIT_ATTACKS;
      # hunt log 2026-09-09 13:44, chameleon shroud on the pin row)
      if current_event && single_hit_parent && SINGLE_HIT_ATTACKS.include?(current_event[:name]) &&
         current_event[:hits].any?
        save_event.call(current_event)
        current_event = single_hit_parent
        single_hit_parent = nil
        current_target = current_event[:target] if current_event[:target] && current_event[:target][:id]
        respond "[Combat] Resumed #{current_event[:name]} after its one-hit side effect (flare)" if Tracker.debug?(:verbose)
      end
      if current_event && (current_event[:inbound] || current_event[:_released]) && interrupted_own &&
         !flare_contradicts_weapon?(flare, interrupted_own)
        save_event.call(current_event)
        current_event = interrupted_own
        interrupted_own = nil
        current_target = current_event[:target] if current_event[:target] && current_event[:target][:id]
        parse_state = :seeking_damage
        respond "[Combat] Resumed interrupted #{current_event[:name]} for its flare" if Tracker.debug?(:verbose)
      end
      # A spell-RELEASING flare fires at the START of an attack. One
      # arriving on a swing that has already landed (hits) or
      # resolved (outcome) - or on a creature's inbound event - is
      # the NEXT swing's, and must be held for it: attached to the
      # finished swing it dragged the released cast under the wrong
      # parent (review of 3c3f1bfe). A maneuver's own SMR does not
      # settle it - pummel rolls its SMR before its release fires.
      releasing_flare = SPELL_RELEASING_FLARES.include?(flare[:name])
      settled_for_release = current_event &&
                            (current_event[:inbound] || current_event[:hits].any? || current_event[:outcomes].any?)
      if current_event && !flare_contradicts_weapon?(flare, current_event) &&
         !(releasing_flare && settled_for_release)
        current_event[:flares] << flare
      else
        pending_flares << flare
      end

      # Only damaging flares own subsequent damage lines; a buff flare
      # (breeze, tailwind) claiming the cursor would steal the parent
      # swing's damage.
      flare_ctx = flare[:damaging] ? flare : nil
      spawn_pending = flare if flare[:spawns]
      # An echo flare (mirror image, hunter's afterimage) is the spawn
      # point of the bare 2p swing that follows it in this blob; queue
      # it so that swing can be parented to it (see echo lineage).
      pending_echoes << { flare: flare, owner: current_event } if ECHO_FLARES.include?(flare[:name])
      respond "[Combat] Found flare: #{flare[:name]}" if Tracker.debug?(:verbose)
    end

    # Spawn-class flares (Blink) fire an imbedded spell whose cast
    # unfolds as a bracketed sequence. Events inside the bracket are
    # children of the flare, not independent casts.
    if (seq = Parser.parse_sequence_start(line))
      # Any sequence bracket names the rounds inside it that print no
      # initiation of their own (a volley arrow that MISSED prints
      # only roll + dodge line; hunt log 2026-09-07: two such arrows
      # recorded as :unknown outside the volley tree).
      active_sequence = seq
      if spawn_pending
        active_spawn = { flare: spawn_pending[:name], sequence: seq, weapon: spawn_pending[:weapon] }
        spawn_pending = nil
        respond "[Combat] Spawn sequence started: #{seq} from #{active_spawn[:flare]}" if Tracker.debug?(:verbose)
      end
    elsif (seq_end = Parser.parse_sequence_end(line))
      active_sequence = nil if active_sequence == seq_end
      if active_spawn && seq_end == active_spawn[:sequence]
        respond "[Combat] Spawn sequence ended: #{active_spawn[:sequence]}" if Tracker.debug?(:verbose)
        active_spawn = nil
      end
    end

    # Assault brackets (single-target multi-round attacks: flurry,
    # barrage, pummel, guardant thrusts, thrash). The opener names
    # the ONLY target the whole assault can strike; the rounds in
    # between usually don't. MODULE state, not a local - the middle
    # rounds arrive in later chunks. The end line also prints when
    # the target dies mid-assault, so death needs no special case.
    if (assault = Parser.parse_assault_start(line))
      @active_assault = { name: assault[:name], target: line_target }
      respond "[Combat] Assault started: #{assault[:name]} on #{line_target ? line_target[:name] : '(unknown)'}" if Tracker.debug?(:verbose)
    elsif @active_assault && Parser.parse_assault_end(line) == @active_assault[:name]
      respond "[Combat] Assault ended: #{@active_assault[:name]}" if Tracker.debug?(:verbose)
      @active_assault = nil
    end

    # Handle target switching (for multi-target attacks like volley).
    # An INBOUND event is aimed at us and has no creature target by
    # construction. It must never adopt one: any creature link later
    # in the chunk (an emote, a room echo) would fill its empty
    # target slot through the nil-branch below and carry the damage
    # the creature dealt US onto that creature (real-feed replay,
    # GSIV-Bodegap 2025-09-17: an ogre's killing 28 damage landed on
    # the ogre via its own "laughs hysterically" emote).
    # A foreign-target event (the def named a player or an
    # unresolvable name) is bound to a non-creature for the same
    # reason and must not adopt one either.
    # A flare announce that names ITS OWN target (a spectral bloom on
    # a creature the glowbark chain reached) is not a target switch:
    # the damage line that follows belongs to that flare, creature-
    # attributed, not to a phantom copy of the swing opened on the
    # bloom's creature (real-feed 2026-09-07: every bloom recorded as
    # a `fire` echo attack with a PLASMA crit while the flare row sat
    # empty). Likewise a non-attack line naming a creature one of this
    # event's flares already touched ("You blinded <bloom target>!")
    # stays with this event.
    flare_owned_target = line_target && current_event &&
                         ((flare && flare[:target_info]) ||
                          (!line_attack && (current_event[:flares] || []).any? do |f|
                            f[:target_info] && f[:target_info][:id] == line_target[:id]
                          end))
    if line_target && !line_redirect && parse_state != :seeking_attack && !flare_owned_target &&
       !(current_event && (current_event[:inbound] || current_event[:foreign_target] ||
                           current_event[:foreign_caster]))
      # Check if this is a real target switch (different creature)
      if current_target && current_target[:id] != line_target[:id]
        # Save previous event if it has data
        if event_savable?(current_event, include_attack_events: include_attack_events)
          save_event.call(current_event)
          respond "[Combat] Saved event for #{current_event[:target][:name]}: #{current_event[:hits].size} hits, #{current_event[:statuses].size} statuses" if Tracker.debug?(:verbose)
        end

        # Create new event for this target (inherit attack name and
        # lineage from previous - a target switch mid-AoE stays inside
        # the same spawned sequence)
        current_event = {
          source: current_event ? current_event[:source] : source,
          name: current_event ? current_event[:name] : :unknown,
          target: line_target,
          weapon: current_event && current_event[:weapon],
          parent: current_event && current_event[:parent],
          # Same attack, another AoE target: it sits at the SAME point
          # in the spawn tree as the event it split from, so it carries
          # the same lineage. root_ref resolves to a real event below.
          root_ref: current_event && current_event[:root_ref],
          parent_ref: current_event && current_event[:parent_ref],
          parent_confidence: current_event && current_event[:parent_confidence],
          hits: [],

          statuses: [],
          flares: [],
          outcomes: [],
          resolutions: [],
          # A line can be BOTH a target switch and a new attack (an
          # AoE's per-target line). The switch fires first, creating
          # this inherited event; if the attack branch then replaces
          # it on the SAME line, it is an artifact, not a miss - mark
          # the birth line so the attack branch can tell.
          _line: index
        }
        # A held roll belongs to the target this line names, not to
        # a later attack: volley's per-arrow SMR precedes the arrow
        # line, and for a MISSED arrow the outcome line is all there
        # is - without this claim the miss's roll leaked into the
        # next arrow's event (real-feed replay, volley.txt).
        unless pending_resolutions.empty?
          current_event[:resolutions].concat(pending_resolutions)
          pending_resolutions = []
        end
        flare_ctx = nil
        current_target = line_target
        respond "[Combat] Switched to target: #{line_target[:name]} (#{line_target[:id]})" if Tracker.debug?(:verbose)

      elsif current_target.nil?
        # First target for current event - just set it, don't discard
        # data. But a creature can never be its own victim: on a 3p
        # initiation with no target of its own (":ambush" - "<creature>
        # leaps from hiding to attack!") the only link in the chunk is
        # the ATTACKER, and adopting it applied the damage it dealt US
        # to itself (real-feed replay, GSIV-Nisugi 2024-11-21: a triton
        # assassin's 15-damage ambush landed on the assassin).
        attacker_id = current_event[:attacker] && current_event[:attacker][:id]
        unless attacker_id && attacker_id == line_target[:id]
          current_event[:target] = line_target
          current_target = line_target
        end
        respond "[Combat] Found target: #{line_target[:name]} (#{line_target[:id]})" if Tracker.debug?(:verbose)
      end
      # If current_target[:id] == line_target[:id], do nothing (same target)
    end

    # Outcomes (why nothing landed) and resolutions (the roll lines)
    # attach to whatever the cursor points at - an active flare owns
    # its own SMR line, the swing owns its AS/DS line. Arrays because
    # multi-strike attacks (flurry) roll several times per target.
    # Runs AFTER target switching: an outcome line names its target
    # ("the warg evades!"), so the switch must happen first or the
    # outcome lands on the previous target's event.
    # Only parsed when a recorder-class subscriber wants the blob.
    if include_attack_events
      if (resolution = Parser.parse_resolution(line))
        # Most rolls FOLLOW their attack line (swing -> AS/DS), but
        # volley's SMR PRECEDES each arrow line. A roll claims the
        # current sink only while that sink has no damage yet;
        # otherwise it is held for the next attack event, which
        # claims it on creation. Damage alone is the boundary -
        # "no roll yet" was part of it, but barrage pairs an aim
        # SMR (claimed at creation) WITH a per-arrow AS/DS, and the
        # stricter rule orphaned every arrow's roll (real-feed
        # replay, logs/examples/Barrage.txt).
        # A damaging flare claims a roll only while it has no damage
        # yet (mirror image: flare -> roll -> damage). One that
        # already dealt its damage is complete - an acid proc must
        # not steal the next swing's AS/DS (real-feed replay,
        # logs/examples/weapon_pulverize.txt).
        # A PHYSICAL roll arriving on a flare-released spell that has
        # ALREADY resolved is the interrupted swing's: resume the swing
        # first so the routing below lands the roll and its damage on
        # it (see SPELL_RELEASING_FLARES). "Already resolved" matters:
        # Holy Weapon can release a BOLT, whose own AS/DS is the first
        # roll after its cast line - that one is the bolt's, and only
        # the roll after it belongs to the swing. Keying on roll type
        # alone gave the bolt's roll and damage to the swing (review
        # of 056ff899). A warding cast resolves on its CS/TD first
        # either way, so this is a no-op for Templar's Verdict.
        if current_event && current_event[:_released] && interrupted_own &&
           %i[as_ds uaf_udf].include?(resolution[:type]) &&
           (current_event[:resolutions].any? || current_event[:hits].any? || current_event[:outcomes].any?)
          save_event.call(current_event)
          current_event = interrupted_own
          interrupted_own = nil
          current_target = current_event[:target] if current_event[:target] && current_event[:target][:id]
          parse_state = :seeking_damage
          flare_ctx = nil
          respond "[Combat] Resumed interrupted #{current_event[:name]} for its #{resolution[:type]} roll" if Tracker.debug?(:verbose)
        end
        settled_flare = flare_ctx if flare_ctx && flare_ctx[:hits].any?
        flare_ctx = nil if settled_flare
        sink = flare_ctx
        # Crit RIDER roll: a knockdown crit rolls its own SMR after
        # the damage and then narrates the fall on the very next
        # line. It belongs to the hit that caused it (the flare or
        # the swing), not to the next attack - held, it became a
        # synthetic :unknown on the wrong creature.
        if sink.nil? && %i[smr maneuver_roll].include?(resolution[:type]) &&
           (peek = lines[index + 1]) && Definitions::Resolutions.crit_rider_line?(peek)
          sink = settled_flare || (current_event && current_event[:hits].any? ? current_event : nil)
        end
        # Roll routing differs by roll class (fixture-verified,
        # logs/examples/):
        #   SMR/SSR/maneuver rolls PRECEDE their per-target line
        #   (volley, barrage, pin) - one arriving on a settled event
        #   (has damage or an outcome) belongs to the NEXT target,
        #   so it is held.
        #   AS/DS-class rolls always FOLLOW their attack line - a
        #   multi-strike (flurry: one initiation, five rolls with
        #   outcomes and damage interleaved) keeps every roll on
        #   the attack-born event.
        if sink.nil? && current_event
          maneuver_roll = %i[smr ssr maneuver_roll fear].include?(resolution[:type])
          born = current_event[:_attack_born]
          if maneuver_roll
            # On an ATTACK-BORN event only damage settles it: cripple
            # prints init -> resisted outcome -> SMR, and that roll is
            # the maneuver's own (logs/examples/cripple.txt). On a
            # switch-born event an outcome settles too - a volley
            # miss's roll came BEFORE its outcome, so one arriving
            # after belongs to the next arrow.
            #
            # A STATUS settles a switch-born event the same way: an
            # AoE status effect rolls once PER onlooker, each roll
            # printed BEFORE the creature it applies to (eviscerate:
            # ssr -> freeze -> unsettled, twice). Without this the
            # second roll fell into the first bystander's still-open
            # event - which had no hits and no outcome to settle it -
            # and the second bystander recorded no roll at all
            # (Rysk logs 2026-09-11, fixture eviscerate.txt).
            settled = current_event[:hits].any? ||
                      (!born && (current_event[:outcomes].any? ||
                                 current_event[:_had_status]))
            sink = current_event unless settled
          elsif born || (current_event[:hits].empty? && current_event[:outcomes].empty?)
            sink = current_event
          end
        end
        if sink
          sink[:resolutions] << resolution
        else
          pending_resolutions << resolution
        end
        respond "[Combat] Found resolution: #{resolution[:type]} = #{resolution[:result]}" if Tracker.debug?(:verbose)
      elsif (outcome = Parser.parse_outcome(line))
        # A pre-emptive evade ("bounds to safety as you move to attack
        # it") is OUR swing resolving, and it names the creature we
        # swung at. A creature's inbound swing is never closed by the
        # target-switcher, so one left open across the nock swallowed
        # the evade and our own swing was never opened - the nocked
        # bow had nothing to name. Scoped to a live nock: only there
        # do we know an outbound swing is outstanding, so inbound
        # maneuvers whose resist line names their own caster
        # possessively ("the warg's unnerving howl") still attach.
        preempts_open_inbound = nocked && current_event && current_event[:inbound] &&
                                !flare_ctx && line_target && line_target[:id] &&
                                !Definitions::Outcomes.inbound_line?(line)
        if line_attack
          same_line_outcome = outcome
        elsif flare_ctx || (current_event && !preempts_open_inbound)
          (flare_ctx || current_event)[:outcomes] << outcome
        elsif line_target && line_target[:id]
          # Reached with an open event only via preempts_open_inbound:
          # the creature's swing that interleaved between our nock and
          # the pre-emptive evade. Save it before opening ours, as the
          # single_hit_parent / interrupted_own resumptions do - it
          # may carry a fully resolved hit on us.
          save_event.call(current_event) if event_savable?(current_event, include_attack_events: include_attack_events)
          # An outcome with a named target and no event at all: the
          # first arrow of a volley round can be a miss - roll +
          # outcome, no attack line, at the top of the chunk. Open
          # the event here (chunk-locally the maneuver name is
          # unknowable) so the miss and its roll survive.
          # When the line names who attacked US instead ("the thorny
          # barrier ... blocks the attack from <X>"), the swing was
          # intercepted before it printed: an INBOUND unknown with X
          # as the attacker, never an attack on X.
          if Definitions::Outcomes.inbound_line?(line)
            # (a creature's wholly-negated ambush on us is this shape
            # too: prefix, then the intercept, no attack line)
            current_event = {
              source: source,
              name: (pending_ambush && pending_ambush[:hidden]) ? :ambush : :unknown, target: {}, inbound: true,
              attacker: line_target, weapon: nil, parent: nil,
              hits: [], statuses: [], flares: [], outcomes: [outcome],
              ambush: !!(pending_ambush && pending_ambush[:hidden]),
              attack_kind: pending_ambush && pending_ambush[:kind],
              resolutions: pending_resolutions
            }
            pending_ambush = nil
            pending_resolutions = []
            parse_state = :seeking_damage
          else
            # Inside a volley bracket the round IS a volley arrow: name
            # it and seat it in the volley's spawn tree (the first arrow
            # of the round becomes the root the later arrows point at).
            round_name = SEQUENCE_ROUND_NAMES.include?(active_sequence) ? active_sequence : nil
            # a nocked bow with no fire line printed: the outcome IS
            # the fire (pre-emptive evade, see nocked decl)
            nock_fire = nocked && !(pending_ambush && pending_ambush[:hidden]) && round_name.nil?
            current_event = {
              source: source,
              name: (pending_ambush && pending_ambush[:hidden]) ? :ambush : (round_name || (nock_fire ? :fire : :unknown)),
              target: line_target, attacker: nil,
              weapon: nock_fire ? nocked : nil, parent: nil, hits: [],
              statuses: [], flares: [], outcomes: [outcome],
              # A wholly-negated ambush prints its prefix and then an
              # intercept, with no attack line between - this is the
              # only record that the ambush was attempted.
              ambush: !!(pending_ambush && pending_ambush[:hidden]),
              attack_kind: pending_ambush && pending_ambush[:kind],
              resolutions: pending_resolutions
            }
            if round_name
              # lineage as the attack branch would stamp it: first own
              # event of the blob roots the tree, later ones point at it
              spawn_root ||= current_event
              current_event[:root_ref] = spawn_root
            end
            pending_ambush = nil
            pending_resolutions = []
            nocked = nil if nock_fire
            current_target = line_target
            parse_state = :seeking_damage
          end
        else
          # No event, no named target: an outcome for an
          # initiation we have no def for. Orphan-sink it.
          orphan_outcomes << outcome
        end
        respond "[Combat] Found outcome: #{outcome}" if Tracker.debug?(:verbose)
      end
    end

    # Ambush prefix ("<X> leaps from hiding to strike!"). Attacking
    # from hiding is still just an attack - the prefix only marks
    # that it carries the ambush bonuses (DS pushdown + crit
    # weighting). It is NOT an attack of its own: the real attack
    # line follows and carries the target and the roll. Arm the flag
    # and move on; the next attack claims it.
    if (amb = Definitions::Attacks.ambush_prefix(line))
      pending_ambush = { attacker: amb[:attacker], kind: amb[:kind], hidden: amb[:hidden] }
      respond '[Combat] Ambush prefix armed' if Tracker.debug?(:verbose)
    end

    # Guardian redirect prefix (see pending_redirect decl). Like the
    # ambush prefix it is a modifier on the attack line that follows,
    # never an event or outcome of its own. The interceptor is the
    # bolded creature on the line when the feed carries links.
    if (rdr = line_redirect)
      redirect = {
        interceptor: line_target || { name: Parser.strip_links(rdr[:interceptor]) },
        intended: rdr[:intended]
      }
      # UAC shape (corpus: 21/130, all "You attempt to kick <X>!"):
      # the announce comes AFTER the attack line, no re-issued
      # attack follows, and the roll/damage still land on the
      # intended victim. The guardian announced but did not take
      # the hit. Stamp the open attack as an unhonored redirect so
      # the fact survives, and do NOT arm the pending marker - a
      # later unrelated swing in the chunk must not claim it.
      # (noun from the link; in stripped mode the open event carries
      # no target identity at all, so an open fact-less attack is
      # taken as the intended one - the only shape the corpus shows)
      open_noun = current_event && current_event[:target] &&
                  (current_event[:target][:noun] || current_event[:target][:name]&.split&.last)
      if current_event && !current_event[:redirect] && current_event[:_attack_born] &&
         (open_noun.nil? || open_noun == rdr[:intended]) &&
         current_event[:resolutions].empty? && current_event[:hits].empty? &&
         current_event[:outcomes].empty?
        current_event[:redirect] = redirect.merge(honored: false)
        respond "[Combat] Redirect announced but not honored (#{rdr[:intended]})" if Tracker.debug?(:verbose)
      else
        pending_redirect = redirect.merge(honored: true)
        respond "[Combat] Redirect prefix armed: intended #{rdr[:intended]}" if Tracker.debug?(:verbose)
      end
    end

    # Attack check is needed in both states (a new attack while seeking
    # damage closes the previous event), so run it once per line. This
    # replaces the old `redo`, which re-ran the status/UCS handlers
    # above on the same line and double-applied their effects.
    attack = (amb || rdr) ? nil : line_attack

    if (nock = line.gsub(/<[^>]+>/, '').match(/\AYou nock .+? in your (?<weapon>[^.]+)\.\s*\z/))
      nocked = nock[:weapon]
    end
    if attack
      # A bare gesture :cast event is the WRAPPER for whatever
      # spell-specific initiation follows in the same chunk (searing
      # light's engulf, evoked tangleweed's lash): the specific def
      # supersedes it. Hand its rolls to the new event, mark the new
      # event via: :cast, and discard the wrapper instead of emitting
      # a fact-less phantom cast. Guards:
      #   - facts on the wrapper (wild entropy, moonbeam - no
      #     specific def ever fires) mean it emits normally;
      #   - an ATTACKER on the new line that differs from the
      #     wrapper's means an unrelated (creature) attack
      #     interleaved - that must not eat our cast. Spell-result
      #     lines are attackerless, so they supersede.
      #   - a cast HELD over from the previous chunk (see @held_cast)
      #     is superseded only by a spell-result line, never by a
      #     fresh 2p initiation of our own ("You fire ...") - that is
      #     the next action, not this cast's effect.
      superseded_cast = nil
      superseded_source = nil
      if bare_cast?(current_event) &&
         (attack[:attacker].nil? ||
          (current_event[:attacker] && attack[:attacker][:name] == current_event[:attacker][:name])) &&
         (!current_event[:_held] || !line.match?(/\AYou\b/))
        pending_resolutions = current_event[:resolutions] + pending_resolutions
        # fact-less flares on the wrapper (a mirror echoing the
        # gesture) belong to the spell event that replaces it
        pending_flares.concat(current_event[:flares])
        superseded_cast = true
        superseded_source = current_event[:source]
        current_event = nil
      end
      # A one-hit side effect remembers the event it cut in front of
      # (see SINGLE_HIT_ATTACKS); anything else clears it. The side
      # effect's own line names ITS victim, so the target switcher
      # has already saved the real parent and left a same-line
      # artifact copy in current_event - the parent is the saved one.
      single_hit_parent = nil
      if SINGLE_HIT_ATTACKS.include?(attack[:name])
        cand = current_event && current_event[:_line] == index ? events.last : current_event
        single_hit_parent = cand if cand && !cand[:inbound] && !cand[:foreign_caster] && !cand[:foreign_target]
      end
      # Save previous event before starting a new one - unless the
      # target-switcher created it on this very line (see _line)
      if event_savable?(current_event, include_attack_events: include_attack_events) && current_event[:_line] != index
        save_event.call(current_event)
        respond "[Combat] Completed event for #{current_event[:target][:name]}: #{current_event[:hits].size} hits" if Tracker.debug?(:verbose)
        # an inbound attack cutting into our own open swing: remember
        # the swing so its trailing flares can resume it
        if attack[:inbound] && !(current_event[:inbound] || current_event[:foreign_caster] || current_event[:foreign_target])
          interrupted_own = current_event
        end
        # our own swing carrying an UNCLAIMED spell-releasing flare:
        # a weaponless CAST opening now is that flare's spell, cutting
        # into the swing. One flare releases one spell - claiming it
        # marks the flare consumed, and a weapon-bearing swing line is
        # never the released spell - otherwise a second swing later in
        # the chunk read as "released" too and handed its roll and
        # damage back to the first swing (review of 056ff899).
        if !attack[:inbound] && !(current_event[:inbound] || current_event[:foreign_caster] || current_event[:foreign_target]) &&
           attack[:weapon].nil? && Parser.parse_swing_weapon(line).nil? &&
           (rel = (current_event[:flares] || []).find { |f| SPELL_RELEASING_FLARES.include?(f[:name]) && !f[:_release_claimed] })
          rel[:_release_claimed] = true
          interrupted_own = current_event
          released_parent = { event: current_event, flare: rel }
        end
        last_inbound_attacker = current_event[:attacker] if current_event[:inbound] && current_event[:attacker]
      end
      # A same-line artifact event may have claimed held rolls in
      # the switch branch above (volley: the arrow's own SMR) -
      # they belong to THIS attack, so carry them across the
      # replacement instead of discarding them with the artifact.
      # The switch artifact also inherited spawn-tree lineage from the
      # sibling it split from (a multi-target AoE per-target line is the
      # same attack striking another creature - same tree node). Capture
      # it here so the fresh current_event below can carry it forward
      # instead of recomputing a fresh root and fragmenting the AoE.
      switch_artifact_lineage = nil
      if current_event && current_event[:_line] == index
        pending_resolutions = current_event[:resolutions] + pending_resolutions if current_event[:resolutions].any?
        if current_event[:root_ref]
          switch_artifact_lineage = {
            root_ref: current_event[:root_ref],
            parent_ref: current_event[:parent_ref],
            parent_confidence: current_event[:parent_confidence]
          }
        end
      end

      # Foreign-attacker latch (see foreign_latch decl). A 2p "You..."
      # attack is ours and reclaims ownership - clear the latch. A
      # foreign_caster attack (its line names a player) arms it, so
      # the actor-less swing/effect lines that fan out from a nearby
      # player's AoE inherit their ownership. An event is foreign when
      # its own def said so, OR when the latch is armed and this line
      # named no actor of its own (an anonymous AoE per-target swing).
      our_2p = line.match?(/\AYou\b/) && attack[:attacker].nil? &&
               !attack[:foreign_caster]
      foreign_latch = nil if our_2p
      foreign_latch = attack[:attacker][:name] if attack[:foreign_caster] && attack[:attacker]
      eff_foreign = attack[:foreign_caster] ||
                    (foreign_latch && attack[:attacker].nil? && !our_2p) || nil

      current_event = {
        source: superseded_cast ? superseded_source : source,
        name: attack[:name],
        target: attack[:target] || {},
        attacker: attack[:attacker], # nil for our own (2nd-person) attacks
        # Aimed at US. Carries no creature target, so event_savable?
        # drops it and its damage/crits are never applied to the
        # attacker - but it still closes the previous event and
        # absorbs the roll/damage lines that follow, keeping them
        # off the creature we were fighting.
        inbound: attack[:inbound],
        # The def named a target that is not a creature (a player,
        # an unresolvable name). Same rule as inbound: never adopt
        # a creature later in the chunk.
        foreign_target: attack[:foreign_target],
        # A nearby player's attack on a creature we can see. Unlike
        # foreign_target it DOES have a creature target; persist_event
        # emits it for observers but never applies it to the creature.
        # eff_foreign folds in the foreign_latch: an anonymous swing
        # inside a nearby player's AoE is theirs even though its own
        # line named nobody.
        foreign_caster: eff_foreign,
        # A DoT/effect TICK line (pestilence boils, web ensnare) that
        # named the victim but no caster, arriving with no owning cast
        # of that spell in this blob. Its damage still applies to the
        # creature (real received damage) but is NOT our deal - the
        # recorder files it under other/unknown. Ours only when our
        # own cast set cast_owner[[name, victim]] = :self this blob; a
        # foreign cast makes it foreign_caster instead. A CAST line
        # ("You exhale...") is our own initiation, never unowned - it
        # is excluded by the owning-cast check below (which set :self
        # for it) plus the 2p-line guard. Keyed by THIS tick's victim,
        # so our cast on another creature can't claim it.
        unowned: (UNOWNED_TICK_ATTACKS.include?(attack[:name]) &&
                  attack[:attacker].nil? && !eff_foreign &&
                  !line.match?(/\AYou\b/) &&
                  cast_owner[cast_owner_key.call(attack[:name], attack[:target])] != :self) || nil,
        # Struck from hiding: this attack carries the ambush
        # bonuses (DS pushdown + crit weighting). A modifier on the
        # attack, not an attack of its own.
        ambush: !!(pending_ambush && pending_ambush[:hidden]),
        # Which hiding maneuver armed it (:waylay weights damage,
        # :ambush weights crits) - see AMBUSH_KINDS. Reaction
        # prefixes set the kind but leave `ambush` false.
        attack_kind: pending_ambush && pending_ambush[:kind],
        # A guardian stepped in front of the creature we struck at
        # and this attack resolved against the guardian instead:
        # { interceptor: {id?, name}, intended: <victim noun> }.
        # A modifier, not an outcome - nothing was nullified.
        redirect: pending_redirect,
        # Aimed shot ("take aim and", or UAC's "make a precise").
        # Same shape as :ambush - a modifier, not an attack. The
        # defs captured this all along and it was never surfaced.
        aimed: attack[:aimed] || false,
        weapon: Parser.parse_swing_weapon(line) || attack[:weapon],
        # the gesture line that opened this spell (see wrapper rule)
        via: superseded_cast ? :cast : nil,
        parent: active_spawn ? { flare: active_spawn[:flare], weapon: active_spawn[:weapon] } : nil,
        # Spawn-tree links (resolved to row ids by the recorder):
        #   :root_ref   - the initiating own attack of this blob's tree
        #   :parent_ref - the immediate spawner, ONLY when we can assert
        #                 it (blink's bracket); nil when ambiguous
        #   :parent_confidence - :bracket (declared by the game) for
        #                 blink; nil otherwise. Reserved for :count
        #                 (count-constraint-forced) in a later pass.
        # eff_foreign/inbound events are their own root and do not join
        # our tree; they are handled after the hash is built.
        root_ref: nil,
        parent_ref: nil,
        parent_confidence: nil,
        hits: [],

        statuses: [],
        flares: [],
        outcomes: [],
        resolutions: [],
        # Born from a real initiation line - multi-strike rolls keep
        # attaching here even after outcomes/damage (see roll routing)
        _attack_born: true
      }
      # The swing the nock announced has printed (see decl). Only OUR
      # own attack can be that swing - "You nock" is first-person - so
      # a creature's inbound swing or another player's attack
      # interleaving between the nock and the fire must not clear it,
      # or the fire (or the pre-emptive evade standing in for it)
      # loses its weapon and falls back to :unknown, which is the very
      # failure the nock tracking exists to prevent.
      nocked = nil unless current_event[:inbound] || eff_foreign
      # see last_inbound_attacker decl
      if current_event[:inbound] && current_event[:attacker].nil? && last_inbound_attacker &&
         !Definitions::Attacks.attackerless_line?(line)
        current_event[:attacker] = last_inbound_attacker
      end

      # Spawn-tree lineage (see spawn_root decl). We stamp ONLY lineage
      # we can assert, never a positional guess:
      #   - blink's bracketed cast (active_spawn) is a child DECLARED by
      #     the game: root = the open tree root, parent = that root,
      #     confidence :bracket.
      #   - a mirror/afterimage ECHO: the echo flare announces, then the
      #     spawned swing prints as a bare 2p line of the same attack
      #     ("You fire ..."). The whole tree resolves inside one blob
      #     before roundtime, so a bare own swing arriving while an echo
      #     flare of this blob is unconsumed IS that flare's swing -
      #     pair them FIFO (the count constraint: N echo flares, N echo
      #     swings). parent = the event the flare rode, confidence
      #     :count, parent flare recorded so reports can hang the echo
      #     under the flare row (owner ruling 2026-09-07: "the flare
      #     is the attack"). An echo's own echo flare parents the next
      #     swing to the echo, so mirror->afterimage chains nest.
      #   - every other own attack becomes the root of its OWN tree.
      #   - inbound/foreign/orphan events are their own root regardless.
      # A foreign/inbound/unowned/orphan event is NEVER part of our
      # spawn tree - it must not graft onto or become a linkable node in
      # it. This single flag gates every branch below (the switch-
      # artifact branch omitted it once and let a nearby player's attack
      # on another creature inherit our lineage - real-feed group play).
      not_ours = current_event[:inbound] || current_event[:foreign_target] ||
                 current_event[:foreign_caster] || current_event[:unowned] ||
                 current_event[:_orphan]
      if switch_artifact_lineage && !not_ours
        # Same-line AoE per-target line: this is the same attack
        # striking another creature, so it sits at the SAME spawn-tree
        # node as the sibling it split from. Carry that lineage forward
        # rather than recomputing (which would fragment the AoE into N
        # independent single-hit roots).
        current_event[:root_ref] = switch_artifact_lineage[:root_ref]
        current_event[:parent_ref] = switch_artifact_lineage[:parent_ref]
        current_event[:parent_confidence] = switch_artifact_lineage[:parent_confidence]
      elsif active_spawn && spawn_root && !not_ours
        current_event[:root_ref] = spawn_root
        current_event[:parent_ref] = spawn_root
        current_event[:parent_confidence] = :bracket
      elsif released_parent && !not_ours
        # A spell released by the swing's own flare: child of that
        # swing. Asserted by adjacency (one releasing flare, one
        # cast), the same count constraint an echo uses.
        owner = released_parent[:event]
        current_event[:root_ref] = owner[:root_ref] || owner
        current_event[:parent_ref] = owner
        current_event[:parent_confidence] = :count
        current_event[:parent] = { flare: released_parent[:flare][:name], weapon: released_parent[:flare][:weapon] }
        current_event[:_released] = true
        released_parent = nil
      elsif !not_ours && spawn_root && !pending_echoes.empty? && line.match?(/\AYou\b/) &&
            current_event[:name] == (pending_echoes.first[:owner] || spawn_root)[:name]
        echo = pending_echoes.shift
        owner = echo[:owner] || spawn_root
        current_event[:root_ref] = spawn_root
        current_event[:parent_ref] = owner
        current_event[:parent_confidence] = :count
        current_event[:parent] = { flare: echo[:flare][:name], weapon: echo[:flare][:weapon] }
      else
        spawn_root = current_event unless not_ours
        current_event[:root_ref] = current_event
      end
      # A weaponless cast opening while a spell-releasing pre-flare
      # is still unclaimed IS that flare's spell (proc -> spell ->
      # swing ordering). Mark it so the assault guard leaves the
      # bracket alone, and hold it for the swing to adopt.
      if !not_ours && !current_event[:_released] && current_event[:weapon].nil? &&
         pending_flares.any? { |f| SPELL_RELEASING_FLARES.include?(f[:name]) }
        current_event[:_released] = true
        pending_release_cast = current_event
      end

      # Record ownership of a DoT/effect spell from its CAST line so
      # the ticks that follow (this blob or later) can be claimed.
      # Our 2p cast ("You exhale a virulent green mist...") makes the
      # spell ours; a 3p cast names the foreign caster. Cast lines
      # carry no inline damage, so a same-name event WITH damage is a
      # tick, not a cast - only the cast sets ownership.
      if UNOWNED_TICK_ATTACKS.include?(current_event[:name]) && current_event[:hits].empty?
        owner =
          if current_event[:foreign_caster] then (current_event[:attacker] && current_event[:attacker][:name]) || :foreign
          elsif current_event[:attacker].nil? && line.match?(/\AYou\b/) then :self
          end
        # Bind ownership to the creature this cast targeted, not the
        # spell globally (see cast_owner decl).
        cast_owner[cast_owner_key.call(current_event[:name], current_event[:target])] = owner
      end

      # Claimed - the ambush/redirect belong to this attack only.
      pending_ambush = nil
      pending_redirect = nil
      current_target = current_event[:target][:id] ? current_event[:target] : nil

      # Assault binding: while an assault is open, its own targetless
      # rounds (barrage's re-nock, flurry's direction-reverse) strike
      # the assault target by definition. :ambush is neutral - the
      # restealth re-emerge line rides inside shadow-mastery assaults
      # (see weapon_pulverize.txt) and binds the same way. Any OTHER
      # outbound attack def is impossible during an assault, so it
      # means our bracket state is stale (missed end line, script
      # restart) - drop the context rather than misattribute.
      if @active_assault && !current_event[:inbound] && !current_event[:foreign_target]
        if current_event[:name] == @active_assault[:name] || current_event[:name] == :ambush
          if current_target.nil? && @active_assault[:target] && @active_assault[:target][:id]
            current_event[:target] = @active_assault[:target]
            current_target = @active_assault[:target]
            respond "[Combat] Assault bound target: #{current_target[:name]}" if Tracker.debug?(:verbose)
          elsif current_target && @active_assault[:target].nil?
            # barrage's opener names no target - the first named
            # round inside the bracket backfills it
            @active_assault[:target] = current_target
          end
        elsif current_event[:attacker].nil? &&
              !%i[unknown companion].include?(current_event[:name]) &&
              !current_event[:_released]
          # Only OUR OWN attacks are impossible mid-assault. A third
          # party's are normal and must not disturb the bracket:
          # :companion defs capture (?<companion>) not (?<attacker>)
          # so they parse attackerless, hence the explicit exemption;
          # creature-vs-groupmate defs carry :attacker and fall out
          # on the nil check. Those events keep their own captured
          # targets and attribute normally either way - this guard
          # only decides whether the assault context survives them.
          respond "[Combat] Assault context dropped (unexpected attack: #{current_event[:name]})" if Tracker.debug?(:verbose)
          @active_assault = nil
        end
      end

      # Some initiation lines carry their damage INLINE rather than on
      # a following "... N points of damage!" line - the damage-over-
      # time ticks ("Pustules break out all over X causing 44 points
      # of damage!") are the whole event, message and damage in one.
      # The attack branch returns before the damage branch runs, so
      # without this the tick's damage was dropped entirely while an
      # unrelated swing later in the same chunk persisted normally
      # (real-feed replay: 59 and 44 lost against a gigas berserker).
      # No track_damage gate: the main damage branch has none, and
      # gating only here made inline-damage events vanish under
      # configs that omit the key (replay 2026-09-05, pestilence)
      if !SUMMARY_DAMAGE_ATTACKS.include?(current_event[:name]) && (inline = Parser.parse_damage(line))
        current_event[:hits] << { damage: inline, crit: nil, line: index }
        respond "[Combat] Found inline damage: #{inline}" if Tracker.debug?(:verbose)
      end
      current_event[:outcomes] << same_line_outcome if same_line_outcome

      # A new swing claims any held pre-flares whose weapon matches it
      # (they resolved before this swing but belong to it). An inbound
      # attack claims neither pre-flares nor held rolls: both were
      # produced by OUR weapon and still belong to our next swing.
      unless current_event[:inbound]
        unless pending_flares.empty?
          # A bow's pre-flare (dispel on the nock) names the BOW while
          # the shot names the ARROW, so a weapon-name match cannot be
          # required (hunt log 2026-09-07: 16 of 16 dispels became
          # their own attacks, in-chunk, right before "You fire"). A
          # pre-flare belongs to this swing unless a flare from a
          # DIFFERENT weapon already sits on it - the back-to-back
          # dual-wield signature (see flare_contradicts_weapon?).
          # Sequential so the first claimed flare guards the second.
          still_pending = []
          pending_flares.each do |f|
            # A spell-RELEASING pre-flare (Holy Weapon) rode a swing,
            # never the spell it released: only an attack that names
            # a weapon may claim it. Left to the generic rule the
            # Templar's Verdict cast took it, which then read as the
            # swing that released the spell and pulled the real
            # swing's AS/DS onto the cast (Dreadt log 2026-09-11
            # 12274, 12715).
            releasing = SPELL_RELEASING_FLARES.include?(f[:name])
            claim = if releasing
                      current_event[:weapon] && !flare_contradicts_weapon?(f, current_event)
                    else
                      flare_matches_weapon?(f, current_event[:weapon]) || !flare_contradicts_weapon?(f, current_event)
                    end
            if claim
              # fired BEFORE the swing line (dispel-on-nock, ensorcell's
              # veil): never the cause of a status the swing's own crit
              # inflicts afterwards (see status_flare_seq)
              f[:_pre] = true
              current_event[:source] = combined_observation_source(current_event[:source], f[:source])
              current_event[:flares] << f
              # ...and the cast that flare released, which printed
              # before this swing, is this swing's child.
              if releasing && pending_release_cast
                f[:_release_claimed] = true
                cast = pending_release_cast
                cast[:root_ref] = current_event[:root_ref] || current_event
                cast[:parent_ref] = current_event
                cast[:parent_confidence] = :count
                cast[:parent] = { flare: f[:name], weapon: f[:weapon] }
                # re-emit it after the swing (recorder needs parent first)
                events.delete_if { |e| e.equal?(cast) }
                (current_event[:_released_children] ||= []) << cast
                deferred_casts << cast
                pending_release_cast = nil
              end
            else
              still_pending << f
            end
          end
          pending_flares = still_pending
        end
        unless pending_resolutions.empty?
          current_event[:resolutions].concat(pending_resolutions)
          pending_resolutions = []
        end
      end
      # Exception: a creature MANEUVER rolls before its line prints
      # (3p feint: "[SMR] X feints high, but you aren't fooled"; sap
      # spit whose miss prints on the NEXT line; a grapple that lands
      # and prints no outcome at all) - that held maneuver roll is its
      # own, not our next swing's. This used to key on the line
      # carrying its own outcome, which only covered the feint shape
      # and left the other two orphaned (Rysk/Dreadt logs 2026-09-11).
      # The roll IS ours only when we are mid-sequence: volley (a
      # sequence) and barrage (an assault) print our SMR before our
      # arrow line, and both announce themselves, so those states keep
      # the hold. Every OTHER assault (pummel, flurry, thrash, guardant
      # thrust) rolls AFTER its round line - fixture-verified - so an
      # open one must not block the claim: a pummel was open when a
      # slaver's subdue cut in, and the blanket guard orphaned that
      # roll (Dreadt log 2026-09-11 7280). Corpus census 2026-09-12:
      # 5 maneuver-SMR -> inbound-line shapes, 0 with our own attack
      # following in the chunk. Maneuver-class rolls only - AS/DS
      # never precedes.
      if current_event[:inbound] && !pending_resolutions.empty? &&
         active_sequence.nil? && !nocked &&
         !(@active_assault && ROLL_BEFORE_ROUND_ASSAULTS.include?(@active_assault[:name]))
        mine, pending_resolutions = pending_resolutions.partition { |r| %i[smr ssr maneuver_roll].include?(r[:type]) }
        current_event[:resolutions].concat(mine)
      end
      flare_ctx = nil

      respond "[Combat] Found attack: #{attack[:name]}" if Tracker.debug?(:verbose)
      parse_state = :seeking_damage
    elsif flare_ctx || parse_state == :seeking_damage
      # Accumulate damage lines. An active flare cursor owns them
      # (its damage arrives after its announce line, before the next
      # swing); otherwise they belong to the current attack. flare_ctx
      # alone also routes pre-flare damage arriving before any swing.
      #
      # A coup de grace prints no damage line: its success line is the
      # killing blow. Record it as a zero-damage FATAL hit so the kill
      # is credited and shown like a fatal crit (owner ruling
      # 2026-09-07); the room-feed death that follows agrees.
      if current_event && current_event[:name] == :coup_de_grace &&
         (coup_loc = Definitions::Attacks.coup_kill_location(line))
        current_event[:hits] << { damage: 0, line: index, crit: { location: coup_loc, type: 'coup_de_grace', rank: nil,
                                                     wound_rank: nil, fatal: true } }
        chunk_deaths << current_event[:target][:id] if current_event[:target] && current_event[:target][:id]
        respond '[Combat] Coup de grace kill' if Tracker.debug?(:verbose)
      elsif (damage = Parser.parse_damage(line))
        # a one-hit side effect already has its hit: this damage is
        # the interrupted attack's (see SINGLE_HIT_ATTACKS)
        if !flare_ctx && current_event && single_hit_parent &&
           SINGLE_HIT_ATTACKS.include?(current_event[:name]) && current_event[:hits].any?
          save_event.call(current_event)
          current_event = single_hit_parent
          single_hit_parent = nil
          current_target = current_event[:target] if current_event[:target] && current_event[:target][:id]
          respond "[Combat] Resumed #{current_event[:name]} after its one-hit side effect" if Tracker.debug?(:verbose)
        end
        sink = flare_ctx || current_event
        # ONE record per landed hit, damage bound to the crit it
        # produced. Parallel :damages/:crits arrays could not express
        # the pairing: their counts differ on 28.7% of events and
        # 48.5% of flares (examples corpus), and a consumer had no way
        # to tell which crit came from which damage. The binding only
        # exists here, where both are in scope.
        #
        # crit stays nil when the lookahead finds none - which IS the
        # concussion marker. Holy fire prints "ravaged for 65" then
        # "... 5 points of damage!"; the 65 is concussion and takes no
        # crit (the lookahead breaks on the next damage line), the 5
        # carries the fire crit.
        hit = { damage: damage, crit: nil, line: index }
        sink[:hits] << hit
        respond "[Combat] Found damage: #{damage}#{flare_ctx ? " (flare: #{flare_ctx[:name]})" : ''}" if Tracker.debug?(:verbose)

        # When we find damage, look ahead 2-3 lines for related crit.
        # This populates hit[:crit], consumed by wound application
        # (apply_crit), status derivation (apply_crit_statuses) AND the
        # emitted :attack payload itself (a recorder reads the crit
        # location/rank/fatal straight off the hit). So it must run
        # whenever ANY of those is enabled. Gating it on track_wounds
        # alone starved status tracking; gating it on wounds||statuses
        # alone starved an emit_attacks-only recorder (combat_stats
        # enables only emit_attacks) of every crit - the emit carried a
        # crit-shaped hole.
        if Tracker.settings[:track_wounds] || Tracker.settings[:track_statuses] ||
           include_attack_events
          (1..3).each do |offset|
            next_line_index = index + offset
            break if next_line_index >= lines.size

            next_line = lines[next_line_index]

            # Stop looking if we hit another damage line (belongs to next damage)
            if Parser.parse_damage(next_line)
              respond "[Combat] Stopped crit search - found next damage line" if Tracker.debug?(:verbose)
              break
            end

            # Look for crit on this line
            if (c = CritRanks.parse(next_line.gsub(/<.+?>/, '')).values.first)
              # Keep the whole CritRanks hash rather than copying five
              # keys out of it: it is already allocated, and the rest
              # (stunned, roundtime, amputated, position, silenced,
              # slowed, dazed, secondary_wound, ...) is state we would
              # otherwise have to infer from messaging - or, for the
              # UCS-only fields, could not obtain at all.
              #
              # :regex is dropped - it is a compiled Regexp that only
              # documents which table row matched, and it makes the
              # payload unserialisable for any recorder downstream.
              hit[:crit] = c.reject { |k, _| k == :regex }
              if c[:fatal]
                victim = flare_ctx ? flare_ctx[:target_info] : (sink[:target_info] || sink[:target])
                chunk_deaths << victim[:id] if victim && victim[:id]
              end
              # Where the crit TEXT sits in the chunk. Crit statuses
              # are applied after the whole chunk is parsed, so this
              # is the only record of where the crit stood relative
              # to the messages around it (see position_recovered?).
              hit[:_crit_line] = next_line_index
              respond "[Combat] Found critical hit: #{c[:location]} rank #{c[:wound_rank]}" if Tracker.debug?(:verbose)
              break # Only take first crit found after this damage
            end
          end
        end
      end
    elsif (orphan_dmg = Parser.parse_damage(line))
      # Damage while seeking an attack: its initiation had no def
      # (or lived in a prior chunk we cannot see). Orphan-sink it
      # rather than dropping the fact.
      orphan_hits << { damage: orphan_dmg, crit: nil, line: index }
      respond "[Combat] Orphan damage: #{orphan_dmg}" if Tracker.debug?(:verbose)
    end

    # The line's status belongs to whichever event now holds that
    # target (the switch above may have just created it) - flag it
    # so event_savable? counts the status as a fact.
    if line_status_id && current_event && current_event[:target][:id] == line_status_id
      current_event[:_had_status] = true
    end
  end

  # Don't forget the last event - unless it is a bare gesture whose
  # spell result has not arrived yet. Live chunks split at the prompt,
  # and "You gesture at X." / "Cast Roundtime 1 Second." end right
  # there, so the wrapper closed and emitted as a fact-less `cast`
  # attack before the briar's lash arrived in the next chunk (real-
  # feed 2026-09-07: 15 phantom casts per hunt, every tangleweed
  # recorded without its via: :cast). Hold it for ONE chunk; the next
  # parse re-opens it (see the top of this method) and either
  # supersedes it or emits it as it stands.
  if bare_cast?(current_event) && !current_event[:_held] && current_event[:attacker].nil?
    @held_cast = current_event
  elsif event_savable?(current_event, include_attack_events: include_attack_events)
    save_event.call(current_event)
  end

  # Orphaned rolls: no attack ever claimed them (trailing rider
  # maneuvers - the pilfer pat-down roll, a topple - or a bespoke
  # initiation we have no def for). Measured at 21% of exchanges
  # lost before this existed (replay harness, 2026-08-21). Wrap
  # them as a synthetic :unknown event bound to the creature being
  # fought, so the roll survives to subscribers - the first slice
  # of the orphan-resolution fallback.
  unless pending_resolutions.empty?
    anchor = current_target || (events.last && events.last[:target])
    if anchor && anchor[:id]
      events << {
        source: source,
        name: :unknown, target: anchor, attacker: nil, weapon: nil,
        parent: nil, hits: [], statuses: [],
        flares: [], outcomes: [], resolutions: pending_resolutions
      }
      pending_resolutions = []
    end
  end

  # Orphan sink: facts whose initiation had no def. Targetless
  # (persist_event never applies it - damage the state machine
  # could not attribute must not land on a guessed creature);
  # exists for recorders, same rationale as inbound events.
  if !orphan_hits.empty? || !orphan_outcomes.empty? || !pending_resolutions.empty?
    events << {
      source: source,
      name: :unknown, target: {}, attacker: nil, weapon: nil,
      parent: nil, hits: orphan_hits, statuses: [],
      flares: [], outcomes: orphan_outcomes,
      resolutions: pending_resolutions, _orphan: true
    }
  end

  # Pre-flares no swing claimed (e.g. the chunk ended first). Ones
  # that resolved damage against a known target still count. First
  # time round they are HELD for one chunk - the swing they belong
  # to is usually the next chunk's first line (dispel-on-nock). A
  # flare already held once is wrapped as its own event so the
  # damage is applied, not dropped.
  hold, wrap = pending_flares.partition { |f| f[:target_info] && !f[:hits].empty? && !f[:_held] }
  @held_pre_flares = hold unless hold.empty?
  wrap.each do |f|
    next unless f[:target_info] && !f[:hits].empty?

    # Data stays on the flare (persist_event applies flare damage
    # separately); duplicating it into the event arrays would
    # double-apply it.
    events << {
      source: f[:source],
      name: f[:name], target: f[:target_info], weapon: f[:weapon] && f[:weapon][:name],
      parent: nil, hits: [], statuses: [], flares: [f],
      outcomes: [], resolutions: []
    }
  end

  # a deferred cast whose swing never saved still carries its facts
  deferred_casts.each { |c| events << c unless events.any? { |e| e.equal?(c) } }
  events
end

.persist_event(event, include_attack_events: attack_events_requested?) ) ⇒ Object

Apply combat event to creature instance (same as before)



1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
# File 'documented/gemstone/combat/processor.rb', line 1877

def persist_event(event, include_attack_events: attack_events_requested?)
  target = event[:target]

  # The whole parsed event as one emit: swing + flares + spawned-cast
  # lineage, already correlated. Recorder-class subscribers get the
  # ledger without reassembling per-fact emits. Emitted FIRST:
  #   - before the target-id guard, because inbound/foreign/orphan
  #     events exist for :attack subscribers only (event_savable?
  #     saves them for exactly this emit; the guard below still
  #     keeps them off any creature),
  #   - before the track_* gates strip anything, so the payload is
  #     complete regardless of settings - and therefore BEFORE the
  #     creature is mutated (an :attack subscriber reading
  #     Creature[id] sees pre-swing state; per-fact emits see post).
  Lich::Common::Events.emit('combat.attack', event) if include_attack_events

  # A nearby player's attack (foreign_caster) DOES resolve onto a
  # creature we can see, so unlike inbound/foreign_target it passes
  # the target-id guard - but its damage, wounds and statuses belong
  # to that player, not to us. Emit it for observers (done above),
  # then stop before touching the creature registry: applying it
  # would credit their kill/damage to us and mutate a creature we
  # did not act on (real-feed, GSIV-Nisugi 2026-09-06: Heavenscent's
  # infused Web on a gigas shield-maiden).
  return if event[:foreign_caster]

  # The swing's own creature (nil for an inbound/self/orphan attack
  # that carries no creature target). Its DIRECT hits/wounds/statuses
  # apply only when it exists - but the event may still carry FLARES
  # that strike a creature (a reactive shield spike on an INBOUND
  # attack hits the attacker). Those flares resolve their own creature
  # below, so we must NOT bail here just because the swing was
  # targetless - that dropped reactive-flare damage, wounds and
  # statuses entirely (they returned before the flare loop).
  creature = target[:id] ? Creature[target[:id].to_i] : nil
  if target[:id] && !creature
    respond "[Combat] No creature found for ID #{target[:id]}" if Tracker.debug?(:verbose)
  end
  # Nothing to apply at all: no swing creature AND no flare could name
  # one. (A targetless event with flares still falls through.)
  return if creature.nil? && (event[:flares] || []).all? { |f| f[:hits].empty? }

  respond "[Combat] Applying to #{creature.name} (#{target[:id]})" if creature && Tracker.debug?(:verbose)

  # Summary mode records what this event actually changed, per
  # creature - a flare can land on a different creature than the
  # swing, so damage/wounds/statuses are keyed by id rather than
  # summed together. nil when off, which is what makes the collector
  # calls in apply_crit/apply_secondary_wound/apply_crit_statuses
  # free in the normal path.
  @delta = Tracker.debug?(:summary) ? Hash.new { |h, k| h[k] = { creature: nil, damage: 0, wounds: [], statuses: [] } } : nil

  # Apply direct damage.
  #
  # Damage for EVERY hit lands before any crit is applied - the two
  # passes are deliberate, not an artifact of the old parallel
  # arrays. Interleaving them would reorder the observer emits a
  # subscriber sees.
  total_damage = 0
  # Direct-hit application needs the swing's creature; skipped for a
  # targetless (inbound/self) parent, whose only creature-bound facts
  # are its reactive flares, handled in the flare loop below.
  if creature && Tracker.settings[:track_damage]
    event[:hits].each do |hit|
      damage = hit[:damage]
      creature.add_damage(damage)
      total_damage += damage
      Lich::Common::Events.emit('combat.damage', id: creature.id, name: creature.name,
                              attack: event[:name], amount: damage)
      record_delta(creature) { |d| d[:damage] += damage }
      respond "  +#{damage} damage" if Tracker.debug?(:verbose)
    end
  end

  # Apply critical wounds
  if creature && Tracker.settings[:track_wounds]
    event[:hits].each { |hit| apply_crit(creature, hit[:crit], event) if hit[:crit] }
  end

  # Flare damage/crits apply to the flare's own target when its
  # announce line named one (AoE flares can hit a different creature
  # than the swing), falling back to the swing's target.
  (event[:flares] || []).each do |flare|
    next if flare[:hits].empty?

    f_target = flare[:target_info] || target
    f_creature = f_target[:id] ? Creature[f_target[:id].to_i] : creature
    next unless f_creature

    if Tracker.settings[:track_damage]
      flare[:hits].each do |hit|
        damage = hit[:damage]
        f_creature.add_damage(damage)
        total_damage += damage
        Lich::Common::Events.emit('combat.damage', id: f_creature.id, name: f_creature.name,
                                attack: event[:name], flare: flare[:name], amount: damage)
        record_delta(f_creature) { |d| d[:damage] += damage }
        respond "  +#{damage} damage (flare: #{flare[:name]})" if Tracker.debug?(:verbose)
      end
    end

    if Tracker.settings[:track_wounds]
      flare[:hits].each { |hit| apply_crit(f_creature, hit[:crit], event, flare: flare[:name]) if hit[:crit] }
    end
  end

  # Status effects: crit-table-derived and message-derived, under
  # one gate so they can never drift onto different flags. Passing a
  # nil swing creature is fine - apply_crit_statuses skips the direct
  # hits and still applies each flare's crit statuses to its own
  # creature (a reactive flare on an inbound attack). Message-derived
  # statuses on event[:statuses] belong to the swing target, so they
  # only apply when that creature exists.
  if Tracker.settings[:track_statuses]
    apply_crit_statuses(creature, event)
    if creature
      event[:statuses].each do |status|
        creature.add_status(status)
        Lich::Common::Events.emit('combat.status', id: creature.id, name: creature.name,
                                status: status, action: :add)
        record_delta(creature) { |d| d[:statuses] << status }
        respond "  +status: #{status}" if Tracker.debug?(:verbose)
      end
    end
  end

  respond "  Total damage applied: #{total_damage}" if total_damage > 0 && Tracker.debug?(:verbose)
  emit_debug_summary(event)

  # Death detection (2026-09-07). Crit tables flag a FATAL crit, but a
  # creature that dies of hit-point loss, or to a coup de grace (no
  # damage line at all), printed only its creature-specific death
  # message - and nothing here emitted a death, so every such kill
  # stayed "alive" for recorders (real-feed: 9 mastodon deaths in a
  # hunt, 3 recorded). The universal signal is the room feed's
  # <crtrStatus dead="1"/>, already parsed onto the creature as
  # crtr_flag?(:dead). Watch every creature this event touched; the
  # sweep that emits ONE `dead` status when the flag turns on runs in
  # process() after the whole chunk's attacks have emitted.
  watch_for_death(target[:id])
  (event[:flares] || []).each { |f| watch_for_death(f.dig(:target_info, :id)) }
end

.position_recovered?(id, crit_line = nil) ⇒ Boolean

Returns a message stood the creature up AFTER this crit.

Parameters:

  • id (Integer, String, nil)
  • crit_line (Integer, nil) (defaults to: nil) —

    line the crit text sat on, when known

Returns:

  • (Boolean) —

    a message stood the creature up AFTER this crit



2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
# File 'documented/gemstone/combat/processor.rb', line 2073

def position_recovered?(id, crit_line = nil)
  return false unless id && @position_recovered

  recovered_at = @position_recovered[id.to_i]
  return false if recovered_at.nil?
  # No line on the crit: fall back to the old chunk-wide answer rather
  # than silently re-proning a creature the game stood up.
  return true if crit_line.nil?

  # Only a stand-up read AFTER the crit outranks it.
  recovered_at > crit_line
end

.process(chunk, at: nil, source: nil) ⇒ void

Note:

Calls must be serialized; production uses the ordered async worker

This method returns an undefined value.

Process a chunk of game lines for combat events. Parses the chunk into events, resolves their in-blob spawn-tree links (event-object refs -> stable per-chunk uids the recorder maps to row ids), stamps each with the chunk's server time, and emits them.

Parameters:

  • chunk (Array<String>) —

    game lines

  • at (Time, nil) (defaults to: nil) —

    server time for this chunk (from the chunk's <prompt time=>). Duration estimates are anchored to this rather than to parse time, which the async worker can lag under load.

  • source (Hash, nil) (defaults to: nil) —

    optional socket-ingestion context; invalid or absent metadata leaves events without verified source provenance



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
# File 'documented/gemstone/combat/processor.rb', line 145

def process(chunk, at: nil, source: nil)
  # Parse-phase fact emits (:status/:ucs/:spell_loss) queue up here
  # and go out AFTER this chunk's :attack emits - see emit_fact.
  @deferred_emits = []
  include_attack_events = attack_events_requested?
  events = parse_events(chunk, source: source, include_attack_events: include_attack_events)
  # Death sweep runs AFTER this chunk's attacks emit, never before:
  # the async worker lags the game stream, so the creature registry
  # already shows a death that THIS chunk's attack caused. Sweeping
  # first credited it to the previous attack (real-feed 2026-09-07:
  # the fatal shot's kill filed under the shot before it). A quiet
  # chunk still sweeps, so a room refresh that lands a chunk after
  # the death message is caught too.
  if events.empty?
    sweep_death_watch
    return
  end

  at ||= prompt_time(chunk) || Time.now
  # Resolve the in-blob spawn-tree links from event-object references
  # into stable per-chunk uids the recorder can map to row ids. Each
  # event gets a _uid; :root_uid/:parent_uid point at other events in
  # THIS chunk (or self for a root). A ref to an event not in the emit
  # set (should not happen) degrades to self-root / no-parent.
  uids = {}.compare_by_identity
  @observation_batch_id = (@observation_batch_id || 0) + 1
  events.each_with_index { |ev, i| uids[ev] = i }
  events.each_with_index do |event, i|
    event[:observation_batch] = { id: @observation_batch_id, index: i, size: events.length }.freeze
    event[:_uid] = i
    root = event[:root_ref]
    event[:root_uid] = root ? (uids[root] || i) : i
    parent = event[:parent_ref]
    event[:parent_uid] = parent ? uids[parent] : nil
    event.delete(:root_ref)
    event.delete(:parent_ref)
  end
  # Parse-phase status facts remember the event they rode (:_event,
  # an object ref). Resolve it to that event's _uid so the recorder
  # files the status under THAT attack, not under whatever attack it
  # emitted last: a creature's cast that interrupted our swing emits
  # after it, and the swing's blinds fell off the swing (hunt log
  # 2026-09-07 23:50, cloak of shadows).
  @deferred_emits&.each do |_, payload|
    ev = payload.delete(:_event)
    payload[:attack_uid] = uids[ev] if ev && uids.key?(ev)
  end
  events.each do |event|
    event[:at] = at
    persist_event(event, include_attack_events: include_attack_events)
  end
  sweep_death_watch

  respond "[Combat] Processed #{events.size} events" if Tracker.debug?(:verbose)
ensure
  flush_deferred_emits
end

.prompt_time(chunk) ⇒ Time?

Extracts the server timestamp from a chunk's tag.

Chunks are segmented on the prompt, so the last match is this chunk's own prompt.

The prompt stamp is the game SERVER's epoch, but every duration estimate downstream (stun expiry, status timestamps) is compared against local Time.now. XMLData tracks the skew between the two clocks for exactly this reason - a raw Time.at(server_epoch) on a machine 40s ahead of the server produces stun estimates that are already expired the moment they land.

Returns:

  • (Time, nil) —

    the chunk's prompt time expressed on the LOCAL clock, or nil when the chunk has no prompt.



269
270
271
272
273
274
275
276
277
# File 'documented/gemstone/combat/processor.rb', line 269

def prompt_time(chunk)
  chunk.reverse_each do |line|
    if (m = PROMPT_TIME_PATTERN.match(line))
      offset = defined?(XMLData) ? XMLData.server_time_offset.to_f : 0.0
      return Time.at(m[1].to_i + offset)
    end
  end
  nil
end

.record_delta(creature) {|entry| ... } ⇒ Object

Records one change against a creature for :summary output.

No-op unless summary debug is on - @delta is nil in the normal path, so this costs a nil check per applied fact.

Yields:

  • (entry)


2157
2158
2159
2160
2161
2162
2163
# File 'documented/gemstone/combat/processor.rb', line 2157

def record_delta(creature)
  return unless @delta

  entry = @delta[creature.id]
  entry[:creature] ||= creature
  yield entry
end

.sweep_death_watch ⇒ Object

Emits :status dead (add) for any watched creature whose registry entry now reports the dead classification flag, once per creature.



2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
# File 'documented/gemstone/combat/processor.rb', line 2112

def sweep_death_watch
  return if @death_watch.nil? || @death_watch.empty?
  return unless defined?(Creature)

  @death_announced ||= {}
  @death_watch.keys.each do |id|
    creature = Creature[id]
    if creature.nil?
      @death_watch.delete(id) # left the registry - nothing to confirm
      next
    end
    if creature_dead?(creature)
      @death_watch.delete(id)
      next if @death_announced.key?(id)

      @death_announced[id] = true
      @death_announced.shift if @death_announced.size > 1_000 # bound the memory
      Lich::Common::Events.emit('combat.status', id: creature.id, name: creature.name,
                              status: 'dead', action: :add)
      respond "[Combat] #{creature.name} (#{id}) confirmed dead" if Tracker.debug?(:verbose)
    end
  end
end

.watch_for_death(id) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Registers a creature for post-chunk death-state inspection.

After each chunk parses, sweep_death_watch checks all watched creatures against the live Creature registry to detect deaths that the chunk's attacks caused. This deferred watch allows death to be attributed to the attack that killed it, not to an earlier unrelated action (real-feed 2026-09-07: the fatal shot's kill was previously credited to the shot before it).

Maintains a FIFO bounded to DEATH_WATCH_MAX (256) entries; older creatures are dropped if the watch overflows.

Parameters:

  • id (Integer, String, nil) —

    the creature's exist ID; nil is ignored

See Also:

  • #sweep_death_watch


2101
2102
2103
2104
2105
2106
2107
2108
# File 'documented/gemstone/combat/processor.rb', line 2101

def watch_for_death(id)
  return unless id

  @death_watch ||= {}
  @death_watch.delete(id.to_i) # re-insert at the tail (most recent)
  @death_watch[id.to_i] = true
  @death_watch.shift while @death_watch.size > DEATH_WATCH_MAX
end