Class: Lich::Gemstone::Combat::Recorder

Inherits:
Object
  • Object
show all
Defined in:
documented/gemstone/combat/recorder.rb

Overview

Persists the combat observer event stream to SQLite for forensic analysis.

Maintains a seven-table relational schema that captures attacks, resolutions, flares, hits, and status changes within hunt sessions. Sessions are bounded by idle gaps (default 5 minutes without events) or explicit start/finish calls.

Thread-safe for concurrent record() calls on the AsyncProcessor worker thread and check_idle!/close calls from the script's own loop via internal mutex serialization.

Examples:

Auto-sessioned live recording

rec = Combat::Recorder.new('/tmp/combat.db', character: Char.name, idle_timeout: 300)
rec.subscribe!
loop { rec.check_idle!; sleep 1 }

Explicit sessions for replay

rec = Combat::Recorder.new('/tmp/combat.db')
rec.start_session(character: 'Nisugi', source: '/path/to/log.txt', at: t0)
# ... feed events via record() ...
rec.finish_session(at: t1)

See Also:

Constant Summary collapse

HANDLER_NAME =
'combat_recorder'
RECEIPT_PROTOCOL =

:recorded_attack is an optional post-commit observer receipt. Its recorder/session/attack IDs identify rows; :source retains validated ingestion context (nil for legacy/replay input). :database and :file_identity are trusted-local locators, not remote protocol data. Receipts neither enable recording nor prove an encounter is complete.

1
SCHEMA =

SQLite schema: seven-table relational schema for combat analytics.

Tables:

- sessions: one per hunt/replay, the recount unit
- creatures: subject registry per (session_id, exist_id)
- attacks: one row per :attack event; includes attribution flags (inbound/foreign_caster/unowned/orphan)
and spawn-tree links (root_attack_id/parent_attack_id/parent_confidence)
- resolutions: roll lines (AS/DS/CS/TD as printed values; d100 separate for deterministic margin)
- flares: one row per flare on an attack; hits/resolutions reference their flare
- hits: one row per damage fact with denormalized crit and creature info for join-free aggregation
- statuses: status add/remove stream (creature/self/ambient), spell losses, UCS facts;
attack-attributed when the emission falls inside that attack's window

Indexes optimize queries by session, creature, attack, and location.

See Also:

<<~SQL
  CREATE TABLE IF NOT EXISTS sessions (
    id          INTEGER PRIMARY KEY,
    character   TEXT,
    source      TEXT,
    started_at  REAL NOT NULL,
    ended_at    REAL
  );

  CREATE TABLE IF NOT EXISTS creatures (
    id          INTEGER PRIMARY KEY,
    session_id  INTEGER NOT NULL REFERENCES sessions(id),
    exist_id    INTEGER,
    noun        TEXT,
    name        TEXT,
    first_seen  REAL,
    last_seen   REAL,
    killed_at   REAL,
    killed_by_attack_id INTEGER,
    kill_credit TEXT,                             -- how killed_by_attack_id was chosen: 'crit' (fatal crit, ground truth) | 'window' (room-feed death inside an attack window) | 'last_own_hit' (no window: the last damaging attack on it was ours) | 'last_hit' (no window: the last damaging attack on it was someone else's) | NULL (unknown / pre-migration)
    UNIQUE (session_id, exist_id)
  );

  CREATE TABLE IF NOT EXISTS attacks (
    id          INTEGER PRIMARY KEY,
    session_id  INTEGER NOT NULL REFERENCES sessions(id),
    seq         INTEGER NOT NULL,             -- monotonic within session
    occurred_at REAL NOT NULL,
    name        TEXT NOT NULL,                -- def name (:unknown = orphan sink)
    parent      TEXT,                         -- spawned-cast lineage (flare name)
    parent_weapon TEXT,                       -- the weapon whose flare spawned it
    root_attack_id   INTEGER REFERENCES attacks(id), -- initiating shot of this blob's spawn tree (self for a root)
    parent_attack_id INTEGER REFERENCES attacks(id), -- immediate spawner, ONLY when asserted (blink bracket); NULL when ambiguous
    parent_confidence TEXT,                   -- 'bracket' (game-declared) | NULL (unproven); reserved: 'count'
    via         TEXT,                         -- gesture wrapper (:cast)
    creature_id INTEGER REFERENCES creatures(id),  -- NULL: inbound/self/foreign/orphan
    target_kind TEXT NOT NULL,                -- creature|self|foreign|none
    attacker    TEXT,                         -- inbound: who attacked us
    attacker_exist_id INTEGER,
    weapon      TEXT,
    outcome     TEXT,                         -- first outcome (miss/evade/warded/...)
    outcomes_all TEXT,                        -- comma-joined when >1
    aimed       INTEGER NOT NULL DEFAULT 0,
    ambush      INTEGER NOT NULL DEFAULT 0,
    attack_kind TEXT,                         -- named maneuver: 'waylay'/'ambush' (from hiding, also sets ambush=1) or 'reverse_strike' (parry reaction, ambush=0); NULL when not an ambush, or recorded before this column existed
    inbound     INTEGER NOT NULL DEFAULT 0,
    orphan      INTEGER NOT NULL DEFAULT 0,
    foreign_caster INTEGER NOT NULL DEFAULT 0, -- a nearby player's attack (observed, not ours)
    unowned     INTEGER NOT NULL DEFAULT 0,    -- effect tick, no owning cast: applied to creature, not our deal
    ours        INTEGER NOT NULL DEFAULT 0,    -- decided at write time: our own OUTBOUND attack - not inbound, not a nearby player's, not on a foreign target, not an unowned tick, not an orphan sink
    chunk_seq   INTEGER,                       -- the recorder's own count of chunks seen (monotonic for its lifetime): orders chunks that share a whole-second occurred_at, where hits.line_seq restarts
    redirected_from TEXT                       -- guardian redirect: noun of the creature we struck AT; the row's creature is the guardian that took it
  );
  CREATE INDEX IF NOT EXISTS idx_attacks_session ON attacks(session_id, seq);
  CREATE INDEX IF NOT EXISTS idx_attacks_creature ON attacks(creature_id);
  CREATE INDEX IF NOT EXISTS idx_attacks_name ON attacks(session_id, name);
  CREATE INDEX IF NOT EXISTS idx_attacks_root ON attacks(root_attack_id);

  -- attacker_stat/defender_stat/modifier by type:
  --   as_ds:  AS  / DS  / AvD      cs_td: CS  / TD  / CvA
  --   uaf_udf:UAF / UDF / MM       fear:  FS  / FD  / FvP
  --   smr/ssr/maneuver_roll/activation: NULLs + roll/bonus/penalty/result
  CREATE TABLE IF NOT EXISTS resolutions (
    id          INTEGER PRIMARY KEY,
    attack_id   INTEGER NOT NULL REFERENCES attacks(id),
    flare_id    INTEGER REFERENCES flares(id),   -- NULL = the attack's own roll
    seq         INTEGER NOT NULL,                -- order within the attack
    type        TEXT NOT NULL,
    attacker_stat INTEGER,
    defender_stat INTEGER,
    modifier    INTEGER,
    roll        INTEGER,                         -- the die, kept separate:
    bonus       INTEGER,                         -- result - roll = margin
    penalty     INTEGER,
    result      INTEGER,
    total       REAL                             -- UCS pre-MM total (fractional)
  );
  CREATE INDEX IF NOT EXISTS idx_resolutions_attack ON resolutions(attack_id);

  CREATE TABLE IF NOT EXISTS flares (
    id          INTEGER PRIMARY KEY,
    attack_id   INTEGER NOT NULL REFERENCES attacks(id),
    seq         INTEGER NOT NULL,
    name        TEXT NOT NULL,
    damaging    INTEGER NOT NULL DEFAULT 0,
    creature_id INTEGER REFERENCES creatures(id), -- AoE: may differ from swing
    weapon      TEXT,
    outcome     TEXT,
    ours        INTEGER NOT NULL DEFAULT 0     -- 2p flare (our item fired). On an INBOUND row ours=1 is our REACTIVE flare (shield spike, thorns); ours=0 there is the creature's own weapon proc striking us
  );
  CREATE INDEX IF NOT EXISTS idx_flares_attack ON flares(attack_id);
  CREATE INDEX IF NOT EXISTS idx_flares_name ON flares(name);

  CREATE TABLE IF NOT EXISTS hits (
    id          INTEGER PRIMARY KEY,
    attack_id   INTEGER NOT NULL REFERENCES attacks(id),
    flare_id    INTEGER REFERENCES flares(id),    -- NULL = attack's own damage
    session_id  INTEGER NOT NULL REFERENCES sessions(id),
    creature_id INTEGER REFERENCES creatures(id), -- NULL = inbound/self/orphan
    seq         INTEGER NOT NULL,
    damage      INTEGER NOT NULL,
    location    TEXT,                             -- CritRanks location
    body_part   TEXT,                             -- mapped injury-doll part
    crit_type   TEXT,
    crit_rank   INTEGER,                          -- CritRanks :rank (0-9): crit severity
    wound_rank  INTEGER,                          -- CritRanks :wound_rank (0-3): wound left on the creature
    fatal       INTEGER NOT NULL DEFAULT 0,
    amputated   INTEGER NOT NULL DEFAULT 0,
    secondary_location TEXT,
    secondary_rank     INTEGER,                   -- secondary wound severity (:wound_rank)
    line_seq    INTEGER                           -- feed position of the damage line within its chunk: COMBAT order. Row id is insertion order, which a released cast (emitted after its swing) breaks; attacks.occurred_at orders across chunks
  );
  CREATE INDEX IF NOT EXISTS idx_hits_attack ON hits(attack_id);
  CREATE INDEX IF NOT EXISTS idx_hits_creature ON hits(session_id, creature_id);
  CREATE INDEX IF NOT EXISTS idx_hits_location ON hits(location);
  CREATE INDEX IF NOT EXISTS idx_hits_crit ON hits(crit_rank);
  CREATE INDEX IF NOT EXISTS idx_hits_creature_only ON hits(creature_id);  -- per-creature damage subqueries (the composite needs session_id first)
  CREATE INDEX IF NOT EXISTS idx_hits_flare ON hits(flare_id);

  -- kind: status (action add/remove), stun (value=rounds),
  --       roundtime (value=seconds), spell_loss (spell/spell_name/cause),
  --       ucs (status=position/tierup/..., value=tier)
  CREATE TABLE IF NOT EXISTS statuses (
    id          INTEGER PRIMARY KEY,
    session_id  INTEGER NOT NULL REFERENCES sessions(id),
    creature_id INTEGER REFERENCES creatures(id), -- NULL = self or unresolved
    subject     TEXT,                             -- name as printed ('self' for us)
    attack_id   INTEGER REFERENCES attacks(id),   -- window attribution
    flare_id    INTEGER REFERENCES flares(id),    -- the flare it rode on (glowbark blind), else NULL
    occurred_at REAL NOT NULL,
    kind        TEXT NOT NULL,
    status      TEXT,
    action      TEXT,
    value       INTEGER,
    spell       INTEGER,
    spell_name  TEXT,
    cause       TEXT,
    source      TEXT                              -- 'direct' | 'window'
  );
  CREATE INDEX IF NOT EXISTS idx_statuses_creature ON statuses(session_id, creature_id);
  CREATE INDEX IF NOT EXISTS idx_statuses_attack ON statuses(attack_id);
SQL
STAT_KEYS =

parsed-resolution key -> generic column, per roll family

{ as: :attacker_stat, cs: :attacker_stat, uaf: :attacker_stat, fs: :attacker_stat,
ds: :defender_stat, td: :defender_stat, udf: :defender_stat, fd: :defender_stat,
avd: :modifier, cva: :modifier, mm: :modifier, fvp: :modifier, mods: :modifier,
roll: :roll, bonus: :bonus, penalty: :penalty, result: :result, total: :total }.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(db_path, character: nil, source: 'live', idle_timeout: nil) ⇒ Recorder

idle_timeout (seconds): enables auto-sessioning - a session opens on the first recorded event and closes once this long passes without one (see check_idle!). nil = explicit start_session/finish_session.



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'documented/gemstone/combat/recorder.rb', line 300

def initialize(db_path, character: nil, source: 'live', idle_timeout: nil)
  @db = SQLite3::Database.new(db_path)
  @receipt_path = File.realpath(db_path) if File.file?(db_path)
  stat = File.stat(@receipt_path) if @receipt_path
  @receipt_file = [stat.dev, stat.ino].freeze if stat
  @recorder_id = SecureRandom.hex(16).freeze
  @db.busy_timeout = 5_000
  @db.execute('PRAGMA journal_mode = WAL')
  @db.execute('PRAGMA synchronous = NORMAL')
  @db.execute_batch(SCHEMA)
  migrate!
  @seq = 0
  @open_attack = nil # { id:, creature_ids: Set, inbound: bool }
  @chunk_rows = {}   # per-chunk _uid -> attack row id, for spawn-tree links
  @chunk_flares = {} # per-chunk _uid -> [flare row ids], for status attack_uid/flare_seq
  @chunk_batch = nil # the processor's observation_batch id for the chunk above
  @pending_cache = nil      # creature-cache entries staged during a txn (see in_txn)
  @pending_chunk_rows = nil # chunk-row entries staged during a txn (see in_txn)
  @character = character
  @source = source
  @idle_timeout = idle_timeout
  # Session-finished hook (see on_session_finished / drain_finished_sessions).
  # Every close path funnels through finish_session_locked, which
  # queues the id; callbacks run OUTSIDE the mutex after the public
  # call that caused the close returns.
  @session_finished_callbacks = []
  @merged_stun_rows = Set.new # status ids that already absorbed their stun twin
  # Chunks seen by this recorder, counted at each chunk boundary
  # (a fresh per-chunk uid sequence). Persisted as attacks.chunk_seq
  # so two chunks inside the same prompt second still order.
  @chunk_seq = 0
  @finished_sessions = []
  @finished_to_notify = []
  @last_event_at = nil
  # record fires on the AsyncProcessor worker thread; check_idle!/close
  # are documented as driven from the consuming script's own periodic
  # loop. Both touch @db, so every public entry point serialises on one
  # non-reentrant mutex. Internal helpers that run while the lock is
  # already held (start_session/finish_session called from inside
  # record) must NOT re-acquire it - hence the unsynchronised _locked
  # variants below.
  @mutex = Mutex.new
end

Instance Attribute Details

#db ⇒ Object (readonly)

Returns the value of attribute db.



295
296
297
# File 'documented/gemstone/combat/recorder.rb', line 295

def db
  @db
end

#session_id ⇒ Object (readonly)

Returns the value of attribute session_id.



295
296
297
# File 'documented/gemstone/combat/recorder.rb', line 295

def session_id
  @session_id
end

Instance Method Details

#check_idle!(now = Time.now) ⇒ Object

Close the current session if the idle gap has elapsed - ended_at is the LAST EVENT's time, not now, so town time never pads a hunt. Cheap; call it from a periodic loop so a finished hunt closes even when no further event ever arrives.



508
509
510
511
512
# File 'documented/gemstone/combat/recorder.rb', line 508

def check_idle!(now = Time.now)
  result = @mutex.synchronize { check_idle_locked!(now) }
  notify_finished_sessions!
  result
end

#check_idle_locked!(now = Time.now) ⇒ 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.

Closes the current session if the idle timeout has elapsed, without acquiring the mutex.

Returns early if idle_timeout is nil (explicit sessions only), or if no session is open, or if insufficient time has passed since the last recorded event.

Parameters:

  • now (Time) (defaults to: Time.now) —

    the time to check against @last_event_at; defaults to Time.now



522
523
524
525
526
527
# File 'documented/gemstone/combat/recorder.rb', line 522

def check_idle_locked!(now = Time.now)
  return unless @idle_timeout && @session_id && @last_event_at
  return unless now - @last_event_at > @idle_timeout

  finish_session_locked(at: @last_event_at)
end

#close ⇒ Object

Finish any open session and release the database.



530
531
532
533
534
535
536
537
# File 'documented/gemstone/combat/recorder.rb', line 530

def close
  unsubscribe!
  @mutex.synchronize do
    finish_session_locked(at: @last_event_at || Time.now) if @session_id
    @db.close
  end
  notify_finished_sessions!
end

#drain_finished_sessions ⇒ Array<Integer>

Drainable alternative to the callback: every session id finished since the last drain, oldest first.

Returns:

  • (Array<Integer>)


426
427
428
429
430
431
432
# File 'documented/gemstone/combat/recorder.rb', line 426

def drain_finished_sessions
  @mutex.synchronize do
    ids = @finished_sessions.dup
    @finished_sessions.clear
    ids
  end
end

#finish_session(at: Time.now) ⇒ Integer?

Returns the id of the session just closed.

Returns:

  • (Integer, nil) —

    the id of the session just closed



405
406
407
408
409
# File 'documented/gemstone/combat/recorder.rb', line 405

def finish_session(at: Time.now)
  result = @mutex.synchronize { finish_session_locked(at: at) }
  notify_finished_sessions!
  result
end

#finish_session_locked(at: Time.now) ⇒ Integer?

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.

Closes the current session without acquiring the mutex; internal to record_locked and finish_session.

Updates the session row's ended_at, queues the session id for callback notification, saves a snapshot of the creature cache for trailing-fact detection, and clears the attack window and chunk maps. Returns nil if no session was open.

Parameters:

  • at (Time) (defaults to: Time.now) —

    session end timestamp (typically @last_event_at or Time.now)

Returns:

  • (Integer, nil) —

    the id of the session that was closed, or nil



461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
# File 'documented/gemstone/combat/recorder.rb', line 461

def finish_session_locked(at: Time.now)
  return unless @session_id

  @db.execute('UPDATE sessions SET ended_at = ? WHERE id = ?', [at.to_f, @session_id])
  finished = @session_id
  @finished_sessions << finished
  @finished_to_notify << finished
  # Remember what the closed session fought. A death confirmed by the
  # room feed can arrive after the idle gap has already closed the
  # hunt, and that kill belongs to THIS session's creature rows - see
  # trailing_fact? / reopen_closed_session_locked!.
  @closed_session = { id: finished, ended_at: at.to_f, cache: (@creature_cache || {}).dup }
  @session_id = nil
  @open_attack = nil
  # A closed session's rows are not addressable by the next session's
  # per-chunk uids. Leaving these populated let an event in the new
  # session resolve a uid to the OLD session's attack row (real db:
  # a status linked to the previous hunt's attack across an idle
  # timeout).
  @chunk_rows = {}
  @chunk_flares = {}
  @chunk_batch = nil
  finished
end

#foreign_event?(type, data) ⇒ Boolean

An event that is not ours: a nearby player's attack, a creature swinging at a third party, an orphan. Recorded for context inside a hunt, but it neither opens a session nor keeps one alive (2026-09-07: Tijay's cast in town opened "session 2" of a hunt that had ended).

A non-attack event is a bare fact (:status/:stun/:roundtime/ :spell_loss/:ucs) with no ownership flags of its own, so it cannot be judged on its own contents. It counts as ours when it is keyed to a creature THIS session already touched - see known_creature?. Blanket-treating every non-attack as foreign dropped the delayed room-feed death confirmation that sweep_death_watch exists to emit: a creature someone else finished minutes later reports dead as a bare :status long after our last swing, and with the session idled out that row (and the creature's killed_at) was lost outright.

Returns:

  • (Boolean)


574
575
576
577
578
# File 'documented/gemstone/combat/recorder.rb', line 574

def foreign_event?(type, data)
  return !known_creature?(data) unless type == :attack

  !!(data[:foreign_caster] || data[:foreign_target] || data[:unowned] || data[:_orphan])
end

#known_creature?(data) ⇒ Boolean

True when this event is keyed to a creature we have already recorded against - in the open session, or in the one the idle gap just closed (@closed_session, so a lagged death confirmation still finds its own hunt). A bystander's fact about a creature we never fought matches neither and stays foreign, opening nothing.

Returns:

  • (Boolean)


585
586
587
588
589
590
591
592
593
# File 'documented/gemstone/combat/recorder.rb', line 585

def known_creature?(data)
  exist_id = data[:id]
  return false unless exist_id

  key = exist_id.to_i
  return true if @creature_cache&.key?(key) || @pending_cache&.key?(key)

  !!@closed_session&.fetch(:cache, nil)&.key?(key)
end

#notify_finished_sessions! ⇒ 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.

Fires session-finished callbacks for all pending sessions outside the mutex.

Drains @finished_to_notify within the mutex, then invokes all registered callbacks (from #on_session_finished) with each session id. Runs after public methods (start_session, finish_session, check_idle!, close) return so callbacks never hold the recorder lock.



443
444
445
446
447
448
449
450
# File 'documented/gemstone/combat/recorder.rb', line 443

def notify_finished_sessions!
  ids = @mutex.synchronize do
    pending = @finished_to_notify.dup
    @finished_to_notify.clear
    pending
  end
  ids.each { |id| @session_finished_callbacks.each { |cb| cb.call(id) } }
end

#on_session_finished {|session_id| ... } ⇒ Object

Session-finished hook. Fires for EVERY close path - the idle poll (check_idle!), the next event's own idle check inside record, and close - so a subscriber sees each hunt end without polling. A session the idle gap closed and a trailing death then re-opened closes again later and fires again with the same id; dedupe if that matters. Callbacks run outside the recorder's mutex.

Yield Parameters:

  • session_id (Integer)


418
419
420
421
# File 'documented/gemstone/combat/recorder.rb', line 418

def on_session_finished(&blk)
  @session_finished_callbacks << blk
  self
end

#record(type, data) ⇒ Hash, ...

Persist one observer event. Attack events return and publish a frozen post-commit receipt; other event types preserve their existing return. Receipt delivery is optional and cannot roll back committed data.

Parameters:

  • type (Symbol) —

    observer event type

  • data (Hash) —

    observer event payload

Returns:

  • (Hash, Object, nil) —

    an attack receipt, or the existing result for non-attack events



547
548
549
550
551
552
553
554
555
556
557
# File 'documented/gemstone/combat/recorder.rb', line 547

def record(type, data)
  result = @mutex.synchronize { record_locked(type, data) }
  notify_finished_sessions!
  # Receipts name committed rows, never pending writes. Emit outside the
  # recorder lock so consumers may inspect the database without deadlock.
  # This is evidence only, not command ownership or a combat-complete flag.
  if type == :attack && result.is_a?(Hash) && result[:protocol] == RECEIPT_PROTOCOL
    Lich::Common::Events.emit('combat.recorded_attack', result)
  end
  result
end

#record_locked(type, data) ⇒ Hash, ...

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.

Persists one observer event without acquiring the mutex; internal to record().

Dispatches to record_attack for :attack events, or to record_status for :status/:stun/:roundtime/:spell_loss/:ucs events. Manages auto-sessioning: judges ownership before idle close, reopens closed sessions for trailing facts, opens a new session on the first owned event, and updates @last_event_at only for owned non-trailing events.

When idle_timeout is set, a nearby player's event, orphan, or bare fact about an unknown creature is foreign and neither opens nor keeps a session alive. A bare fact about a known creature is a trailing fact and does not extend the hunt's duration (ended_at stays at the last real attack).

Wraps database operations in exception handling; errors log via Lich.log or warn.

Parameters:

  • type (Symbol) —

    observer event type: :attack, :status, :stun, :roundtime, :spell_loss, or :ucs

  • data (Hash) —

    observer event payload

Returns:

  • (Hash, Object, nil) —

    the result of record_attack for attacks, or the existing result for other types



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

def record_locked(type, data)
  if @idle_timeout
    now = Time.now
    # Judge ownership BEFORE the idle close: check_idle_locked! ends
    # the session and start_session_locked wipes @creature_cache, so
    # asking afterwards would call every delayed fact foreign.
    ours = !foreign_event?(type, data)
    trailing = trailing_fact?(type, ours)
    # A trailing fact holds the open session rather than letting the
    # idle gap split it; if the gap already closed the hunt, re-open
    # that same session instead of starting a new one.
    check_idle_locked!(now) unless trailing && @session_id
    reopen_closed_session_locked! if trailing && !@session_id
    start_session_locked(character: @character, source: @source, at: now) if ours && !@session_id
    # A trailing fact does not extend the hunt: ended_at stays at the
    # last real attack, so town time never pads a session.
    @last_event_at = now if ours && !trailing
  end
  return unless @session_id

  case type
  when :attack then record_attack(data)
  when :status then record_status(kind: 'status', id: data[:id], name: data[:name],
                                  status: data[:status].to_s, action: data[:action].to_s,
                                  flare_seq: data[:flare_seq], attack_uid: data[:attack_uid])
  when :stun then record_status(kind: 'stun', id: data[:id], name: data[:name],
                                status: 'stunned', action: 'add', value: data[:rounds].to_i)
  when :roundtime then record_status(kind: 'roundtime', id: data[:id], name: data[:name],
                                     status: 'roundtime', action: 'add', value: data[:seconds].to_i)
  when :spell_loss then record_status(kind: 'spell_loss', id: data[:id], name: data[:name],
                                      action: 'remove', spell: data[:spell],
                                      spell_name: data[:spell_name], cause: data[:cause]&.to_s)
  when :ucs then record_status(kind: 'ucs', id: data[:id], name: data[:name],
                               status: data[:kind].to_s,
                               value: ucs_value(data))
  end
rescue StandardError => e
  # Never raise into the processor; surfaced via Lich.log when present.
  msg = "CombatRecorder #{type}: #{e.message}"
  defined?(Lich) && Lich.respond_to?(:log) ? Lich.log("error: #{msg}") : warn(msg)
end

#reopen_closed_session_locked! ⇒ Object

Re-open the session the idle gap just closed so a trailing fact files against its rows. ended_at is left where finish_session_locked put it - the last real attack - and re-stamped on the next close, so a lagged death never pads the hunt's duration.



606
607
608
609
610
611
612
613
614
615
616
617
618
# File 'documented/gemstone/combat/recorder.rb', line 606

def reopen_closed_session_locked!
  return false unless @closed_session

  @session_id = @closed_session[:id]
  # Re-stamped by the next finish_session_locked, which closes at
  # @last_event_at - untouched by a trailing fact, so ended_at comes
  # back to the last real attack.
  @db.execute('UPDATE sessions SET ended_at = NULL WHERE id = ?', [@session_id])
  # Restore the cache so the trailing fact resolves to the creature
  # row the attack wrote, instead of inserting a duplicate.
  @creature_cache = @closed_session[:cache].dup
  true
end

#start_session(character: nil, source: nil, at: Time.now) ⇒ Integer

Starts a new session (hunt) with optional character and source metadata.

Acquires the internal mutex before calling start_session_locked, ensuring thread-safe initialization when called concurrently with record(). Closes any existing session first.

Examples:

Start a session for explicit replay

rec.start_session(character: 'Nisugi', source: '/var/log/combat.txt', at: Time.at(1000))

Parameters:

  • character (String, nil) (defaults to: nil) —

    the player name; defaults to @character from initialize

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

    replay log path or 'live'; defaults to @source from initialize

  • at (Time) (defaults to: Time.now) —

    session start time; defaults to Time.now

Returns:

  • (Integer) —

    the id of the newly created session



357
358
359
# File 'documented/gemstone/combat/recorder.rb', line 357

def start_session(character: nil, source: nil, at: Time.now)
  @mutex.synchronize { start_session_locked(character: character, source: source, at: at) }
end

#start_session_locked(character: nil, source: nil, at: Time.now) ⇒ Integer

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.

Opens a session without acquiring the mutex; internal to record_locked and start_session.

Closes any currently open session, inserts a sessions row, and initializes the creature cache. Resets the attack sequence counter.

Parameters:

  • character (String, nil) (defaults to: nil) —

    the player name

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

    replay log path or event source identifier

  • at (Time) (defaults to: Time.now) —

    session start timestamp

Returns:

  • (Integer) —

    the id of the newly created session



393
394
395
396
397
398
399
400
401
402
# File 'documented/gemstone/combat/recorder.rb', line 393

def start_session_locked(character: nil, source: nil, at: Time.now)
  finish_session_locked if @session_id
  @db.execute('INSERT INTO sessions (character, source, started_at) VALUES (?, ?, ?)',
              [txt(character), txt(source), at.to_f])
  @session_id = @db.last_insert_row_id
  @seq = 0
  @creature_cache = {}
  @closed_session = nil # a new hunt: the previous one takes no more facts
  @session_id
end

#subscribe! ⇒ Object

Hook the live observer feed. Idempotent via the named-handler contract; per the Events subscriber contract the callback stays cheap (single WAL transaction) and never sends game commands.



489
490
491
492
493
494
# File 'documented/gemstone/combat/recorder.rb', line 489

def subscribe!
  topics = %w[attack status stun roundtime spell_loss ucs].map { |t| "combat.#{t}" }
  Lich::Common::Events.on(*topics, name: HANDLER_NAME) do |topic, data|
    record(topic.delete_prefix('combat.').to_sym, data)
  end
end

#trailing_fact?(type, ours) ⇒ Boolean

A bare fact (not an :attack) about a creature we fought. It belongs to the hunt that fought it, so it must never open a fresh session: killed_at has to land on the creature row the attack already wrote.

Returns:

  • (Boolean)


598
599
600
# File 'documented/gemstone/combat/recorder.rb', line 598

def trailing_fact?(type, ours)
  ours && type != :attack
end

#txt(value) ⇒ Object

Text from the game stream arrives as ASCII-8BIT (binary) strings, and the sqlite3 gem binds a binary string as a BLOB. Every noun, creature name, attacker and weapon was landing typed blob (real db 2026-09-07: creatures.noun blob=196, text=0), so WHERE noun = 'berserker' never matched and text functions saw bytes, not words. Re-tag as UTF-8 at the boundary; game text is ASCII/Latin-1 so scrub only guards junk. Whitespace is normalised here too. A creature revealed from hiding sometimes arrives with a space injected into BOTH attributes of its link - real line 2026-09-11: noun=" rogue" name="human rogue", the same creature being plain "rogue"/"human rogue" on its other 34 mentions. The game sends it; it is intermittent, and the reveal line is never trustworthy. Untouched, " rogue" is a noun distinct from "rogue" and the creature reports as its own kind forever.



374
375
376
377
378
379
380
381
# File 'documented/gemstone/combat/recorder.rb', line 374

def txt(value)
  return nil if value.nil?

  s = value.to_s
  s = s.dup.force_encoding('UTF-8').scrub('?') if s.encoding == Encoding::ASCII_8BIT
  s = s.strip.squeeze(' ')
  s.empty? ? nil : s
end

#unsubscribe! ⇒ 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.

Unregisters the named combat event handler from the live observer feed.



500
501
502
# File 'documented/gemstone/combat/recorder.rb', line 500

def unsubscribe!
  Lich::Common::Events.off(HANDLER_NAME)
end