22 Commits

Author SHA1 Message Date
52ff8cb3fe docs: add CHANGELOG.md with v0.1.0 entry
Some checks failed
Tests / Run tests on PHP v8.4 (push) Failing after 1s
Tests / Run tests on PHP v8.5 (push) Failing after 1s
Keep-a-Changelog format, dated 2026-05-01, sections Added / Changed /
Deferred. Captures the framework rename to IndifferentKetchup\Codex\*
(Aternos namespace fully removed in 66a2fcc, MIT LICENSE preserves
original copyright), the components-outer-with-game-suffix layout
(option 1 from the Phase A Q3 decision, not option 3), the package
name indifferentketchup/codex, and the eight analysers shipped across
Phase B.1 / B.2 / B.3. Redactor utility, non-PZ games, and Packagist
publication land in Deferred.
2026-05-01 12:57:46 +00:00
1485507c8f docs: add Redactor utility design spec (deferred)
Forward-looking design for the codex-side PII redactor utility flagged
in Phase A Step E (Q5) and explicitly deferred from Phase B. Captures
the per-game redactor shape (RedactorInterface plus
ProjectZomboidRedactor under src/Util/), the rationale for not using
a single generic regex utility (PII detection is context-sensitive),
the replacement conventions that match the synthetic fixture
placeholders, the regex anchor shapes, and the open questions for v1
vs v2.

Status: deferred. Not implemented in this commit. The spec exists so
iblogs's upload-time PII story has a referenced design to point at,
and so a future implementation pass has a clear contract to start
from.
2026-05-01 12:54:57 +00:00
ed920485dc docs: backfill Phase B.3 spec and plan
Retroactive design + plan documentation for Phase B.3 (deferred
analysers requiring custom Analyser subclasses for cross-entry and
threshold logic). Records the architectural shift away from vanilla
PatternAnalyser, the threshold constant rationale (event-pairing /
sliding-window / consecutive-snapshot deltas), and the synthetic
fixture extensions that exercise both trigger and non-trigger paths.
Plan is as-built with checkboxes pre-checked and SHAs referenced.
2026-05-01 12:53:32 +00:00
b99d8f3061 docs: backfill Phase B.2 spec and plan
Retroactive design + plan documentation for Phase B.2 (PvP combat
detection plus six admin verb-dispatch insight classes), reconstructed
from chat history and git log. Mirrors the shape of the existing
Phase B.1 docs. Plan is as-built with checkboxes pre-checked and
commit SHAs referenced inline; Deviations section captures the
90c85a0 brace-fix interlude.
2026-05-01 12:51:26 +00:00
38fa1471ba Expand README with worked example and architecture overview
Some checks failed
Tests / Run tests on PHP v8.4 (push) Failing after 1s
Tests / Run tests on PHP v8.5 (push) Failing after 1s
Replaces the four-line stub with a usable landing page: install line,
end-to-end PHP example showing how a caller goes from a log file to
analysed insights, sample (placeholder-laden) output, a one-diagram
architecture summary, and a per-game support table. Sends interested
readers to CLAUDE.md for the extension guide and developer setup so
this file stays focused on consumers.

The example uses Project Zomboid because that is the in-tree reference
implementation. Output is illustrated with placeholder identifiers
(<hash>, <mod_id>, <missing>) rather than copied real-log content.
2026-05-01 05:41:36 +00:00
1cdc78c54c Refresh CLAUDE.md for Phase B.3 analyser additions
Some checks failed
Tests / Run tests on PHP v8.4 (push) Failing after 1s
Tests / Run tests on PHP v8.5 (push) Failing after 0s
The framework architecture section claimed PatternAnalyser was the
sole analysis surface; Phase B.3 introduced three custom Analyser
subclasses (ConnectionFailureAnalyser, ItemDuplicationAnalyser,
SkillProgressionAnomalyAnalyser) for cross-entry and threshold logic
that PatternAnalyser cannot express. Add a new bullet explaining when
to extend Analyser directly, plus an enumeration of which Log subclass
returns which kind of analyser from getDefaultAnalyser().

Also bumps the ProjectZomboid summary line from "11 log subclasses,
11 pattern classes" to include the analyser surface (12 Insight
classes plus 3 Analyser subclasses).
2026-05-01 05:36:51 +00:00
60f12bc868 Replace deprecated ::set-output with GITHUB_OUTPUT
GitHub deprecated the ::set-output workflow command in 2022 and the
runners now emit warnings on every CI run. Switch to writing the
'name=value' line into the file pointed to by \$GITHUB_OUTPUT, which is
the documented modern equivalent. The downstream cache step already
references steps.composer-cache.outputs.dir, no other change needed.
2026-05-01 05:35:57 +00:00
0c90e40a28 Add SkillProgressionAnomalyAnalyser
Some checks failed
Tests / Run tests on PHP v8.4 (push) Failing after 1s
Tests / Run tests on PHP v8.5 (push) Failing after 0s
Compares consecutive perks-snapshot rows per Steam ID and emits a
SkillProgressionAnomalyProblem for any single skill whose level gained
more than THRESHOLD_DELTA between two snapshots. Login/Logout/LevelUp
event rows are skipped via a perk-pair regex check on the bracketed
event field.

Threshold of 3 reflects PZ's slow leveling pace: typical session bridges
should not produce four-or-more level jumps in a single skill. The
constant is documented inline so operators can tune for modded XP
servers without touching analysis logic.

Synthetic fixture extended with a PlayerSuspect Steam ID carrying two
snapshots: Strength jumps 2 -> 10 (delta +8, triggers), Fitness jumps
2 -> 8 (+6, triggers), Maintenance jumps 0 -> 3 (+3, exactly at
threshold, does NOT trigger). The existing single-snapshot players
remain noise-free.
2026-04-30 22:43:44 +00:00
ba3fae8736 Add ItemDuplicationAnalyser
Sliding-window heuristic over (Steam ID, item code) groups: any window of
THRESHOLD_WINDOW_SECONDS containing THRESHOLD_COUNT or more positive-delta
events for the same player/item pair triggers a Problem. Negative deltas
(drops, transfers out) are filtered. Five events in ten seconds (defaults)
encodes the rule of thumb that legitimate gameplay rarely produces five
identical items in that span.

Constants live as class constants on the analyser so operators can
override via subclass without touching analysis logic; the docblocks
record the justification.

Synthetic fixture extended with a 6-event burst (AdminUser +
Base.Bullets9mm in <1s) and a 4-event sub-threshold group (Player1 +
Base.Plank scattered over 4 minutes) to exercise both paths.
2026-04-30 22:41:36 +00:00
73e9ca6181 Add ConnectionFailureAnalyser
First custom Analyser subclass in this game tree. PatternAnalyser
operates per-entry without cross-entry state, so pairing
'attempting to join' with 'allowed to join' per Steam ID requires a
bespoke pass over the log. The analyser counts attempts and allowed
events per Steam ID and emits a ConnectionFailureProblem for each
player whose attempt count exceeds their allowed count. Unmatched
'attempting to join used queue' rows are surfaced as failures in v1
because a long queue wait is indistinguishable from a real failure
without timing context.
2026-04-30 22:39:13 +00:00
c444e8543b pre-phase-B.3 checkpoint 2026-04-30 22:38:00 +00:00
c57d646229 Wire ProjectZomboidAdminLog default analyser
Some checks failed
Tests / Run tests on PHP v8.4 (push) Failing after 1s
Tests / Run tests on PHP v8.5 (push) Failing after 1s
2026-04-30 21:48:31 +00:00
51eb2de282 Wire ProjectZomboidPvpLog default analyser 2026-04-30 21:47:51 +00:00
d15fc81f9f Add AdminTeleportedInformation insight 2026-04-30 21:47:14 +00:00
64641fa8e8 Add AdminReloadedOptionsInformation insight 2026-04-30 21:46:47 +00:00
b7b89ef24e Add AdminChangedOptionInformation insight 2026-04-30 21:46:13 +00:00
caed04db10 Add AdminGrantedAccessInformation insight 2026-04-30 21:45:34 +00:00
a2faa551a1 Add AdminAddedXpInformation insight 2026-04-30 21:45:12 +00:00
0d85a05df3 Fix missing closing brace in AdminPattern
The previous commit's Edit replaced the TELEPORTED constant including its
trailing closing brace and forgot to add the brace back. Tests went red
with a ParseError. Restoring the brace.
2026-04-30 21:44:34 +00:00
90c85a052f Add AdminAddedItemInformation insight 2026-04-30 21:44:08 +00:00
55f769ca1e Add PvpDamageInformation insight 2026-04-30 21:43:24 +00:00
df62da1d6e pre-phase-B.2 checkpoint 2026-04-30 21:42:51 +00:00
46 changed files with 1963 additions and 14 deletions

View File

@@ -27,7 +27,7 @@ jobs:
- name: Set composer cache directory - name: Set composer cache directory
id: composer-cache id: composer-cache
run: echo "::set-output name=dir::$(composer config cache-files-dir)" run: echo "dir=$(composer config cache-files-dir)" >> "$GITHUB_OUTPUT"
- name: Restore composer from cache - name: Restore composer from cache
uses: actions/cache@v4 uses: actions/cache@v4

39
CHANGELOG.md Normal file
View File

@@ -0,0 +1,39 @@
# Changelog
All notable changes to `indifferentketchup/codex` are documented here.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.1.0] — 2026-05-01
First public release. Codex is a generic PHP log parsing and analysis framework with full Project Zomboid server-log support across eight analysers. The Composer package name is `indifferentketchup/codex` (the repository directory and Gitea slug are `ik-codex`; the package name is not).
### Added
- **Framework foundation** — generic `Log` / `Entry` / `Line` / `Parser` / `Analyser` / `Detective` / `Insight` pipeline forked from upstream `aternos/codex` and renamed end-to-end to `IndifferentKetchup\Codex\*` in `66a2fcc`. Zero `Aternos\Codex\*` namespace references remain in `src/` or `test/`.
- **`FilenameDetector`** at `IndifferentKetchup\Codex\Detective\FilenameDetector` — path-based detector that uses the new `LogFileInterface::getPath()` accessor to dispatch on a filename hint. Falls back to `false` for path-less log files (`StringLogFile`, `StreamLogFile`).
- **Project Zomboid log subclasses (11)** under `IndifferentKetchup\Codex\Log\ProjectZomboid\*` covering every PZ server-log file type: a multi-line `ProjectZomboidServerLog` for `DebugLog-server.txt`, an abstract `ProjectZomboidEventLog` base for the ten single-line logs, and concrete subclasses for `admin.txt`, `BurdJournals.txt`, `chat.txt`, `ClientActionLog.txt`, `cmd.txt`, `item.txt`, `map.txt`, `PerkLog.txt`, `pvp.txt`, `user.txt`.
- **Pattern classes (11)** under `IndifferentKetchup\Codex\Pattern\ProjectZomboid\*` holding regex string constants. Each `<Type>Pattern` carries a `LINE` regex used by `PatternParser`, plus named-group extractor regexes (`FIELDS`, `COMBAT`, `MOD_LOAD`, etc.) used by analysers.
- **`ProjectZomboidDetective`** at `IndifferentKetchup\Codex\Detective\ProjectZomboid\ProjectZomboidDetective` — pre-registers all 11 log subclasses in its constructor with paired filename-hint plus content-signature detectors.
- **Phase B.1 ServerLog analysers (3)**: `EngineVersionAnalyser` (extracts engine version, build hash, and build date from the server banner), `ModLoadAnalyser` (mod load order plus missing-mod problems with attached `ModMissingSolution`), `ServerExceptionAnalyser` (Java exception type and stack-trace body, coalesced by exception type).
- **Phase B.2 PvP and Admin analysers (2)**: `PvpDamageAnalyser` (filters zombie hits and zero-damage rows at the regex itself), `AdminAuditAnalyser` (verb-pattern dispatch across six admin actions: added item, added xp, granted access, changed option, reloaded options, teleported).
- **Phase B.3 deferred analysers (3)** — first custom `Analyser` subclasses in the tree, addressing logic that vanilla `PatternAnalyser` cannot express: `ConnectionFailureAnalyser` (event pairing across the file), `ItemDuplicationAnalyser` (sliding-window heuristic with `THRESHOLD_COUNT=5`, `THRESHOLD_WINDOW_SECONDS=10`), `SkillProgressionAnomalyAnalyser` (consecutive-snapshot delta with `THRESHOLD_DELTA=3`). All three threshold constants ship with rationale docblocks and are tunable via subclass override.
- **Synthetic test fixtures** under `test/src/Games/ProjectZomboid/fixtures/`, hand-crafted from observed PZ log shapes with placeholder identifiers per the project's privacy rules: Steam IDs `76561198000000001``76561198000000004`, names `Player1` / `Player2` / `AdminUser` / `PlayerSuspect`, generic coords. No real-log content reaches the index.
- **End-to-end tests** validating each Log subclass's parser, each analyser's insight emission, and the Detective's dispatch behaviour against the synthetic fixtures. Final count: **195 tests, 412 assertions**.
- **Project documentation**: `CLAUDE.md` with framework architecture, pitfalls, and workflow conventions; `README.md` with worked Project Zomboid example and per-game support table; design specs and as-built plans for Phase B.1 / B.2 / B.3 plus a deferred-status spec for the codex `Redactor` utility, all under `docs/superpowers/`.
### Changed
- **Layout: components-outer with game suffix.** Every game's code lives at `IndifferentKetchup\Codex\<Component>\<Game>\*` for the existing components (`Analyser`, `Analysis`, `Detective`, `Log`, `Parser`, `Pattern`). This is option 1 from the Phase A Step 2 layout decision; option 3 (a flat `IndifferentKetchup\Codex\Games\<Game>\*` tree) was originally proposed and was **not** selected.
- **`LICENSE`** retains the original `Copyright (c) 2019-2026 Aternos GmbH` line per MIT requirements; the LICENSE file is byte-for-byte unchanged from the upstream import.
- **`composer.json`** rewritten in `aae016d`: package name `indifferentketchup/codex`, MIT license, generic-framework description, single author entry, PSR-4 autoload roots set to `IndifferentKetchup\Codex\` and the test-fixture / test-suite namespaces, PHP `>=8.4` require constraint, PHPUnit `^12` dev dependency.
- **`tests.yaml`** uses the modern `$GITHUB_OUTPUT` workflow command instead of the deprecated `::set-output` (commit `60f12bc`). CI matrix runs PHP 8.4 and 8.5.
- **`.gitignore`** excludes `Logs.zip` (real production log fixtures) and `.scratch/` (extracted reference logs), plus `.claude/` and `.claude.local.md` for personal Claude Code artefacts.
### Deferred
- **Codex `Redactor` utility** — design captured in `docs/superpowers/specs/2026-04-30-redactor-design.md`. Not implemented in v0.1.0. iblogs (the downstream consumer) handles upload-time PII filtering for this release; codex itself ships no PII helper. The deferred spec exists so iblogs's privacy story has a referenced design to point at and so a future implementation pass has a clear contract to start from.
- **Other game implementations** — `Minecraft`, `Hytale`, and `SevenDaysToDie` are detective-stub-only. Each has a TODO `<Game>Detective` extending base `Detective`; their per-component subdirectories under `Analyser`, `Log`, `Parser`, and `Pattern` contain only `.gitkeep` placeholders. Real implementations land if and when fixtures and demand exist.
- **Packagist publication** — v0.1.0 is consumable via Composer's `vcs` repository entry pointing at the Gitea remote. Pushing to Packagist is a separate decision and is not in scope for this release.
[0.1.0]: https://git.indifferentketchup.com/indifferentketchup/ik-codex/releases/tag/v0.1.0

View File

@@ -48,6 +48,7 @@ Analysis of Insight[]
- **`Detective`** ranks candidate Log subclasses by running each candidate's `getDetectors()` and picking the highest-scoring result (`bool|float`). It receives a `LogFile`, returns a constructed `Log` subclass. - **`Detective`** ranks candidate Log subclasses by running each candidate's `getDetectors()` and picking the highest-scoring result (`bool|float`). It receives a `LogFile`, returns a constructed `Log` subclass.
- **`PatternParser`** is regex-driven. Lines that don't match the LINE regex append to the previous `Entry` — this is the mechanism that handles multi-line records like Java stack traces under an ERROR header. - **`PatternParser`** is regex-driven. Lines that don't match the LINE regex append to the previous `Entry` — this is the mechanism that handles multi-line records like Java stack traces under an ERROR header.
- **`PatternAnalyser`** walks entries, runs each registered insight class's static `getPatterns()` against entry text via `preg_match_all`, and emits coalesced insights (equal insights bump a counter instead of duplicating). - **`PatternAnalyser`** walks entries, runs each registered insight class's static `getPatterns()` against entry text via `preg_match_all`, and emits coalesced insights (equal insights bump a counter instead of duplicating).
- **Custom `Analyser` subclasses** are the right move when analysis needs cross-entry state — pairing events, sliding-window thresholds, comparing consecutive snapshots. `PatternAnalyser` operates per-entry only and can't express those. Phase B.3 (`ConnectionFailureAnalyser`, `ItemDuplicationAnalyser`, `SkillProgressionAnomalyAnalyser`) shows the shape: extend `Analyser`, override `analyse()`, walk `$this->log` once, aggregate, then emit coalesced `Problem`/`Information` insights at the end. Tunable thresholds belong as `public const` constants on the subclass with the rationale in a docblock.
- Detectors available out of the box: `SinglePatternDetector`, `WeightedSinglePatternDetector`, `LinePatternDetector` (returns match ratio), `MultiPatternDetector` (AND), and the path-based `FilenameDetector` (uses `LogFileInterface::getPath()`, returns `false` when no path is available). - Detectors available out of the box: `SinglePatternDetector`, `WeightedSinglePatternDetector`, `LinePatternDetector` (returns match ratio), `MultiPatternDetector` (AND), and the path-based `FilenameDetector` (uses `LogFileInterface::getPath()`, returns `false` when no path is available).
## Game subtrees ## Game subtrees
@@ -61,7 +62,7 @@ test/tests/Games/<Game>/...
test/src/Games/<Game>/fixtures/<type>-minimal.txt (synthetic fixtures only) test/src/Games/<Game>/fixtures/<type>-minimal.txt (synthetic fixtures only)
``` ```
Scaffolded games: `Minecraft`, `Hytale`, `SevenDaysToDie` (stubs only — empty `.gitkeep`s plus a TODO `<Game>Detective` extending base `Detective`). `ProjectZomboid` is fully implemented (11 log subclasses, 11 pattern classes, detective wired with all 11, synthetic fixtures, dispatch tests). Scaffolded games: `Minecraft`, `Hytale`, `SevenDaysToDie` (stubs only — empty `.gitkeep`s plus a TODO `<Game>Detective` extending base `Detective`). `ProjectZomboid` is fully implemented: 11 log subclasses, 11 pattern classes, detective wired with all 11, synthetic fixtures, dispatch tests, plus the analyser surface — 12 `PatternAnalyser`-driven Insight classes under `src/Analysis/ProjectZomboid/` and 3 custom `Analyser` subclasses under `src/Analyser/ProjectZomboid/` for cross-entry / threshold logic.
`src/Pattern/` is **not a framework abstraction** — patterns are plain `string` class constants. Each `<Type>Pattern` typically holds a `LINE` constant for the parser plus named-group extractor constants (`FIELDS`, `COMBAT`, `MOD_LOAD`, etc.) for analysers. `src/Pattern/` is **not a framework abstraction** — patterns are plain `string` class constants. Each `<Type>Pattern` typically holds a `LINE` constant for the parser plus named-group extractor constants (`FIELDS`, `COMBAT`, `MOD_LOAD`, etc.) for analysers.
@@ -69,6 +70,10 @@ Scaffolded games: `Minecraft`, `Hytale`, `SevenDaysToDie` (stubs only — empty
- Two abstract bases: `ProjectZomboidLog` (`TIME_FORMAT = 'd-m-y H:i:s.v'`, UTC default, `makePatternParser()` helper) and `ProjectZomboidEventLog` (marker for the ten single-line logs; `ProjectZomboidServerLog` extends the parent directly because it permits multi-line entries). - Two abstract bases: `ProjectZomboidLog` (`TIME_FORMAT = 'd-m-y H:i:s.v'`, UTC default, `makePatternParser()` helper) and `ProjectZomboidEventLog` (marker for the ten single-line logs; `ProjectZomboidServerLog` extends the parent directly because it permits multi-line entries).
- `ProjectZomboidDetective::__construct()` pre-registers all 11 log classes — instantiate it and call `setLogFile(...)->detect()`. - `ProjectZomboidDetective::__construct()` pre-registers all 11 log classes — instantiate it and call `setLogFile(...)->detect()`.
- Each Log subclass's `getDefaultAnalyser()` returns one of:
- A custom `Analyser` subclass (cross-entry logic): `UserLog → ConnectionFailureAnalyser`, `ItemLog → ItemDuplicationAnalyser`, `PerkLog → SkillProgressionAnomalyAnalyser`.
- A configured `PatternAnalyser` (per-entry pattern matching): `ServerLog`, `PvpLog`, `AdminLog` register their respective Insight classes.
- An empty `PatternAnalyser` for logs with no analysers yet: `ChatLog`, `ClientActionLog`, `CmdLog`, `MapLog`, `BurdJournalsLog`. These are wiring stubs awaiting future analysis work.
### Standard test template for a Log subclass ### Standard test template for a Log subclass

View File

@@ -1,13 +1,97 @@
# IndifferentKetchup Codex # IndifferentKetchup Codex
A generic PHP log parsing and analysis framework. Provides interfaces and base implementations for reading log files, detecting log types, parsing entries into structured form, analysing them for problems and information, and printing results. Generic PHP log parsing and analysis framework. Reads a log file, detects which log type it is, parses entries (including multi-line records like Java stack traces), runs the type-specific analysers, and returns structured `Information` and `Problem` insights with attached `Solution`s where applicable.
## Installation Originally a fork of [`aternos/codex`](https://github.com/aternosorg/codex); the framework is intentionally game-agnostic. The reference implementation in this tree is Project Zomboid server logs.
## Install
``` ```
composer require indifferentketchup/codex composer require indifferentketchup/codex
``` ```
Requires PHP `>=8.4`. No third-party runtime dependencies.
## Quick start
Given a Project Zomboid `DebugLog-server.txt`:
```php
<?php
require __DIR__ . '/vendor/autoload.php';
use IndifferentKetchup\Codex\Detective\ProjectZomboid\ProjectZomboidDetective;
use IndifferentKetchup\Codex\Log\File\PathLogFile;
$detective = new ProjectZomboidDetective();
$detective->setLogFile(new PathLogFile('2026-04-30_14-00_DebugLog-server.txt'));
$log = $detective->detect();
$log->parse();
$analysis = $log->analyse();
echo $log->getTitle(), "\n\n";
foreach ($analysis->getInformation() as $info) {
echo "[INFO] ", $info->getMessage(), "\n";
}
foreach ($analysis->getProblems() as $problem) {
echo "[PROBLEM] ", $problem->getMessage(), "\n";
foreach ($problem->getSolutions() as $solution) {
echo " -> ", $solution->getMessage(), "\n";
}
}
```
For a session with mod issues and a server-side exception, output looks roughly like:
```
Project Zomboid Debug Server Log
[INFO] Engine version: 42.16.3 (build <hash>, <build date>)
[INFO] Mod loaded: <mod_id>
[INFO] Mod loaded: <other_mod_id>
[PROBLEM] Required mod "<missing>" not found.
-> Subscribe to mod "<missing>" or remove its ID from the Mods= line in serverconfig.ini.
[PROBLEM] Exception thrown: java.nio.file.NoSuchFileException
```
If the log content arrives without a filesystem path (clipboard paste, web upload, stream), use `StringLogFile` or `StreamLogFile` instead of `PathLogFile`. The detective falls back to content signatures when the filename hint is absent.
## Architecture
```
LogFile → Log → parse() → Entry[] of Line[] → analyse() → Analysis of Insight[]
└── Information | Problem(+Solutions)
```
- **`Detective`** ranks candidate `Log` subclasses by running each candidate's static `getDetectors()` and picking the highest-scoring result. Each game ships its own `<Game>Detective` that pre-registers its log classes.
- **`PatternParser`** is regex-driven; lines that don't match the entry-start regex append to the previous `Entry`, which is how multi-line records (Java stack traces, indented warnings) are kept intact.
- **Analysers** come in two flavours: configured `PatternAnalyser` instances for per-entry pattern matching, and custom subclasses of `Analyser` for cross-entry logic (pairing events, sliding-window thresholds, snapshot comparisons).
- **Insights** are either `Information` (label + value) or `Problem` (with attached `Solution`s). Equal insights coalesce via a counter, so repeated patterns don't produce duplicate output.
Patterns live as plain `string` constants under `src/Pattern/<Game>/` — there is no `PatternInterface`. Each game adds files under `src/<Component>/<Game>/` (components-outer, game-suffixed). Full extension guide and conventions in [`CLAUDE.md`](CLAUDE.md).
## Game support
| Game | State |
|---|---|
| Project Zomboid | Full: 11 log subclasses across all the file types a server emits; analysers covering engine version, mod loading, server exceptions, PvP combat, admin audit, connection failures, item duplication, skill progression anomalies |
| Minecraft | Stub only — `MinecraftDetective` skeleton, no log subclasses yet |
| Hytale | Stub only |
| Seven Days To Die | Stub only |
The framework itself is generic — adding a new game means writing the same shape of files Project Zomboid demonstrates, not modifying anything in `src/{Analyser,Analysis,Detective,Log,Parser,Printer,Pattern}/` outside the new game's subdirectory.
## Developing
`composer test` runs the suite. PHP and Composer are not required on the host — invocations wrap in the official `composer:latest` Docker image (PHP 8.5). See [`CLAUDE.md`](CLAUDE.md) for the wrapped command, file layout, and the workflow conventions used in this repo.
## Source ## Source
<https://git.indifferentketchup.com/indifferentketchup/ik-codex> <https://git.indifferentketchup.com/indifferentketchup/ik-codex>
## License
MIT — see [`LICENSE`](LICENSE).

View File

@@ -0,0 +1,74 @@
# ProjectZomboid Phase B.3 Deferred Analysers — As-Built Plan
> Retroactive: written 2026-05-01.
This document is a historical record of how Phase B.3 (the three deferred analysers from the original Step D candidate list) was implemented. The corresponding design spec is `docs/superpowers/specs/2026-04-30-pz-analysers-deferred-design.md`. The work is complete and merged to `master`; checkboxes are pre-checked.
**Goal:** Land three custom `Analyser` subclasses under `src/Analyser/ProjectZomboid/` (the first non-empty contents of that directory), three `Problem` subclasses under `src/Analysis/ProjectZomboid/`, threshold constants documented inline as `public const`, fixture extensions to exercise trigger and non-trigger paths, and e2e tests verifying the analysers' behaviour against the fixtures.
**Architecture:** Custom subclasses of the framework's abstract `Analyser`. Each overrides `analyse()` to walk `$this->log` once, aggregate cross-entry state, and emit coalesced `Problem` insights at the end. This is the first deviation from Phase B.1/B.2's vanilla-`PatternAnalyser` pattern; the reasoning is recorded in the design spec and in `CLAUDE.md`.
**Tech Stack:** PHP 8.4+, PHPUnit 12, Composer (root package: `indifferentketchup/codex`). PHP/Composer not installed on host — all command invocations wrap in `docker run --rm -v "$(pwd):/app" -w /app -u "$(id -u):$(id -g)" composer:latest …`.
---
## Tasks
### Task 0 — Pre-checkpoint
- [x] Empty checkpoint commit: `c444e85 pre-phase-B.3 checkpoint`
### Task 1 — `ConnectionFailureAnalyser` (UserLog)
Pairing logic: walk the log, count `attempting to join` and `allowed to join` events per Steam ID, emit a `ConnectionFailureProblem` for any Steam ID whose attempt count exceeds its allowed count.
- [x] Add `src/Analysis/ProjectZomboid/ConnectionFailureProblem.php` (Steam ID, player, unmatched count; `isEqual` coalesces by Steam ID)
- [x] Add `src/Analyser/ProjectZomboid/ConnectionFailureAnalyser.php` — first file in this directory; the `.gitkeep` placeholder is removed in this commit
- [x] Wire `ProjectZomboidUserLog::getDefaultAnalyser()` to return `new ConnectionFailureAnalyser()` and drop the now-unused `PatternAnalyser` import
- [x] Add `test/tests/Games/ProjectZomboid/Analyser/UserLogAnalysisTest.php` — asserts Player1 (`76561198000000001`) is flagged with `unmatchedAttempts == 1` and Player2 (`76561198000000002`) is not flagged
- [x] `composer test` green: 188 tests, 392 assertions
- [x] Commit: `73e9ca6 Add ConnectionFailureAnalyser`
Design note inside the analyser docblock: "attempting to join used queue" rows are surfaced as failures in v1 because a long queue wait is indistinguishable from a real failure without timing context. Tunable in v2 if false positives become noisy.
### Task 2 — `ItemDuplicationAnalyser` (ItemLog)
Sliding-window heuristic over `(steamid, item)` groups, restricted to positive-delta events. Negative-delta rows (drops/transfers) are filtered out.
- [x] Add `src/Analysis/ProjectZomboid/ItemDuplicationProblem.php` (Steam ID, player, item, event count; `isEqual` coalesces by `(steamid, item)`)
- [x] Add `src/Analyser/ProjectZomboid/ItemDuplicationAnalyser.php` with two threshold constants and rationale docblocks: `THRESHOLD_COUNT = 5`, `THRESHOLD_WINDOW_SECONDS = 10`
- [x] Wire `ProjectZomboidItemLog::getDefaultAnalyser()` to return `new ItemDuplicationAnalyser()`; drop unused `PatternAnalyser` import
- [x] Extend `test/src/Games/ProjectZomboid/fixtures/item-minimal.txt`: append 6 Bullets9mm events at sub-second timestamps `19:50:00.001``.006` for AdminUser (trigger), plus 4 Plank events scattered `20:00:00``20:03:00` for Player1 (sub-threshold)
- [x] Bump entry-count assertion in `ProjectZomboidItemLogTest::testParsesEachLineAsAnEntry`: 10 → 20
- [x] Add `test/tests/Games/ProjectZomboid/Analyser/ItemLogAnalysisTest.php` — asserts one `ItemDuplicationProblem` (AdminUser + Bullets9mm + 6 events), zero for the Plank group, and the threshold constants are positive
- [x] `composer test` green: 191 tests, 400 assertions
- [x] Commit: `ba3fae8 Add ItemDuplicationAnalyser`
Implementation note: the analyser uses a two-pointer sliding window per group, which is O(n) per group after the initial sort. `Entry::getTime()` returns integer Unix seconds (sub-second precision dropped); the burst events all collapse to the same Unix-second value so any positive window catches them.
### Task 3 — `SkillProgressionAnomalyAnalyser` (PerkLog)
Compare consecutive perks-snapshot rows per Steam ID; emit a problem for any single skill that gained more than `THRESHOLD_DELTA` levels between snapshots.
- [x] Add `src/Analysis/ProjectZomboid/SkillProgressionAnomalyProblem.php` (Steam ID, player, skill, fromLevel, toLevel, delta; `isEqual` coalesces by `(steamid, skill)`)
- [x] Add `src/Analyser/ProjectZomboid/SkillProgressionAnomalyAnalyser.php` with `THRESHOLD_DELTA = 3` and a rationale docblock about PZ's slow skill leveling
- [x] Wire `ProjectZomboidPerkLog::getDefaultAnalyser()` to return `new SkillProgressionAnomalyAnalyser()`; drop unused `PatternAnalyser` import
- [x] Extend `test/src/Games/ProjectZomboid/fixtures/perk-minimal.txt`: append PlayerSuspect (Steam ID `76561198000000004`) with two snapshots — Strength 2→10 (+8 trigger), Fitness 2→8 (+6 trigger), Maintenance 0→3 (+3 boundary, does not trigger because comparison is strict `>`)
- [x] Bump entry-count assertion in `ProjectZomboidPerkLogTest::testParsesEachLineAsAnEntry`: 6 → 10
- [x] Add `test/tests/Games/ProjectZomboid/Analyser/PerkLogAnalysisTest.php` — asserts exactly two problems for PlayerSuspect (Strength + Fitness, sorted), no problem for Maintenance, no problems for single-snapshot Player1/Player2, and the threshold constant is positive
- [x] `composer test` green: 195 tests, 412 assertions
- [x] Commit: `0c90e40 Add SkillProgressionAnomalyAnalyser`
Filtering note: the analyser skips event-token rows (`Login`, `Logout`, `LevelUp`) by checking that the bracketed event field contains a `Skill=N` pair via `PerkPattern::PERK_PAIR`. Only true perks-snapshot rows enter the comparison.
---
## Done condition (met)
After Task 3, `composer test` reports **195 tests, 412 assertions, all green** under PHPUnit 12.5.6 / PHP 8.5.5. All eight Step D candidate analysers (Phase B.1's three ServerLog + Phase B.2's seven PvP/Admin + Phase B.3's three deferred) are operational across their respective Log subclasses.
The directory `src/Analyser/ProjectZomboid/` now contains real code for the first time; its `.gitkeep` placeholder was removed in `73e9ca6`.
## Deviations from the original plan
None this phase. The 4-commit count and the per-analyser shape both match what was committed-to in chat before execution. No silent breakages, no missing closing braces. The only observation worth recording is that the planned commit count was inclusive of the pre-checkpoint, and the actual commit ordering matched the plan exactly.

View File

@@ -0,0 +1,116 @@
# ProjectZomboid Phase B.2 Analysers — As-Built Plan
> Retroactive: written 2026-05-01.
This document is a historical record of how Phase B.2 (PvP combat detection + admin verb dispatch) was implemented. The corresponding design spec is `docs/superpowers/specs/2026-04-30-pz-analysers-pvp-admin-design.md`. The work is complete and merged to `master`; checkboxes are pre-checked.
**Goal:** Land seven new `Information` insight classes (one for PvP combat, six for admin verbs) under `src/Analysis/ProjectZomboid/`, plus seven new pattern constants on `PvpPattern` / `AdminPattern`, then wire `ProjectZomboidPvpLog` and `ProjectZomboidAdminLog` default analysers to register them.
**Architecture:** Vanilla `PatternAnalyser` configured with the new insight classes. No custom `Analyser` subclasses (deferred to Phase B.3). `Entry::__toString()` joins lines with `\n`, but B.2 logs are single-line per entry so multi-line behaviour doesn't apply here.
**Tech Stack:** PHP 8.4+, PHPUnit 12, Composer (root package: `indifferentketchup/codex`). PHP/Composer not installed on host — all command invocations wrap in `docker run --rm -v "$(pwd):/app" -w /app -u "$(id -u):$(id -g)" composer:latest …`.
---
## Tasks
### Task 0 — Pre-checkpoint
- [x] Empty checkpoint commit: `df62da1 pre-phase-B.2 checkpoint`
### Task 1 — `PvpDamageInformation` + `PvpPattern::COMBAT_REAL`
- [x] Add `PvpPattern::COMBAT_REAL` constant (combat regex with negative lookahead on weapon and positive-non-zero damage clause)
- [x] Add `src/Analysis/ProjectZomboid/PvpDamageInformation.php`
- [x] Add `test/tests/Games/ProjectZomboid/Analysis/PvpDamageInformationTest.php` covering pattern shape, match extraction, and three rejection cases (zombie weapon, zero damage, negative damage)
- [x] `composer test` green: 167 tests, 343 assertions
- [x] Commit: `55f769c Add PvpDamageInformation insight`
### Task 2 — `AdminAddedItemInformation` + `AdminPattern::ADDED_ITEM_ENTRY`
- [x] Add `AdminPattern::ADDED_ITEM_ENTRY` constant (entry-anchored variant; the body-only `ADDED_ITEM` from Phase A stays in place)
- [x] Add `src/Analysis/ProjectZomboid/AdminAddedItemInformation.php`
- [x] Add `test/tests/Games/ProjectZomboid/Analysis/AdminAddedItemInformationTest.php`
- [x] Commit: `90c85a0 Add AdminAddedItemInformation insight`**see Deviations section below**
- [x] Forward-fix: `0d85a05 Fix missing closing brace in AdminPattern`
- [x] `composer test` green after forward-fix: 170 tests
### Task 3 — `AdminAddedXpInformation` + `ADDED_XP_ENTRY`
- [x] Add `AdminPattern::ADDED_XP_ENTRY` constant
- [x] Add `src/Analysis/ProjectZomboid/AdminAddedXpInformation.php`
- [x] Unit test
- [x] `composer test` green: 173 tests
- [x] Commit: `a2faa55 Add AdminAddedXpInformation insight`
### Task 4 — `AdminGrantedAccessInformation` + `GRANTED_ACCESS_ENTRY`
- [x] Add `AdminPattern::GRANTED_ACCESS_ENTRY` constant
- [x] Add `src/Analysis/ProjectZomboid/AdminGrantedAccessInformation.php`
- [x] Unit test
- [x] `composer test` green: 175 tests
- [x] Commit: `caed04d Add AdminGrantedAccessInformation insight`
### Task 5 — `AdminChangedOptionInformation` + `CHANGED_OPTION_ENTRY`
- [x] Add `AdminPattern::CHANGED_OPTION_ENTRY` constant
- [x] Add `src/Analysis/ProjectZomboid/AdminChangedOptionInformation.php`
- [x] Unit test
- [x] `composer test` green: 177 tests
- [x] Commit: `b7b89ef Add AdminChangedOptionInformation insight`
### Task 6 — `AdminReloadedOptionsInformation` + `RELOADED_OPTIONS_ENTRY`
- [x] Add `AdminPattern::RELOADED_OPTIONS_ENTRY` constant
- [x] Add `src/Analysis/ProjectZomboid/AdminReloadedOptionsInformation.php`
- [x] Unit test
- [x] `composer test` green: 179 tests
- [x] Commit: `64641fa Add AdminReloadedOptionsInformation insight`
### Task 7 — `AdminTeleportedInformation` + `TELEPORTED_ENTRY`
- [x] Add `AdminPattern::TELEPORTED_ENTRY` constant (handles negative Z for basement coordinates)
- [x] Add `src/Analysis/ProjectZomboid/AdminTeleportedInformation.php`
- [x] Unit test (positive and negative Z cases)
- [x] `composer test` green: 182 tests
- [x] Commit: `d15fc81 Add AdminTeleportedInformation insight`
### Task 8 — Wire `ProjectZomboidPvpLog::getDefaultAnalyser()`
- [x] Replace `return new PatternAnalyser();` with `(new PatternAnalyser())->addPossibleInsightClass(PvpDamageInformation::class)`
- [x] Add `test/tests/Games/ProjectZomboid/Analyser/PvpLogAnalysisTest.php` — asserts three real-PvP insights (Bare Hands, Tire Iron, Hunting Knife) and zero zombie/vehicle insights
- [x] `composer test` green: 184 tests
- [x] Commit: `51eb2de Wire ProjectZomboidPvpLog default analyser`
### Task 9 — Wire `ProjectZomboidAdminLog::getDefaultAnalyser()`
- [x] Register all six `Admin<Verb>Information` classes
- [x] Add `test/tests/Games/ProjectZomboid/Analyser/AdminLogAnalysisTest.php` — asserts the 2+2+2+2+1+2 distribution and confirms the duplicate ShotgunShells row coalesces with `counter == 2`
- [x] `composer test` green: 186 tests
- [x] Commit: `c57d646 Wire ProjectZomboidAdminLog default analyser`
---
## Deviations from the original plan
### The `90c85a0` brace-fix interlude
Task 2's commit (`90c85a0 Add AdminAddedItemInformation insight`) shipped broken. While adding the first `_ENTRY` constant to `AdminPattern.php`, the `Edit` tool's `old_string` was `<TELEPORTED line>\n}` and the `new_string` included a docblock plus the new constant but **dropped the closing brace** of the class body. The commit was made before the test result was inspected, so it landed with a `ParseError: Unclosed '{'` and 9 cascading test errors.
Forward-fix `0d85a05 Fix missing closing brace in AdminPattern` restored the brace as a separate commit (per the `CLAUDE.md` workflow rule: "Always create new commits rather than amending"). The broken intermediate commit remains in history; force-pushing master to clean it would have cost more than the cosmetic gain.
The remaining five admin commits (Tasks 37) used a deliberate practice change: every subsequent `Edit` to `AdminPattern.php` included the closing `}` in both `old_string` and `new_string` so it couldn't be dropped again. No further breakage.
### Total commit count
11 commits vs the 10 originally outlined in the spec's planning section. The extra commit is the brace-fix.
### Test-count divergence note (now resolved)
When Phase B.1's plan was written I projected a final count of 158 tests for B.1; the actual landed count was 161 (off by 3 — Task 5's contribution wasn't summed in the plan footer). For B.2 the planned and actual per-step counts match exactly. No projection error this phase.
---
## Done condition (met)
After Task 9, `composer test` reports **186 tests, 387 assertions, all green** under PHPUnit 12.5.6 / PHP 8.5.5 (verified via the `composer:latest` Docker image). All five originally-planned analysers from the Step D Phase B scope (B.1's three plus B.2's two) are now operational on their respective Log subclasses.

View File

@@ -0,0 +1,117 @@
# ProjectZomboid analyser design (Phase B.3 — deferred analysers)
> Retroactive: written 2026-05-01.
## Summary
Add the three remaining Project Zomboid analysers from the original Step D candidate list — connection failure pairing, item duplication heuristic, and skill progression anomaly detection — by introducing custom `Analyser` subclasses under `src/Analyser/ProjectZomboid/`. These are the first analysers in the tree that cannot be expressed as configured `PatternAnalyser` instances; they require cross-entry state (event pairing, sliding windows, snapshot deltas) that `PatternAnalyser` does not provide.
This document covers Phase B.3. Phase B.1 / B.2 docs are at `2026-04-30-pz-analysers-design.md` / `2026-04-30-pz-analysers-pvp-admin-design.md`. With Phase B.3, the original eight-analyser candidate list from Step D is fully implemented.
## Scope
- **In scope:** `ConnectionFailureAnalyser` + `ConnectionFailureProblem` (UserLog, event pairing); `ItemDuplicationAnalyser` + `ItemDuplicationProblem` (ItemLog, sliding-window heuristic); `SkillProgressionAnomalyAnalyser` + `SkillProgressionAnomalyProblem` (PerkLog, consecutive-snapshot delta); wiring three Log subclasses' `getDefaultAnalyser()`; extending two synthetic fixtures to exercise trigger and non-trigger cases; end-to-end tests.
- **Out of scope (B.3):** the five other PZ logs whose `getDefaultAnalyser()` continues returning an empty `PatternAnalyser` stub (Chat, ClientAction, Cmd, Map, BurdJournals); the codex-side `Redactor` utility; Hytale / Minecraft / Seven Days To Die analysers; v0.1.0 release plumbing.
## Architectural shift: custom `Analyser` subclasses
Phases B.1 and B.2 established the convention that vanilla `PatternAnalyser` plus `Insight::isEqual()` coalescing is sufficient for per-entry pattern matching, and a custom Analyser subclass is **not** needed even for multi-line records (PatternParser's continuation-line behaviour combined with `Entry::__toString()` joins solves multi-line capture without subclassing).
Phase B.3's three analysers genuinely require cross-entry state:
- **ConnectionFailureAnalyser** must count `attempting to join` and `allowed to join` events per Steam ID and report unmatched attempts. PatternAnalyser dispatches each entry independently and has no mechanism to compare counts across entries.
- **ItemDuplicationAnalyser** must group positive-delta item events by `(steamid, item)` tuple and slide a fixed-second window across each group. Sliding-window logic spans multiple entries by definition.
- **SkillProgressionAnomalyAnalyser** must collect all perks-row snapshots per Steam ID, sort them by time, then compute pairwise deltas between consecutive snapshots. Pairwise comparison spans entries.
Each subclass extends the framework's abstract `Analyser`, overrides `analyse(): AnalysisInterface`, walks `$this->log` once to aggregate state, and emits `Problem` insights at the end. The CLAUDE.md "Framework architecture" section was updated alongside Phase B.3 to document this pattern.
## Components
Three `Analyser` subclasses under `src/Analyser/ProjectZomboid/` (the directory's `.gitkeep` placeholder is removed in this phase):
| Analyser | Target Log | Logic shape | Threshold constants |
|---|---|---|---|
| `ConnectionFailureAnalyser` | `ProjectZomboidUserLog` | Two-pass count of attempt vs allowed events per Steam ID; emits one Problem per Steam ID where attempts > allowed | None — strict pairing |
| `ItemDuplicationAnalyser` | `ProjectZomboidItemLog` | Sliding-window heuristic over `(steamid, item)` groups | `THRESHOLD_COUNT = 5`, `THRESHOLD_WINDOW_SECONDS = 10` |
| `SkillProgressionAnomalyAnalyser` | `ProjectZomboidPerkLog` | Consecutive-snapshot delta per `(steamid, skill)`; only positive-delta perks-row entries (Login/Logout/LevelUp event tokens are filtered out) | `THRESHOLD_DELTA = 3` |
Three `Problem` subclasses under `src/Analysis/ProjectZomboid/`:
| Problem | Coalescing |
|---|---|
| `ConnectionFailureProblem` | By Steam ID — one problem per player regardless of how many unmatched attempts |
| `ItemDuplicationProblem` | By `(steamid, item)` tuple — one problem per suspicious group |
| `SkillProgressionAnomalyProblem` | By `(steamid, skill)` — one problem per skill exceeding the delta threshold |
## Threshold rationale (recorded as docblocks)
The constants are first-pass heuristics expected to be tuned once production logs flow through codex. Each is documented inline in its analyser class:
- **`ItemDuplicationAnalyser::THRESHOLD_COUNT = 5`**: Five identical item gains in a fixed window. Legitimate gameplay rarely produces five identical items quickly — crafting has animation delays, looting is one-at-a-time, zombie drops are similarly serial. A burst of five suggests admin-spawn or exploit. Tune downward if false negatives appear.
- **`ItemDuplicationAnalyser::THRESHOLD_WINDOW_SECONDS = 10`**: Ten seconds covers a realistic burst-loot scenario (e.g. a crate full of identical items) without collapsing onto unrelated events. Combined with `THRESHOLD_COUNT` this means an effective rate of 0.5 same-item events per second.
- **`SkillProgressionAnomalyAnalyser::THRESHOLD_DELTA = 3`**: PZ skills require thousands of XP per level; even active grinding rarely produces four-or-more level jumps in a single session bridge. Set to 3 as baseline; modded XP servers may need to raise this via subclass override.
## Patterns
No new pattern constants. Existing constants from Phase A are reused inside the per-entry walks:
- `UserPattern::PLAYER_EVENT` — decode `[time] <steamid> "<player>" <event>` lines
- `ItemPattern::FIELDS` — decode `[time] <steamid> "<player>" <location> <delta> <coords> [<item>]` lines
- `PerkPattern::FIELDS` — decode the bracket-heavy perks log line
- `PerkPattern::PERK_PAIR` — extract individual `Skill=N` pairs from the perks-row event field
`Entry::getTime()` returns integer Unix seconds (sub-second precision is dropped by `DateTime::getTimestamp()`). For `ItemDuplicationAnalyser` this means events within the same second collapse to time-diff zero, which is acceptable for v1.
## Wiring
Three `getDefaultAnalyser()` overrides (each was previously `return new PatternAnalyser();`):
```php
// ProjectZomboidUserLog
return new ConnectionFailureAnalyser();
// ProjectZomboidItemLog
return new ItemDuplicationAnalyser();
// ProjectZomboidPerkLog
return new SkillProgressionAnomalyAnalyser();
```
The unused `PatternAnalyser` import is removed from each Log subclass.
## Test plan
End-to-end tests under `test/tests/Games/ProjectZomboid/Analyser/`, one per Log:
- **`UserLogAnalysisTest`** — drives `user-minimal.txt`. Asserts exactly one `ConnectionFailureProblem` for Player1 (Steam ID `76561198000000001`) with `unmatchedAttempts == 1` (Player1 has two `attempting to join` events, one of which is `attempting to join used queue`, and one `allowed to join`). Asserts that Player2 (matched 1+1) is not flagged.
- **`ItemLogAnalysisTest`** — drives the extended `item-minimal.txt`. Asserts one `ItemDuplicationProblem` for AdminUser + Base.Bullets9mm with `eventCount == 6`, and verifies the four-event Base.Plank group does not trigger. Also asserts the threshold constants are positive and documented.
- **`PerkLogAnalysisTest`** — drives the extended `perk-minimal.txt`. Asserts exactly two `SkillProgressionAnomalyProblem` insights for PlayerSuspect (Steam ID `76561198000000004`), one for Strength (delta +8) and one for Fitness (delta +6). Verifies that Maintenance (delta exactly +3) does not trigger because the comparison is strict `>`. Verifies that single-snapshot players (Player1, Player2) are not flagged. Asserts the threshold constant is positive and documented.
## Fixture changes
Two synthetic fixtures extended (no new files, no real-log content):
- **`item-minimal.txt`** — appended 10 lines: a 6-event Bullets9mm burst by AdminUser at sub-second timestamps `19:50:00.001``.006` (triggers the dupe heuristic), and a 4-event Plank group by Player1 scattered across 4 minutes (`20:00:00``20:03:00`, sub-threshold). The Phase A entry-count assertion in `ProjectZomboidItemLogTest` was bumped from 10 → 20.
- **`perk-minimal.txt`** — appended 4 lines: PlayerSuspect (Steam ID `76561198000000004`) with two perks snapshots — a low-stat baseline at `18:30:00.000` and an inflated set at `22:00:00.000` showing Strength 2→10, Fitness 2→8, and Maintenance 0→3 (boundary case). The Phase A entry-count assertion in `ProjectZomboidPerkLogTest` was bumped from 6 → 10.
All identifiers are placeholder per the Privacy / Fixture Rules in CLAUDE.md (`76561198000000001``76561198000000004` for Steam IDs, `Player1`/`Player2`/`AdminUser`/`PlayerSuspect` for names, coords in the `1000-1100, 2000-2200, 0` range).
## Commits (as-built, in order)
1. `c444e85``pre-phase-B.3 checkpoint` (`--allow-empty`)
2. `73e9ca6``Add ConnectionFailureAnalyser`
3. `ba3fae8``Add ItemDuplicationAnalyser`
4. `0c90e40``Add SkillProgressionAnomalyAnalyser`
4 commits total. Each non-checkpoint commit ships an Analyser + Problem + (optional) fixture extension + updated count assertion + e2e test in one logical unit, per the per-analyser commit shape requested up front.
## Open issues
None blocking. All three threshold constants are heuristic guesses pending production data calibration; tuning is expected once iblogs starts feeding real logs through codex. The values are tunable via subclass override and the rationale is in the source docblocks.
## Pointers
- Phase B.1 (foundation, ServerLog analysers): `2026-04-30-pz-analysers-design.md` and `2026-04-30-pz-analysers.md`.
- Phase B.2 (vanilla PatternAnalyser PvP/Admin coverage): `2026-04-30-pz-analysers-pvp-admin-design.md` and `2026-04-30-pz-analysers-pvp-admin.md`.
- Workflow conventions and architecture overview: `CLAUDE.md`.
- The Phase B.3 commit set begins at `c444e85` (pre-checkpoint) and ends at `0c90e40` (the third analyser).

View File

@@ -0,0 +1,106 @@
# ProjectZomboid analyser design (Phase B.2)
> Retroactive: written 2026-05-01.
## Summary
Add Project Zomboid PvP combat detection (filtering zombie hits and zero-damage events) and admin verb-dispatch coverage of six action types, by registering seven new `Information` insight classes onto the existing `PatternAnalyser`. No custom `Analyser` subclasses are introduced in this phase — all dispatch fits within `PatternAnalyser`'s per-entry pattern matching.
This document covers Phase B.2. Phase B.1 is in `2026-04-30-pz-analysers-design.md`. Phase B.3 (cross-entry / threshold analysers requiring custom `Analyser` subclasses) is in `2026-04-30-pz-analysers-deferred-design.md`.
## Scope
- **In scope:** `PvpDamageInformation` + `PvpPattern::COMBAT_REAL` regex; six `Admin<Verb>Information` classes + six `AdminPattern::<VERB>_ENTRY` regex constants; wiring `ProjectZomboidPvpLog::getDefaultAnalyser()` and `ProjectZomboidAdminLog::getDefaultAnalyser()`; end-to-end tests for both logs.
- **Out of scope (B.2):** any cross-entry / threshold / pairing logic (deferred to B.3); the eight other PZ logs whose `getDefaultAnalyser()` continues returning an empty `PatternAnalyser` stub; the codex-side `Redactor` utility (deferred — see `2026-04-30-redactor-design.md`).
## Architectural decision: vanilla PatternAnalyser
Phase B.1 established that `PatternAnalyser` plus `Insight::isEqual()` coalescing covers single-entry pattern matching cleanly. Phase B.2's analysers (PvP damage rows, admin verb lines) all fit that mould — each interesting line is independent of the others, dispatch is per-entry, and counter-coalescing handles repeats. No `Analyser` subclassing required. (Phase B.3 will deviate from this when cross-entry logic enters the picture.)
## Components
All under `src/Analysis/ProjectZomboid/`:
| Class | Type | Pattern | Coalescing |
|---|---|---|---|
| `PvpDamageInformation` | Information | `PvpPattern::COMBAT_REAL` | Default `Information::isEqual` (label + value) — same attacker/victim/weapon coalesces |
| `AdminAddedItemInformation` | Information | `AdminPattern::ADDED_ITEM_ENTRY` | Default — same admin/item/target coalesces |
| `AdminAddedXpInformation` | Information | `AdminPattern::ADDED_XP_ENTRY` | Default — same admin/amount/skill/target coalesces |
| `AdminGrantedAccessInformation` | Information | `AdminPattern::GRANTED_ACCESS_ENTRY` | Default — same admin/level/target coalesces |
| `AdminChangedOptionInformation` | Information | `AdminPattern::CHANGED_OPTION_ENTRY` | Default — same admin/option/value coalesces |
| `AdminReloadedOptionsInformation` | Information | `AdminPattern::RELOADED_OPTIONS_ENTRY` | Default — same admin coalesces |
| `AdminTeleportedInformation` | Information | `AdminPattern::TELEPORTED_ENTRY` | Default — same admin/target/coords coalesces |
## Patterns
Seven new constants total.
**`PvpPattern::COMBAT_REAL`** — combat regex with the noise filter baked in. The negative lookahead `(?!zombie")` rejects zombie weapon rows; the damage clause uses alternation to match only positive non-zero floats:
```
'/Combat: "(?<attacker>[^"]+)" \([^)]+\) hit "(?<victim>[^"]+)" \([^)]+\) weapon="(?<weapon>(?!zombie")[^"]+)" damage=(?<damage>0\.0*[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)/'
```
The damage alternation explicitly rejects `0.000000` and any leading-minus value because both branches require either `0.<non-zero>` or `<non-zero>.<digits>`.
**`AdminPattern::<VERB>_ENTRY`** — six entry-anchored variants of the existing body-only verb constants. Necessary because `PatternAnalyser` calls `preg_match_all` against the full Entry text (including the `[time]` prefix), so the Phase A verb constants anchored at `^<admin>` would never match. The Phase A constants stay intact for direct-message use; new ones live alongside them on the same `AdminPattern` class.
## Wiring
Two `getDefaultAnalyser()` overrides (was `return new PatternAnalyser();` for both):
```php
// ProjectZomboidPvpLog
return (new PatternAnalyser())
->addPossibleInsightClass(PvpDamageInformation::class);
```
```php
// ProjectZomboidAdminLog
return (new PatternAnalyser())
->addPossibleInsightClass(AdminAddedItemInformation::class)
->addPossibleInsightClass(AdminAddedXpInformation::class)
->addPossibleInsightClass(AdminGrantedAccessInformation::class)
->addPossibleInsightClass(AdminChangedOptionInformation::class)
->addPossibleInsightClass(AdminReloadedOptionsInformation::class)
->addPossibleInsightClass(AdminTeleportedInformation::class);
```
## Test plan
Unit tests under `test/tests/Games/ProjectZomboid/Analysis/`, one per Insight class — exercises `getPatterns()` shape, `setMatches()` extraction, and at least one filter-rejection case for `PvpDamageInformation` (zombie weapon and zero-damage rejection).
End-to-end tests under `test/tests/Games/ProjectZomboid/Analyser/`:
- `PvpLogAnalysisTest` against `pvp-minimal.txt`: asserts exactly three `PvpDamageInformation` insights (Bare Hands, Tire Iron (Worn), Hunting Knife). Zombie and vehicle rows must be filtered out by the regex.
- `AdminLogAnalysisTest` against `admin-minimal.txt`: asserts 2 + 2 + 2 + 2 + 1 + 2 = 11 insights across the six admin classes, with the duplicate ShotgunShells row coalescing into a single insight at `counter == 2`.
## Fixture changes
None. The Phase A synthetic fixtures `pvp-minimal.txt` and `admin-minimal.txt` already cover every code path Phase B.2 exercises.
## Commits (as-built, in order)
1. `df62da1``pre-phase-B.2 checkpoint` (`--allow-empty`)
2. `55f769c``Add PvpDamageInformation insight`
3. `90c85a0``Add AdminAddedItemInformation insight` ⚠️ broken — see `2026-04-30-pz-analysers-pvp-admin.md` §Deviations
4. `0d85a05``Fix missing closing brace in AdminPattern` (forward-fix for #3)
5. `a2faa55``Add AdminAddedXpInformation insight`
6. `caed04d``Add AdminGrantedAccessInformation insight`
7. `b7b89ef``Add AdminChangedOptionInformation insight`
8. `64641fa``Add AdminReloadedOptionsInformation insight`
9. `d15fc81``Add AdminTeleportedInformation insight`
10. `51eb2de``Wire ProjectZomboidPvpLog default analyser`
11. `c57d646``Wire ProjectZomboidAdminLog default analyser`
11 commits total, vs 10 originally planned. The brace-fix commit accounts for the discrepancy.
## Open issues
None blocking. Phase A Q4 (admin verb scope) was settled before B.2 began. Phase B Q2 confirmed PvP fixtures contain real combat events worth analysing.
## Pointers
- Phase B.1 (foundation): `2026-04-30-pz-analysers-design.md` and `2026-04-30-pz-analysers.md`.
- Phase B.3 (deferred analysers requiring custom `Analyser` subclasses): `2026-04-30-pz-analysers-deferred-design.md`.
- Workflow conventions: `CLAUDE.md` § Workflow conventions and § Pitfalls.

View File

@@ -0,0 +1,150 @@
# Codex Redactor utility — design spec
> Retroactive: written 2026-05-01.
> **Status: deferred — not implemented.** This is a forward-looking design captured here for backfill symmetry and to inform iblogs's upload-time PII handling.
## Summary
Codex grows a small utility surface for redacting personally-identifying data from log content before it is stored, displayed, or analysed in environments where preservation of PII is unwanted. The shape is a thin generic interface plus per-game implementations that know each game's log format. iblogs is the primary line of defence (upload-time filter); codex's redactor is the optional helper consumers can call when they want codex itself to scrub data.
## Why deferred
The Phase A Step E open-questions table (Q5) marked the codex-side redactor as "defer to its own session" because the iblogs upload-time filter is the actual privacy boundary — anything codex does in this layer is a convenience, not a guarantee. Phase B (the analyser arc) shipped without the redactor and remains useful: synthetic fixtures use placeholder identifiers throughout, real Logs.zip never reaches the index, and the privacy story for codex's tests does not depend on this utility. Building it remains worthwhile when iblogs starts consuming codex output and wants a one-line option for "scrub before analyse."
## Scope
- **In scope (when this spec is implemented):** a `RedactorInterface` under `src/Util/`, a `ProjectZomboidRedactor` implementation that handles the three PII categories observed in PZ logs (Steam IDs, player names, world coordinates), per-category toggles with a defaults-on stance, replacement-string conventions matching the synthetic fixture placeholders.
- **Out of scope:** non-PZ game redactors (those land alongside their respective game implementations); UI / CLI wrappers; redaction of mod-specific identifiers (e.g. BurdJournals scientific-notation Steam IDs) — handled by an extension of the PZ implementation if/when needed; storage / persistence of redaction maps.
## Architecture
```
+-------------------------+
| RedactorInterface |
| (src/Util/) |
| redact(string): string|
+-----------+-------------+
|
+-----------------------+-----------------------+
| |
+------------v-----------------+ +--------------v-------------+
| ProjectZomboidRedactor | | (Future) MinecraftRedactor |
| (src/Util/ProjectZomboid/) | | (src/Util/Minecraft/) |
+------------------------------+ +----------------------------+
```
A thin interface in the framework's `Util` namespace. One concrete implementation per supported game, mirroring the existing components-outer-with-game-suffix layout used everywhere else in the tree (Analyser, Analysis, Detective, Log, Parser, Pattern). Future games' redactors land alongside their analyser surface.
## Why per-game implementations rather than a single regex utility
PII detection in log text is **context-sensitive**, not just regex matching:
- **Steam IDs** are 17-digit decimal numbers. Almost regexable, but care is needed not to chew through unrelated long numbers (timestamps, build numbers, GUIDs that happen to be 17 digits).
- **Player names** are arbitrary strings. They cannot be detected from text alone — a redactor needs to know the lexical contexts where names appear (`<steamid> "Name"`, `ChatMessage{author='Name'}`, `Combat: "Name"`). Without that knowledge a naive `\w+`-style match would shred the entire log.
- **Coordinates** are number triples in specific shapes (`x,y,z` after `at`, `[x,y,z]` between brackets, `(x,y,z)` in PvP combat lines). Stripping every "two commas in a row" regex match would over-redact (e.g. `f:0, t:1776297642406, st:48,648,157,584` is server metadata, not coordinates).
Per-game implementations encode the lexical contexts. PZ's redactor uses the same regex shapes Phase A's Pattern classes encode for parsing, applied in a different direction (replacement instead of extraction).
## Components
### `src/Util/RedactorInterface.php`
```php
namespace IndifferentKetchup\Codex\Util;
interface RedactorInterface
{
/**
* Return a copy of $content with PII replaced by placeholder tokens
* according to the redactor's enabled toggles.
*/
public function redact(string $content): string;
}
```
A single method. Stateless from the caller's perspective; toggles are configured on the concrete implementation before `redact()` is called.
### `src/Util/ProjectZomboid/ProjectZomboidRedactor.php`
Implements `RedactorInterface`. Three independent toggles (defaults all on) and three regex-driven replacement passes:
```php
namespace IndifferentKetchup\Codex\Util\ProjectZomboid;
use IndifferentKetchup\Codex\Util\RedactorInterface;
class ProjectZomboidRedactor implements RedactorInterface
{
private bool $redactSteamIds = true;
private bool $redactPlayerNames = true;
private bool $redactCoordinates = true;
public function redactSteamIds(bool $on): static { /* ... */ }
public function redactPlayerNames(bool $on): static { /* ... */ }
public function redactCoordinates(bool $on): static { /* ... */ }
public function redact(string $content): string
{
if ($this->redactSteamIds) { /* preg_replace */ }
if ($this->redactPlayerNames) { /* preg_replace */ }
if ($this->redactCoordinates) { /* preg_replace */ }
return $content;
}
}
```
### Replacement conventions
To match the synthetic fixture placeholders already used throughout the test suite (per the Privacy / fixture rules in CLAUDE.md):
| PII category | Replacement |
|---|---|
| Steam ID (17 decimal digits in a Steam ID context) | `76561198000000000` |
| Player name (between `"..."` after a 17-digit Steam ID, between `'...'` in `ChatMessage{author='...'}`, between `"..."` after subsystem keywords like `Combat:` / `Safety:`) | `<player>` |
| World coordinates (the `x,y,z` or `(x,y,z)` triples in PZ log lines, distinguished by leading-context anchors so server metadata triples are not stripped) | `0,0,0` |
The replacements are deliberately not reversible — codex makes no attempt to maintain a map between original and redacted values. Reversibility is a different feature scope (encryption / tokenization) and is not what this utility provides.
### Lexical anchors for the regex passes
Steam ID: `(?<![\w])(?P<sid>76561198\d{9})(?![\w])` — the `76561198` prefix matches the SteamID64 universe prefix for Steam (region "Individual"); avoids matching unrelated 17-digit numbers. Boundary classes prevent matching inside a longer alphanumeric token.
Player name (PZ-specific contexts):
- After Steam ID quoted: `(?<sid>76561198000000000) "(?P<name>[^"]+)"` → preserve the redacted Steam ID, replace the quoted name. (Redaction order matters: SIDs first, names second.)
- ChatMessage author: `ChatMessage\{chat=\w+, author='(?P<name>[^']+)',` → replace the captured author.
- PvP / Safety subsystem: `(?P<sub>Combat|Safety): "(?P<name>[^"]+)"` → replace the captured name.
Coordinates:
- ItemLog / MapLog / CmdLog `at` clauses: `at (?P<coords>[\d.]+,[\d.]+,-?[\d.]+)\.` → replace with `0,0,0.`
- ClientActionLog / PerkLog bracketed coords: `\[(?P<coords>\d+,\d+,-?\d+)\]` → replace with `[0,0,0]`
- PvP combat parenthesised coords: `\((?P<coords>\d+,\d+,-?\d+)\) (?:hit|restore|store|true|false)` — the trailing context disambiguates from server metadata triples.
These regex shapes are not yet committed to the spec implementation; tuning is expected during the actual implementation pass against the real `Logs.zip` content under `.scratch/pz/Logs/`.
## Where this fits relative to iblogs
The Phase A Step D Section e split holds: **iblogs is the primary line of defence**. iblogs filters PII at upload time, before storage, mirroring the mclogs IP/token redaction approach. Stored logs in iblogs are pre-sanitised. The codex `Redactor` is the *option* iblogs (or any other consumer) reaches for if they want codex itself to do the scrubbing — for example in a preview pipeline that wants to render redacted output without writing the raw paste to disk first, or in a dev environment where the same code path runs without iblogs's upload filter.
This means the codex Redactor is **non-load-bearing** for the privacy story. iblogs implementing redaction independently is the actual safety guarantee; codex's helper is a convenience.
## Test plan (when implemented)
Synthetic-only fixtures, no real-log content:
1. Three pairs of fixture-input / expected-output strings exercising each category in isolation.
2. One combined-input fixture demonstrating that all three categories applied to the same content produce a fully-scrubbed output.
3. Toggle tests: each of the three booleans turned off in isolation produces partial scrubbing; all three off produces an unchanged copy of input (the redactor returns input verbatim).
4. Idempotence test: `redact(redact($x)) == redact($x)`.
5. A small "negative" test: server metadata triples (`f:0, t:1776297642406, st:48,648,157,584`) are not mistaken for coordinates.
## Open questions
1. **Should the redactor optionally preserve some structure for analysers downstream?** For example, after redaction the analysers can no longer correlate by Steam ID across events because every Steam ID is the same placeholder. Two paths: (a) accept the loss — redaction is done before storage and you don't analyse redacted content, or (b) provide a "tokenizing redactor" that maps each unique input value to a unique placeholder (`76561198000000001`, `76561198000000002`, ...) preserving cardinality. Recommend (a) for v1; (b) is its own design pass.
2. **What about `BurdJournals.txt`'s scientific-notation Steam IDs?** Phase A Step C noted these as `7.656119799341651E16` form. The PZ redactor's Steam ID regex doesn't match this shape. v1 leaves them intact (tag `[BurdJournals]` already disambiguates them as mod-internal). v2 could add a separate regex for the sci-notation form.
3. **Should `coords` redaction try to preserve relative location** (e.g. round to the nearest 1000-tile chunk so the *region* is visible without giving precise base coords)? Out of scope for v1.
## Pointers
- Phase A original Q5 deferral: `2026-04-30-pz-analysers-design.md` referenced this; the explicit deferral lived in chat (Phase A Step E open-questions table).
- iblogs upload-time filtering decisions: see the iblogs bootstrap spec at `2026-05-01-iblogs-bootstrap-design.md`.
- Existing Pattern classes that the regex shapes will mirror in reverse: `src/Pattern/ProjectZomboid/{CmdPattern,ItemPattern,MapPattern,PerkPattern,ClientActionPattern,ChatPattern,PvpPattern,UserPattern}.php`.

View File

@@ -0,0 +1,64 @@
<?php
namespace IndifferentKetchup\Codex\Analyser\ProjectZomboid;
use IndifferentKetchup\Codex\Analyser\Analyser;
use IndifferentKetchup\Codex\Analysis\Analysis;
use IndifferentKetchup\Codex\Analysis\AnalysisInterface;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\ConnectionFailureProblem;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\UserPattern;
/**
* Pairs "attempting to join" with subsequent "allowed to join" events per
* Steam ID and flags any unmatched attempts. PatternAnalyser cannot express
* this because it operates per-entry without cross-entry state, so this
* walks the entire log once and aggregates before emitting Problems.
*
* "attempting to join used queue" is treated as an attempt; a player still
* waiting in queue at end-of-log will therefore be flagged. This is
* intentional v1 behaviour — a long-lived queue wait looks indistinguishable
* from a real failure without timing context, and surfacing both lets a
* human triage.
*/
class ConnectionFailureAnalyser extends Analyser
{
public function analyse(): AnalysisInterface
{
$analysis = new Analysis();
$analysis->setLog($this->log);
$attempts = [];
$allowed = [];
$playerName = [];
foreach ($this->log as $entry) {
$text = (string) $entry;
if (preg_match(UserPattern::PLAYER_EVENT, $text, $m) !== 1) {
continue;
}
$steamId = $m['steamid'];
$playerName[$steamId] = $m['player'];
if (str_starts_with($m['event'], 'attempting to join')) {
$attempts[$steamId] = ($attempts[$steamId] ?? 0) + 1;
} elseif (str_starts_with($m['event'], 'allowed to join')) {
$allowed[$steamId] = ($allowed[$steamId] ?? 0) + 1;
}
}
foreach ($attempts as $steamId => $attemptCount) {
$allowedCount = $allowed[$steamId] ?? 0;
$unmatched = $attemptCount - $allowedCount;
if ($unmatched <= 0) {
continue;
}
$analysis->addInsight((new ConnectionFailureProblem())
->setSteamId($steamId)
->setPlayer($playerName[$steamId] ?? '')
->setUnmatchedAttempts($unmatched));
}
return $analysis;
}
}

View File

@@ -0,0 +1,90 @@
<?php
namespace IndifferentKetchup\Codex\Analyser\ProjectZomboid;
use IndifferentKetchup\Codex\Analyser\Analyser;
use IndifferentKetchup\Codex\Analysis\Analysis;
use IndifferentKetchup\Codex\Analysis\AnalysisInterface;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\ItemDuplicationProblem;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\ItemPattern;
/**
* Flags suspicious item-gain frequency per (player, item) tuple. Slides a
* fixed-second window across each group's events; a window with at least
* THRESHOLD_COUNT positive-delta events triggers a problem.
*
* Negative-delta events (drops, transfers out) are ignored — they do not
* indicate creation of items and a sufficiently fast trade-and-pickup loop
* would self-cancel.
*
* Entry::getTime() resolves to integer Unix seconds, so sub-second
* timestamps in the fixture all collapse to the same value. This is
* acceptable for v1: events emitted within the same second are by
* definition within any positive window.
*/
class ItemDuplicationAnalyser extends Analyser
{
/**
* Minimum number of same-item gain events that must fall inside the
* window before a Problem is emitted. Five was picked because legitimate
* gameplay rarely produces five identical items in ten seconds:
* crafting has animation delays, looting is one-at-a-time, and zombie
* drops are similarly serial. A burst of five suggests admin-spawn or
* exploit. Tune downward if false negatives appear in production logs.
*/
public const int THRESHOLD_COUNT = 5;
/**
* Length of the sliding window in seconds. Ten seconds covers a
* realistic burst-loot scenario (e.g. crate of identical items) without
* collapsing onto unrelated events. Combined with THRESHOLD_COUNT this
* means an effective rate of 0.5 same-item events per second.
*/
public const int THRESHOLD_WINDOW_SECONDS = 10;
public function analyse(): AnalysisInterface
{
$analysis = new Analysis();
$analysis->setLog($this->log);
$groups = [];
foreach ($this->log as $entry) {
if (preg_match(ItemPattern::FIELDS, (string) $entry, $m) !== 1) {
continue;
}
if (!str_starts_with($m['delta'], '+')) {
continue;
}
$key = $m['steamid'] . '|' . $m['item'];
$groups[$key][] = [
'time' => $entry->getTime() ?? 0,
'steamid' => $m['steamid'],
'item' => $m['item'],
'player' => $m['player'],
];
}
foreach ($groups as $events) {
usort($events, static fn($a, $b) => $a['time'] <=> $b['time']);
$left = 0;
$eventCount = count($events);
for ($right = 0; $right < $eventCount; $right++) {
while ($events[$right]['time'] - $events[$left]['time'] > self::THRESHOLD_WINDOW_SECONDS) {
$left++;
}
if (($right - $left + 1) >= self::THRESHOLD_COUNT) {
$sample = $events[0];
$analysis->addInsight((new ItemDuplicationProblem())
->setSteamId($sample['steamid'])
->setPlayer($sample['player'])
->setItem($sample['item'])
->setEventCount($eventCount));
break;
}
}
}
return $analysis;
}
}

View File

@@ -0,0 +1,87 @@
<?php
namespace IndifferentKetchup\Codex\Analyser\ProjectZomboid;
use IndifferentKetchup\Codex\Analyser\Analyser;
use IndifferentKetchup\Codex\Analysis\Analysis;
use IndifferentKetchup\Codex\Analysis\AnalysisInterface;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\SkillProgressionAnomalyProblem;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\PerkPattern;
/**
* Walks PerkLog entries, parses each perks-snapshot row into a
* skill->level dict, and compares consecutive snapshots per Steam ID. If
* any single skill gained more than THRESHOLD_DELTA levels between
* snapshots, emits a SkillProgressionAnomalyProblem for that
* (player, skill) pair.
*
* Login/Logout/LevelUp event rows are skipped — they have a single token
* in the event field rather than a comma-separated list of Skill=N pairs.
*/
class SkillProgressionAnomalyAnalyser extends Analyser
{
/**
* Maximum plausible single-skill gain between two consecutive snapshots
* of the same player. Project Zomboid skill leveling is slow: most
* skills require thousands of XP per level, and even maxed grinding
* setups don't routinely produce four-or-more level jumps in a single
* session bridge. Set to 3 as a baseline; if production logs surface
* frequent legitimate jumps of 4 (e.g. on heavily modded XP servers),
* raise via subclass override or tune downward to catch finer abuse.
*/
public const int THRESHOLD_DELTA = 3;
public function analyse(): AnalysisInterface
{
$analysis = new Analysis();
$analysis->setLog($this->log);
$snapshots = [];
foreach ($this->log as $entry) {
$text = (string) $entry;
if (preg_match(PerkPattern::FIELDS, $text, $m) !== 1) {
continue;
}
if (preg_match(PerkPattern::PERK_PAIR, $m['event']) !== 1) {
continue;
}
preg_match_all(PerkPattern::PERK_PAIR, $m['event'], $pairs, PREG_SET_ORDER);
$skills = [];
foreach ($pairs as $pair) {
$skills[$pair['skill']] = (int) $pair['level'];
}
$snapshots[$m['steamid']][] = [
'time' => $entry->getTime() ?? 0,
'player' => $m['player'],
'skills' => $skills,
];
}
foreach ($snapshots as $steamId => $playerSnapshots) {
usort($playerSnapshots, static fn($a, $b) => $a['time'] <=> $b['time']);
for ($i = 1; $i < count($playerSnapshots); $i++) {
$prev = $playerSnapshots[$i - 1];
$curr = $playerSnapshots[$i];
foreach ($curr['skills'] as $skill => $currLevel) {
$prevLevel = $prev['skills'][$skill] ?? 0;
$delta = $currLevel - $prevLevel;
if ($delta > self::THRESHOLD_DELTA) {
$analysis->addInsight((new SkillProgressionAnomalyProblem())
->setSteamId($steamId)
->setPlayer($curr['player'])
->setSkill($skill)
->setFromLevel($prevLevel)
->setToLevel($currLevel)
->setDelta($delta));
}
}
}
}
return $analysis;
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace IndifferentKetchup\Codex\Analysis\ProjectZomboid;
use IndifferentKetchup\Codex\Analysis\Information;
use IndifferentKetchup\Codex\Analysis\PatternInsightInterface;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\AdminPattern;
class AdminAddedItemInformation extends Information implements PatternInsightInterface
{
public static function getPatterns(): array
{
return [AdminPattern::ADDED_ITEM_ENTRY];
}
public function setMatches(array $matches, mixed $patternKey): void
{
$this->setLabel('Admin added item');
$this->setValue(sprintf(
'%s added %s to %s',
$matches['admin'],
$matches['item'],
$matches['target']
));
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace IndifferentKetchup\Codex\Analysis\ProjectZomboid;
use IndifferentKetchup\Codex\Analysis\Information;
use IndifferentKetchup\Codex\Analysis\PatternInsightInterface;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\AdminPattern;
class AdminAddedXpInformation extends Information implements PatternInsightInterface
{
public static function getPatterns(): array
{
return [AdminPattern::ADDED_XP_ENTRY];
}
public function setMatches(array $matches, mixed $patternKey): void
{
$this->setLabel('Admin added xp');
$this->setValue(sprintf(
'%s added %s %s xp to %s',
$matches['admin'],
$matches['amount'],
$matches['skill'],
$matches['target']
));
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace IndifferentKetchup\Codex\Analysis\ProjectZomboid;
use IndifferentKetchup\Codex\Analysis\Information;
use IndifferentKetchup\Codex\Analysis\PatternInsightInterface;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\AdminPattern;
class AdminChangedOptionInformation extends Information implements PatternInsightInterface
{
public static function getPatterns(): array
{
return [AdminPattern::CHANGED_OPTION_ENTRY];
}
public function setMatches(array $matches, mixed $patternKey): void
{
$this->setLabel('Admin changed option');
$this->setValue(sprintf(
'%s set %s=%s',
$matches['admin'],
$matches['option'],
$matches['value']
));
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace IndifferentKetchup\Codex\Analysis\ProjectZomboid;
use IndifferentKetchup\Codex\Analysis\Information;
use IndifferentKetchup\Codex\Analysis\PatternInsightInterface;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\AdminPattern;
class AdminGrantedAccessInformation extends Information implements PatternInsightInterface
{
public static function getPatterns(): array
{
return [AdminPattern::GRANTED_ACCESS_ENTRY];
}
public function setMatches(array $matches, mixed $patternKey): void
{
$this->setLabel('Admin granted access');
$this->setValue(sprintf(
'%s granted %s to %s',
$matches['admin'],
$matches['level'],
$matches['target']
));
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace IndifferentKetchup\Codex\Analysis\ProjectZomboid;
use IndifferentKetchup\Codex\Analysis\Information;
use IndifferentKetchup\Codex\Analysis\PatternInsightInterface;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\AdminPattern;
class AdminReloadedOptionsInformation extends Information implements PatternInsightInterface
{
public static function getPatterns(): array
{
return [AdminPattern::RELOADED_OPTIONS_ENTRY];
}
public function setMatches(array $matches, mixed $patternKey): void
{
$this->setLabel('Admin reloaded options');
$this->setValue($matches['admin']);
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace IndifferentKetchup\Codex\Analysis\ProjectZomboid;
use IndifferentKetchup\Codex\Analysis\Information;
use IndifferentKetchup\Codex\Analysis\PatternInsightInterface;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\AdminPattern;
class AdminTeleportedInformation extends Information implements PatternInsightInterface
{
public static function getPatterns(): array
{
return [AdminPattern::TELEPORTED_ENTRY];
}
public function setMatches(array $matches, mixed $patternKey): void
{
$this->setLabel('Admin teleported');
$this->setValue(sprintf(
'%s teleported %s to %s,%s,%s',
$matches['admin'],
$matches['target'],
$matches['x'],
$matches['y'],
$matches['z']
));
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace IndifferentKetchup\Codex\Analysis\ProjectZomboid;
use IndifferentKetchup\Codex\Analysis\InsightInterface;
use IndifferentKetchup\Codex\Analysis\Problem;
/**
* Problem emitted by ConnectionFailureAnalyser when a player's
* "attempting to join" event count exceeds their "allowed to join" count
* within the same log file. Coalesced by Steam ID so each player produces
* at most one problem regardless of how many unmatched attempts they have.
*/
class ConnectionFailureProblem extends Problem
{
private string $steamId = '';
private string $player = '';
private int $unmatchedAttempts = 0;
public function setSteamId(string $steamId): static
{
$this->steamId = $steamId;
return $this;
}
public function setPlayer(string $player): static
{
$this->player = $player;
return $this;
}
public function setUnmatchedAttempts(int $count): static
{
$this->unmatchedAttempts = $count;
return $this;
}
public function getSteamId(): string
{
return $this->steamId;
}
public function getPlayer(): string
{
return $this->player;
}
public function getUnmatchedAttempts(): int
{
return $this->unmatchedAttempts;
}
public function getMessage(): string
{
return sprintf(
'Player %s (%s) had %d "attempting to join" event(s) without a matching "allowed to join".',
$this->player,
$this->steamId,
$this->unmatchedAttempts
);
}
public function isEqual(InsightInterface $insight): bool
{
return $insight instanceof self && $insight->getSteamId() === $this->steamId;
}
}

View File

@@ -0,0 +1,82 @@
<?php
namespace IndifferentKetchup\Codex\Analysis\ProjectZomboid;
use IndifferentKetchup\Codex\Analysis\InsightInterface;
use IndifferentKetchup\Codex\Analysis\Problem;
/**
* Problem emitted by ItemDuplicationAnalyser when a player gains the same
* item code at a rate that exceeds the configured threshold. Coalesced by
* the (Steam ID, item code) tuple so each suspicious group produces one
* problem regardless of how many events fall inside the window.
*/
class ItemDuplicationProblem extends Problem
{
private string $steamId = '';
private string $player = '';
private string $item = '';
private int $eventCount = 0;
public function setSteamId(string $steamId): static
{
$this->steamId = $steamId;
return $this;
}
public function setPlayer(string $player): static
{
$this->player = $player;
return $this;
}
public function setItem(string $item): static
{
$this->item = $item;
return $this;
}
public function setEventCount(int $count): static
{
$this->eventCount = $count;
return $this;
}
public function getSteamId(): string
{
return $this->steamId;
}
public function getPlayer(): string
{
return $this->player;
}
public function getItem(): string
{
return $this->item;
}
public function getEventCount(): int
{
return $this->eventCount;
}
public function getMessage(): string
{
return sprintf(
'Player %s (%s) gained %s %d times at a rate above the duplication threshold.',
$this->player,
$this->steamId,
$this->item,
$this->eventCount
);
}
public function isEqual(InsightInterface $insight): bool
{
return $insight instanceof self
&& $insight->getSteamId() === $this->steamId
&& $insight->getItem() === $this->item;
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace IndifferentKetchup\Codex\Analysis\ProjectZomboid;
use IndifferentKetchup\Codex\Analysis\Information;
use IndifferentKetchup\Codex\Analysis\PatternInsightInterface;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\PvpPattern;
class PvpDamageInformation extends Information implements PatternInsightInterface
{
public static function getPatterns(): array
{
return [PvpPattern::COMBAT_REAL];
}
public function setMatches(array $matches, mixed $patternKey): void
{
$this->setLabel('PvP combat');
$this->setValue(sprintf(
'%s hit %s with %s',
$matches['attacker'],
$matches['victim'],
$matches['weapon']
));
}
}

View File

@@ -0,0 +1,107 @@
<?php
namespace IndifferentKetchup\Codex\Analysis\ProjectZomboid;
use IndifferentKetchup\Codex\Analysis\InsightInterface;
use IndifferentKetchup\Codex\Analysis\Problem;
/**
* Problem emitted by SkillProgressionAnomalyAnalyser when a single skill
* gained more than the configured threshold between two consecutive
* snapshots of the same player. Coalesced by (Steam ID, skill).
*/
class SkillProgressionAnomalyProblem extends Problem
{
private string $steamId = '';
private string $player = '';
private string $skill = '';
private int $fromLevel = 0;
private int $toLevel = 0;
private int $delta = 0;
public function setSteamId(string $steamId): static
{
$this->steamId = $steamId;
return $this;
}
public function setPlayer(string $player): static
{
$this->player = $player;
return $this;
}
public function setSkill(string $skill): static
{
$this->skill = $skill;
return $this;
}
public function setFromLevel(int $level): static
{
$this->fromLevel = $level;
return $this;
}
public function setToLevel(int $level): static
{
$this->toLevel = $level;
return $this;
}
public function setDelta(int $delta): static
{
$this->delta = $delta;
return $this;
}
public function getSteamId(): string
{
return $this->steamId;
}
public function getPlayer(): string
{
return $this->player;
}
public function getSkill(): string
{
return $this->skill;
}
public function getFromLevel(): int
{
return $this->fromLevel;
}
public function getToLevel(): int
{
return $this->toLevel;
}
public function getDelta(): int
{
return $this->delta;
}
public function getMessage(): string
{
return sprintf(
'Player %s (%s) gained %d levels of %s between snapshots (%d to %d).',
$this->player,
$this->steamId,
$this->delta,
$this->skill,
$this->fromLevel,
$this->toLevel
);
}
public function isEqual(InsightInterface $insight): bool
{
return $insight instanceof self
&& $insight->getSteamId() === $this->steamId
&& $insight->getSkill() === $this->skill;
}
}

View File

@@ -4,6 +4,12 @@ namespace IndifferentKetchup\Codex\Log\ProjectZomboid;
use IndifferentKetchup\Codex\Analyser\AnalyserInterface; use IndifferentKetchup\Codex\Analyser\AnalyserInterface;
use IndifferentKetchup\Codex\Analyser\PatternAnalyser; use IndifferentKetchup\Codex\Analyser\PatternAnalyser;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminAddedItemInformation;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminAddedXpInformation;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminChangedOptionInformation;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminGrantedAccessInformation;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminReloadedOptionsInformation;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminTeleportedInformation;
use IndifferentKetchup\Codex\Detective\FilenameDetector; use IndifferentKetchup\Codex\Detective\FilenameDetector;
use IndifferentKetchup\Codex\Detective\WeightedSinglePatternDetector; use IndifferentKetchup\Codex\Detective\WeightedSinglePatternDetector;
use IndifferentKetchup\Codex\Parser\ParserInterface; use IndifferentKetchup\Codex\Parser\ParserInterface;
@@ -22,7 +28,13 @@ class ProjectZomboidAdminLog extends ProjectZomboidEventLog
public static function getDefaultAnalyser(): AnalyserInterface public static function getDefaultAnalyser(): AnalyserInterface
{ {
return new PatternAnalyser(); return (new PatternAnalyser())
->addPossibleInsightClass(AdminAddedItemInformation::class)
->addPossibleInsightClass(AdminAddedXpInformation::class)
->addPossibleInsightClass(AdminGrantedAccessInformation::class)
->addPossibleInsightClass(AdminChangedOptionInformation::class)
->addPossibleInsightClass(AdminReloadedOptionsInformation::class)
->addPossibleInsightClass(AdminTeleportedInformation::class);
} }
public static function getDetectors(): array public static function getDetectors(): array

View File

@@ -3,7 +3,7 @@
namespace IndifferentKetchup\Codex\Log\ProjectZomboid; namespace IndifferentKetchup\Codex\Log\ProjectZomboid;
use IndifferentKetchup\Codex\Analyser\AnalyserInterface; use IndifferentKetchup\Codex\Analyser\AnalyserInterface;
use IndifferentKetchup\Codex\Analyser\PatternAnalyser; use IndifferentKetchup\Codex\Analyser\ProjectZomboid\ItemDuplicationAnalyser;
use IndifferentKetchup\Codex\Detective\FilenameDetector; use IndifferentKetchup\Codex\Detective\FilenameDetector;
use IndifferentKetchup\Codex\Detective\WeightedSinglePatternDetector; use IndifferentKetchup\Codex\Detective\WeightedSinglePatternDetector;
use IndifferentKetchup\Codex\Parser\ParserInterface; use IndifferentKetchup\Codex\Parser\ParserInterface;
@@ -22,7 +22,7 @@ class ProjectZomboidItemLog extends ProjectZomboidEventLog
public static function getDefaultAnalyser(): AnalyserInterface public static function getDefaultAnalyser(): AnalyserInterface
{ {
return new PatternAnalyser(); return new ItemDuplicationAnalyser();
} }
public static function getDetectors(): array public static function getDetectors(): array

View File

@@ -3,7 +3,7 @@
namespace IndifferentKetchup\Codex\Log\ProjectZomboid; namespace IndifferentKetchup\Codex\Log\ProjectZomboid;
use IndifferentKetchup\Codex\Analyser\AnalyserInterface; use IndifferentKetchup\Codex\Analyser\AnalyserInterface;
use IndifferentKetchup\Codex\Analyser\PatternAnalyser; use IndifferentKetchup\Codex\Analyser\ProjectZomboid\SkillProgressionAnomalyAnalyser;
use IndifferentKetchup\Codex\Detective\FilenameDetector; use IndifferentKetchup\Codex\Detective\FilenameDetector;
use IndifferentKetchup\Codex\Detective\WeightedSinglePatternDetector; use IndifferentKetchup\Codex\Detective\WeightedSinglePatternDetector;
use IndifferentKetchup\Codex\Parser\ParserInterface; use IndifferentKetchup\Codex\Parser\ParserInterface;
@@ -22,7 +22,7 @@ class ProjectZomboidPerkLog extends ProjectZomboidEventLog
public static function getDefaultAnalyser(): AnalyserInterface public static function getDefaultAnalyser(): AnalyserInterface
{ {
return new PatternAnalyser(); return new SkillProgressionAnomalyAnalyser();
} }
public static function getDetectors(): array public static function getDetectors(): array

View File

@@ -4,6 +4,7 @@ namespace IndifferentKetchup\Codex\Log\ProjectZomboid;
use IndifferentKetchup\Codex\Analyser\AnalyserInterface; use IndifferentKetchup\Codex\Analyser\AnalyserInterface;
use IndifferentKetchup\Codex\Analyser\PatternAnalyser; use IndifferentKetchup\Codex\Analyser\PatternAnalyser;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\PvpDamageInformation;
use IndifferentKetchup\Codex\Detective\FilenameDetector; use IndifferentKetchup\Codex\Detective\FilenameDetector;
use IndifferentKetchup\Codex\Detective\WeightedSinglePatternDetector; use IndifferentKetchup\Codex\Detective\WeightedSinglePatternDetector;
use IndifferentKetchup\Codex\Parser\ParserInterface; use IndifferentKetchup\Codex\Parser\ParserInterface;
@@ -22,7 +23,8 @@ class ProjectZomboidPvpLog extends ProjectZomboidEventLog
public static function getDefaultAnalyser(): AnalyserInterface public static function getDefaultAnalyser(): AnalyserInterface
{ {
return new PatternAnalyser(); return (new PatternAnalyser())
->addPossibleInsightClass(PvpDamageInformation::class);
} }
public static function getDetectors(): array public static function getDetectors(): array

View File

@@ -3,7 +3,7 @@
namespace IndifferentKetchup\Codex\Log\ProjectZomboid; namespace IndifferentKetchup\Codex\Log\ProjectZomboid;
use IndifferentKetchup\Codex\Analyser\AnalyserInterface; use IndifferentKetchup\Codex\Analyser\AnalyserInterface;
use IndifferentKetchup\Codex\Analyser\PatternAnalyser; use IndifferentKetchup\Codex\Analyser\ProjectZomboid\ConnectionFailureAnalyser;
use IndifferentKetchup\Codex\Detective\FilenameDetector; use IndifferentKetchup\Codex\Detective\FilenameDetector;
use IndifferentKetchup\Codex\Detective\WeightedSinglePatternDetector; use IndifferentKetchup\Codex\Detective\WeightedSinglePatternDetector;
use IndifferentKetchup\Codex\Parser\ParserInterface; use IndifferentKetchup\Codex\Parser\ParserInterface;
@@ -22,7 +22,7 @@ class ProjectZomboidUserLog extends ProjectZomboidEventLog
public static function getDefaultAnalyser(): AnalyserInterface public static function getDefaultAnalyser(): AnalyserInterface
{ {
return new PatternAnalyser(); return new ConnectionFailureAnalyser();
} }
public static function getDetectors(): array public static function getDetectors(): array

View File

@@ -25,4 +25,23 @@ class AdminPattern
public const string RELOADED_OPTIONS = '/^(?<admin>.+?) reloaded options$/'; public const string RELOADED_OPTIONS = '/^(?<admin>.+?) reloaded options$/';
public const string TELEPORTED = '/^(?<admin>.+?) teleported (?<target>.+?) to (?<x>\d+),(?<y>\d+),(?<z>-?\d+)$/'; public const string TELEPORTED = '/^(?<admin>.+?) teleported (?<target>.+?) to (?<x>\d+),(?<y>\d+),(?<z>-?\d+)$/';
/**
* Entry-anchored variants for analyser use. PatternAnalyser passes the
* full Entry text (including the [time] prefix) to preg_match_all, so
* these include the timestamp prefix and are anchored at start/end of
* the line. The body-only constants above are kept for direct-message
* matching.
*/
public const string ADDED_ITEM_ENTRY = '/^\[\d{2}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}\] (?<admin>.+?) added item (?<item>Base\.\S+) in (?<target>.+?)\'s inventory\.?$/';
public const string ADDED_XP_ENTRY = '/^\[\d{2}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}\] (?<admin>.+?) added (?<amount>[\d.]+) (?<skill>\S+) xp\'s to (?<target>.+?)\.?$/';
public const string GRANTED_ACCESS_ENTRY = '/^\[\d{2}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}\] (?<admin>.+?) granted (?<level>\w+) access level on (?<target>.+?)\.?$/';
public const string CHANGED_OPTION_ENTRY = '/^\[\d{2}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}\] (?<admin>.+?) changed option (?<option>\S+?)=(?<value>.+?)\.?$/';
public const string RELOADED_OPTIONS_ENTRY = '/^\[\d{2}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}\] (?<admin>.+?) reloaded options\.?$/';
public const string TELEPORTED_ENTRY = '/^\[\d{2}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}\] (?<admin>.+?) teleported (?<target>.+?) to (?<x>\d+),(?<y>\d+),(?<z>-?\d+)\.?$/';
} }

View File

@@ -24,4 +24,12 @@ class PvpPattern
public const string COMBAT = '/^Combat: "(?<attacker>[^"]+)" \((?<ax>\d+),(?<ay>\d+),(?<az>-?\d+)\) hit "(?<victim>[^"]+)" \((?<vx>\d+),(?<vy>\d+),(?<vz>-?\d+)\) weapon="(?<weapon>[^"]+)" damage=(?<damage>-?\d+\.\d+)\.$/'; public const string COMBAT = '/^Combat: "(?<attacker>[^"]+)" \((?<ax>\d+),(?<ay>\d+),(?<az>-?\d+)\) hit "(?<victim>[^"]+)" \((?<vx>\d+),(?<vy>\d+),(?<vz>-?\d+)\) weapon="(?<weapon>[^"]+)" damage=(?<damage>-?\d+\.\d+)\.$/';
public const string SAFETY = '/^Safety: "(?<player>[^"]+)" \((?<x>\d+),(?<y>\d+),(?<z>-?\d+)\) (?<verb>\w+) (?<state>true|false)\.$/'; public const string SAFETY = '/^Safety: "(?<player>[^"]+)" \((?<x>\d+),(?<y>\d+),(?<z>-?\d+)\) (?<verb>\w+) (?<state>true|false)\.$/';
/**
* Real-PvP combat: weapon!="zombie" AND damage>0. Filtering is in the
* regex itself so PatternAnalyser produces no insights for zombie/zero
* rows. Damage clause matches any positive non-zero float (rejects
* 0.000000 and any leading-minus value).
*/
public const string COMBAT_REAL = '/Combat: "(?<attacker>[^"]+)" \([^)]+\) hit "(?<victim>[^"]+)" \([^)]+\) weapon="(?<weapon>(?!zombie")[^"]+)" damage=(?<damage>0\.0*[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)/';
} }

View File

@@ -8,3 +8,13 @@
[16-04-26 19:35:42.812] 76561198000000001 "Player1" container -1 1002,2002,0 [Base.WaterBottleFull]. [16-04-26 19:35:42.812] 76561198000000001 "Player1" container -1 1002,2002,0 [Base.WaterBottleFull].
[16-04-26 19:40:00.514] 76561198000000002 "Player2" floor +1 1011,2011,0 [Base.Bandage]. [16-04-26 19:40:00.514] 76561198000000002 "Player2" floor +1 1011,2011,0 [Base.Bandage].
[16-04-26 19:42:25.223] 76561198000000002 "Player2" inventory +5 1011,2011,0 [Base.Bullets9mm]. [16-04-26 19:42:25.223] 76561198000000002 "Player2" inventory +5 1011,2011,0 [Base.Bullets9mm].
[16-04-26 19:50:00.001] 76561198000000003 "AdminUser" inventory +1 1020,2020,0 [Base.Bullets9mm].
[16-04-26 19:50:00.002] 76561198000000003 "AdminUser" inventory +1 1020,2020,0 [Base.Bullets9mm].
[16-04-26 19:50:00.003] 76561198000000003 "AdminUser" inventory +1 1020,2020,0 [Base.Bullets9mm].
[16-04-26 19:50:00.004] 76561198000000003 "AdminUser" inventory +1 1020,2020,0 [Base.Bullets9mm].
[16-04-26 19:50:00.005] 76561198000000003 "AdminUser" inventory +1 1020,2020,0 [Base.Bullets9mm].
[16-04-26 19:50:00.006] 76561198000000003 "AdminUser" inventory +1 1020,2020,0 [Base.Bullets9mm].
[16-04-26 20:00:00.000] 76561198000000001 "Player1" floor +1 1004,2004,0 [Base.Plank].
[16-04-26 20:01:00.000] 76561198000000001 "Player1" floor +1 1004,2004,0 [Base.Plank].
[16-04-26 20:02:00.000] 76561198000000001 "Player1" floor +1 1004,2004,0 [Base.Plank].
[16-04-26 20:03:00.000] 76561198000000001 "Player1" floor +1 1004,2004,0 [Base.Plank].

View File

@@ -4,3 +4,7 @@
[16-04-26 18:29:15.823] [76561198000000002][Player2][1010,2010,0][Cooking=2, Fitness=10, Strength=10, Blunt=10, Axe=0, Lightfoot=4, Nimble=4, Sprinting=7, Sneak=2, Woodwork=6, Aiming=5, Reloading=4, Farming=0, Fishing=0, Trapping=0, PlantScavenging=0, Doctor=2, Electricity=5, Blacksmith=8, MetalWelding=10, Mechanics=10, Spear=0, Maintenance=7, SmallBlade=0, LongBlade=0, SmallBlunt=0, Tailoring=0, Tracking=0, Husbandry=0, FlintKnapping=0, Masonry=0, Pottery=0, Carving=0, Butchering=0, Glassmaking=0, Side_L=0, Side_R=0, ProstFamiliarity=0][Hours Survived: 50]. [16-04-26 18:29:15.823] [76561198000000002][Player2][1010,2010,0][Cooking=2, Fitness=10, Strength=10, Blunt=10, Axe=0, Lightfoot=4, Nimble=4, Sprinting=7, Sneak=2, Woodwork=6, Aiming=5, Reloading=4, Farming=0, Fishing=0, Trapping=0, PlantScavenging=0, Doctor=2, Electricity=5, Blacksmith=8, MetalWelding=10, Mechanics=10, Spear=0, Maintenance=7, SmallBlade=0, LongBlade=0, SmallBlunt=0, Tailoring=0, Tracking=0, Husbandry=0, FlintKnapping=0, Masonry=0, Pottery=0, Carving=0, Butchering=0, Glassmaking=0, Side_L=0, Side_R=0, ProstFamiliarity=0][Hours Survived: 50].
[16-04-26 18:30:02.500] [76561198000000003][AdminUser][1020,2020,0][Logout][Hours Survived: 75]. [16-04-26 18:30:02.500] [76561198000000003][AdminUser][1020,2020,0][Logout][Hours Survived: 75].
[16-04-26 19:15:00.000] [76561198000000001][Player1][1003,2003,1][LevelUp][Hours Survived: 101]. [16-04-26 19:15:00.000] [76561198000000001][Player1][1003,2003,1][LevelUp][Hours Survived: 101].
[16-04-26 18:30:00.000] [76561198000000004][PlayerSuspect][1030,2030,0][Login][Hours Survived: 10].
[16-04-26 18:30:00.000] [76561198000000004][PlayerSuspect][1030,2030,0][Cooking=2, Fitness=2, Strength=2, Blunt=0, Axe=0, Lightfoot=0, Nimble=0, Sprinting=0, Sneak=0, Woodwork=0, Aiming=0, Reloading=0, Farming=0, Fishing=0, Trapping=0, PlantScavenging=0, Doctor=0, Electricity=0, Blacksmith=0, MetalWelding=0, Mechanics=0, Spear=0, Maintenance=0, SmallBlade=0, LongBlade=0, SmallBlunt=0, Tailoring=0, Tracking=0, Husbandry=0, FlintKnapping=0, Masonry=0, Pottery=0, Carving=0, Butchering=0, Glassmaking=0, Side_L=0, Side_R=0, ProstFamiliarity=0][Hours Survived: 10].
[16-04-26 22:00:00.000] [76561198000000004][PlayerSuspect][1031,2031,0][Login][Hours Survived: 12].
[16-04-26 22:00:00.000] [76561198000000004][PlayerSuspect][1031,2031,0][Cooking=2, Fitness=8, Strength=10, Blunt=0, Axe=0, Lightfoot=0, Nimble=0, Sprinting=0, Sneak=0, Woodwork=0, Aiming=0, Reloading=0, Farming=0, Fishing=0, Trapping=0, PlantScavenging=0, Doctor=0, Electricity=0, Blacksmith=0, MetalWelding=0, Mechanics=0, Spear=0, Maintenance=3, SmallBlade=0, LongBlade=0, SmallBlunt=0, Tailoring=0, Tracking=0, Husbandry=0, FlintKnapping=0, Masonry=0, Pottery=0, Carving=0, Butchering=0, Glassmaking=0, Side_L=0, Side_R=0, ProstFamiliarity=0][Hours Survived: 12].

View File

@@ -0,0 +1,53 @@
<?php
namespace IndifferentKetchup\Codex\Test\Tests\Games\ProjectZomboid\Analyser;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminAddedItemInformation;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminAddedXpInformation;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminChangedOptionInformation;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminGrantedAccessInformation;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminReloadedOptionsInformation;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminTeleportedInformation;
use IndifferentKetchup\Codex\Log\File\PathLogFile;
use IndifferentKetchup\Codex\Log\ProjectZomboid\ProjectZomboidAdminLog;
use PHPUnit\Framework\TestCase;
class AdminLogAnalysisTest extends TestCase
{
private function fixturePath(): string
{
return __DIR__ . '/../../../../src/Games/ProjectZomboid/fixtures/admin-minimal.txt';
}
public function testAnalyseProducesExpectedInsightCounts(): void
{
$log = (new ProjectZomboidAdminLog())->setLogFile(new PathLogFile($this->fixturePath()));
$log->parse();
$analysis = $log->analyse();
$this->assertCount(2, $analysis->getFilteredInsights(AdminAddedItemInformation::class));
$this->assertCount(2, $analysis->getFilteredInsights(AdminAddedXpInformation::class));
$this->assertCount(2, $analysis->getFilteredInsights(AdminGrantedAccessInformation::class));
$this->assertCount(2, $analysis->getFilteredInsights(AdminChangedOptionInformation::class));
$this->assertCount(1, $analysis->getFilteredInsights(AdminReloadedOptionsInformation::class));
$this->assertCount(2, $analysis->getFilteredInsights(AdminTeleportedInformation::class));
}
public function testIdenticalAddedItemEventsAreCoalesced(): void
{
$log = (new ProjectZomboidAdminLog())->setLogFile(new PathLogFile($this->fixturePath()));
$log->parse();
$analysis = $log->analyse();
$shotgunInsight = null;
foreach ($analysis->getFilteredInsights(AdminAddedItemInformation::class) as $insight) {
if (str_contains($insight->getValue(), 'Base.ShotgunShells')) {
$shotgunInsight = $insight;
break;
}
}
$this->assertNotNull($shotgunInsight);
$this->assertSame(2, $shotgunInsight->getCounterValue());
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace IndifferentKetchup\Codex\Test\Tests\Games\ProjectZomboid\Analyser;
use IndifferentKetchup\Codex\Analyser\ProjectZomboid\ItemDuplicationAnalyser;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\ItemDuplicationProblem;
use IndifferentKetchup\Codex\Log\File\PathLogFile;
use IndifferentKetchup\Codex\Log\ProjectZomboid\ProjectZomboidItemLog;
use PHPUnit\Framework\TestCase;
class ItemLogAnalysisTest extends TestCase
{
private function fixturePath(): string
{
return __DIR__ . '/../../../../src/Games/ProjectZomboid/fixtures/item-minimal.txt';
}
public function testFlagsBurstOfSameItemAboveThreshold(): void
{
$log = (new ProjectZomboidItemLog())->setLogFile(new PathLogFile($this->fixturePath()));
$log->parse();
$analysis = $log->analyse();
$problems = $analysis->getFilteredInsights(ItemDuplicationProblem::class);
$this->assertCount(1, $problems);
$problem = $problems[0];
$this->assertSame('76561198000000003', $problem->getSteamId());
$this->assertSame('AdminUser', $problem->getPlayer());
$this->assertSame('Base.Bullets9mm', $problem->getItem());
$this->assertSame(6, $problem->getEventCount());
}
public function testDoesNotFlagSubThresholdGroup(): void
{
$log = (new ProjectZomboidItemLog())->setLogFile(new PathLogFile($this->fixturePath()));
$log->parse();
$analysis = $log->analyse();
$problems = $analysis->getFilteredInsights(ItemDuplicationProblem::class);
foreach ($problems as $problem) {
$this->assertNotSame('Base.Plank', $problem->getItem());
}
}
public function testThresholdConstantsAreDocumentedAndPositive(): void
{
$this->assertGreaterThan(0, ItemDuplicationAnalyser::THRESHOLD_COUNT);
$this->assertGreaterThan(0, ItemDuplicationAnalyser::THRESHOLD_WINDOW_SECONDS);
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace IndifferentKetchup\Codex\Test\Tests\Games\ProjectZomboid\Analyser;
use IndifferentKetchup\Codex\Analyser\ProjectZomboid\SkillProgressionAnomalyAnalyser;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\SkillProgressionAnomalyProblem;
use IndifferentKetchup\Codex\Log\File\PathLogFile;
use IndifferentKetchup\Codex\Log\ProjectZomboid\ProjectZomboidPerkLog;
use PHPUnit\Framework\TestCase;
class PerkLogAnalysisTest extends TestCase
{
private function fixturePath(): string
{
return __DIR__ . '/../../../../src/Games/ProjectZomboid/fixtures/perk-minimal.txt';
}
public function testFlagsSkillsThatExceedDeltaThreshold(): void
{
$log = (new ProjectZomboidPerkLog())->setLogFile(new PathLogFile($this->fixturePath()));
$log->parse();
$analysis = $log->analyse();
$problems = $analysis->getFilteredInsights(SkillProgressionAnomalyProblem::class);
$skills = array_map(fn($p) => $p->getSkill(), $problems);
sort($skills);
$this->assertSame(['Fitness', 'Strength'], $skills);
foreach ($problems as $problem) {
$this->assertSame('76561198000000004', $problem->getSteamId());
$this->assertSame('PlayerSuspect', $problem->getPlayer());
}
}
public function testDeltaAtThresholdDoesNotTrigger(): void
{
$log = (new ProjectZomboidPerkLog())->setLogFile(new PathLogFile($this->fixturePath()));
$log->parse();
$analysis = $log->analyse();
$problems = $analysis->getFilteredInsights(SkillProgressionAnomalyProblem::class);
foreach ($problems as $problem) {
$this->assertNotSame('Maintenance', $problem->getSkill());
}
}
public function testSinglePlayerWithOneSnapshotProducesNoProblem(): void
{
$log = (new ProjectZomboidPerkLog())->setLogFile(new PathLogFile($this->fixturePath()));
$log->parse();
$analysis = $log->analyse();
$problems = $analysis->getFilteredInsights(SkillProgressionAnomalyProblem::class);
foreach ($problems as $problem) {
$this->assertNotSame('76561198000000001', $problem->getSteamId());
$this->assertNotSame('76561198000000002', $problem->getSteamId());
}
}
public function testThresholdConstantIsDocumentedAndPositive(): void
{
$this->assertGreaterThan(0, SkillProgressionAnomalyAnalyser::THRESHOLD_DELTA);
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace IndifferentKetchup\Codex\Test\Tests\Games\ProjectZomboid\Analyser;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\PvpDamageInformation;
use IndifferentKetchup\Codex\Log\File\PathLogFile;
use IndifferentKetchup\Codex\Log\ProjectZomboid\ProjectZomboidPvpLog;
use PHPUnit\Framework\TestCase;
class PvpLogAnalysisTest extends TestCase
{
private function fixturePath(): string
{
return __DIR__ . '/../../../../src/Games/ProjectZomboid/fixtures/pvp-minimal.txt';
}
public function testAnalyseProducesOnlyRealPvpInsights(): void
{
$log = (new ProjectZomboidPvpLog())->setLogFile(new PathLogFile($this->fixturePath()));
$log->parse();
$analysis = $log->analyse();
$insights = $analysis->getFilteredInsights(PvpDamageInformation::class);
$values = array_map(fn($i) => $i->getValue(), $insights);
sort($values);
$this->assertSame(
[
'AdminUser hit Player1 with Hunting Knife',
'Player1 hit Player2 with Bare Hands',
'Player1 hit Player2 with Tire Iron (Worn)',
],
$values
);
}
public function testZombieAndZeroDamageAreFilteredOut(): void
{
$log = (new ProjectZomboidPvpLog())->setLogFile(new PathLogFile($this->fixturePath()));
$log->parse();
$analysis = $log->analyse();
$insights = $analysis->getFilteredInsights(PvpDamageInformation::class);
foreach ($insights as $insight) {
$this->assertStringNotContainsString('zombie', $insight->getValue());
$this->assertStringNotContainsString('vehicle', $insight->getValue());
}
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace IndifferentKetchup\Codex\Test\Tests\Games\ProjectZomboid\Analyser;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\ConnectionFailureProblem;
use IndifferentKetchup\Codex\Log\File\PathLogFile;
use IndifferentKetchup\Codex\Log\ProjectZomboid\ProjectZomboidUserLog;
use PHPUnit\Framework\TestCase;
class UserLogAnalysisTest extends TestCase
{
private function fixturePath(): string
{
return __DIR__ . '/../../../../src/Games/ProjectZomboid/fixtures/user-minimal.txt';
}
public function testFlagsPlayerWithUnmatchedAttempts(): void
{
$log = (new ProjectZomboidUserLog())->setLogFile(new PathLogFile($this->fixturePath()));
$log->parse();
$analysis = $log->analyse();
$problems = $analysis->getFilteredInsights(ConnectionFailureProblem::class);
$this->assertCount(1, $problems);
$problem = $problems[0];
$this->assertSame('76561198000000001', $problem->getSteamId());
$this->assertSame('Player1', $problem->getPlayer());
$this->assertSame(1, $problem->getUnmatchedAttempts());
}
public function testDoesNotFlagPlayerWithMatchedAttempts(): void
{
$log = (new ProjectZomboidUserLog())->setLogFile(new PathLogFile($this->fixturePath()));
$log->parse();
$analysis = $log->analyse();
$problems = $analysis->getFilteredInsights(ConnectionFailureProblem::class);
foreach ($problems as $problem) {
$this->assertNotSame('76561198000000002', $problem->getSteamId());
}
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace IndifferentKetchup\Codex\Test\Tests\Games\ProjectZomboid\Analysis;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminAddedItemInformation;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\AdminPattern;
use PHPUnit\Framework\TestCase;
class AdminAddedItemInformationTest extends TestCase
{
public function testGetPatternsReturnsEntryRegex(): void
{
$this->assertSame([AdminPattern::ADDED_ITEM_ENTRY], AdminAddedItemInformation::getPatterns());
}
public function testEntryRegexMatchesFullLine(): void
{
$line = "[16-04-26 18:33:34.289] AdminUser added item Base.ShotgunShells in Player1's inventory.";
$this->assertSame(1, preg_match(AdminPattern::ADDED_ITEM_ENTRY, $line, $m));
$insight = new AdminAddedItemInformation();
$insight->setMatches($m, 0);
$this->assertSame('Admin added item', $insight->getLabel());
$this->assertSame('AdminUser added Base.ShotgunShells to Player1', $insight->getValue());
}
public function testIsEqualCoalescesIdenticalAddedItem(): void
{
$a = $this->insightFor('AdminUser', 'Base.X', 'Player1');
$b = $this->insightFor('AdminUser', 'Base.X', 'Player1');
$c = $this->insightFor('AdminUser', 'Base.Y', 'Player1');
$this->assertTrue($a->isEqual($b));
$this->assertFalse($a->isEqual($c));
}
private function insightFor(string $admin, string $item, string $target): AdminAddedItemInformation
{
$insight = new AdminAddedItemInformation();
$insight->setMatches([
'admin' => $admin,
'item' => $item,
'target' => $target,
], 0);
return $insight;
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace IndifferentKetchup\Codex\Test\Tests\Games\ProjectZomboid\Analysis;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminAddedXpInformation;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\AdminPattern;
use PHPUnit\Framework\TestCase;
class AdminAddedXpInformationTest extends TestCase
{
public function testGetPatternsReturnsEntryRegex(): void
{
$this->assertSame([AdminPattern::ADDED_XP_ENTRY], AdminAddedXpInformation::getPatterns());
}
public function testEntryRegexMatchesFullLine(): void
{
$line = "[16-04-26 18:34:00.500] AdminUser added 750.0 Blunt xp's to Player1.";
$this->assertSame(1, preg_match(AdminPattern::ADDED_XP_ENTRY, $line, $m));
$insight = new AdminAddedXpInformation();
$insight->setMatches($m, 0);
$this->assertSame('Admin added xp', $insight->getLabel());
$this->assertSame('AdminUser added 750.0 Blunt xp to Player1', $insight->getValue());
}
public function testEntryRegexDoesNotMatchAddedItemLine(): void
{
$line = "[16-04-26 18:33:34.289] AdminUser added item Base.ShotgunShells in Player1's inventory.";
$this->assertSame(0, preg_match(AdminPattern::ADDED_XP_ENTRY, $line));
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace IndifferentKetchup\Codex\Test\Tests\Games\ProjectZomboid\Analysis;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminChangedOptionInformation;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\AdminPattern;
use PHPUnit\Framework\TestCase;
class AdminChangedOptionInformationTest extends TestCase
{
public function testGetPatternsReturnsEntryRegex(): void
{
$this->assertSame([AdminPattern::CHANGED_OPTION_ENTRY], AdminChangedOptionInformation::getPatterns());
}
public function testEntryRegexMatchesFullLine(): void
{
$line = "[16-04-26 18:36:15.500] AdminUser changed option AnnounceDeath=true.";
$this->assertSame(1, preg_match(AdminPattern::CHANGED_OPTION_ENTRY, $line, $m));
$insight = new AdminChangedOptionInformation();
$insight->setMatches($m, 0);
$this->assertSame('Admin changed option', $insight->getLabel());
$this->assertSame('AdminUser set AnnounceDeath=true', $insight->getValue());
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace IndifferentKetchup\Codex\Test\Tests\Games\ProjectZomboid\Analysis;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminGrantedAccessInformation;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\AdminPattern;
use PHPUnit\Framework\TestCase;
class AdminGrantedAccessInformationTest extends TestCase
{
public function testGetPatternsReturnsEntryRegex(): void
{
$this->assertSame([AdminPattern::GRANTED_ACCESS_ENTRY], AdminGrantedAccessInformation::getPatterns());
}
public function testEntryRegexMatchesFullLine(): void
{
$line = "[16-04-26 18:35:10.000] AdminUser granted admin access level on Player1.";
$this->assertSame(1, preg_match(AdminPattern::GRANTED_ACCESS_ENTRY, $line, $m));
$insight = new AdminGrantedAccessInformation();
$insight->setMatches($m, 0);
$this->assertSame('Admin granted access', $insight->getLabel());
$this->assertSame('AdminUser granted admin to Player1', $insight->getValue());
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace IndifferentKetchup\Codex\Test\Tests\Games\ProjectZomboid\Analysis;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminReloadedOptionsInformation;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\AdminPattern;
use PHPUnit\Framework\TestCase;
class AdminReloadedOptionsInformationTest extends TestCase
{
public function testGetPatternsReturnsEntryRegex(): void
{
$this->assertSame([AdminPattern::RELOADED_OPTIONS_ENTRY], AdminReloadedOptionsInformation::getPatterns());
}
public function testEntryRegexMatchesFullLine(): void
{
$line = "[16-04-26 18:37:00.014] AdminUser reloaded options.";
$this->assertSame(1, preg_match(AdminPattern::RELOADED_OPTIONS_ENTRY, $line, $m));
$insight = new AdminReloadedOptionsInformation();
$insight->setMatches($m, 0);
$this->assertSame('Admin reloaded options', $insight->getLabel());
$this->assertSame('AdminUser', $insight->getValue());
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace IndifferentKetchup\Codex\Test\Tests\Games\ProjectZomboid\Analysis;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\AdminTeleportedInformation;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\AdminPattern;
use PHPUnit\Framework\TestCase;
class AdminTeleportedInformationTest extends TestCase
{
public function testGetPatternsReturnsEntryRegex(): void
{
$this->assertSame([AdminPattern::TELEPORTED_ENTRY], AdminTeleportedInformation::getPatterns());
}
public function testEntryRegexMatchesPositiveZ(): void
{
$line = "[16-04-26 18:38:00.225] AdminUser teleported Player1 to 1100,2200,0.";
$this->assertSame(1, preg_match(AdminPattern::TELEPORTED_ENTRY, $line, $m));
$insight = new AdminTeleportedInformation();
$insight->setMatches($m, 0);
$this->assertSame('Admin teleported', $insight->getLabel());
$this->assertSame('AdminUser teleported Player1 to 1100,2200,0', $insight->getValue());
}
public function testEntryRegexHandlesNegativeZ(): void
{
$line = "[16-04-26 18:39:15.500] AdminUser teleported Player2 to 1100,2200,-1.";
$this->assertSame(1, preg_match(AdminPattern::TELEPORTED_ENTRY, $line, $m));
$this->assertSame('-1', $m['z']);
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace IndifferentKetchup\Codex\Test\Tests\Games\ProjectZomboid\Analysis;
use IndifferentKetchup\Codex\Analysis\ProjectZomboid\PvpDamageInformation;
use IndifferentKetchup\Codex\Pattern\ProjectZomboid\PvpPattern;
use PHPUnit\Framework\TestCase;
class PvpDamageInformationTest extends TestCase
{
public function testGetPatternsReturnsCombatRealRegex(): void
{
$this->assertSame([PvpPattern::COMBAT_REAL], PvpDamageInformation::getPatterns());
}
public function testCombatRealMatchesPositiveDamageRealWeapon(): void
{
$line = 'Combat: "Player1" (1005,2005,0) hit "Player2" (1006,2005,0) weapon="Tire Iron (Worn)" damage=0.112317.';
$this->assertSame(1, preg_match(PvpPattern::COMBAT_REAL, $line, $m));
$insight = new PvpDamageInformation();
$insight->setMatches($m, 0);
$this->assertSame('PvP combat', $insight->getLabel());
$this->assertSame('Player1 hit Player2 with Tire Iron (Worn)', $insight->getValue());
}
public function testCombatRealRejectsZombieWeapon(): void
{
$line = 'Combat: "Player1" (1005,2005,0) hit "Player1" (1005,2005,0) weapon="zombie" damage=-1.000000.';
$this->assertSame(0, preg_match(PvpPattern::COMBAT_REAL, $line));
}
public function testCombatRealRejectsZeroDamage(): void
{
$line = 'Combat: "Player1" (1100,2200,0) hit "Player2" (1100,2201,0) weapon="vehicle" damage=0.000000.';
$this->assertSame(0, preg_match(PvpPattern::COMBAT_REAL, $line));
}
public function testCombatRealRejectsNegativeDamage(): void
{
$line = 'Combat: "Player1" (1005,2005,0) hit "Player2" (1005,2005,0) weapon="Bare Hands" damage=-0.500000.';
$this->assertSame(0, preg_match(PvpPattern::COMBAT_REAL, $line));
}
public function testIsEqualCoalescesSameAttackerVictimWeapon(): void
{
$a = $this->insightFor('Player1', 'Player2', 'Bare Hands');
$b = $this->insightFor('Player1', 'Player2', 'Bare Hands');
$c = $this->insightFor('Player1', 'Player2', 'Tire Iron');
$this->assertTrue($a->isEqual($b));
$this->assertFalse($a->isEqual($c));
}
private function insightFor(string $attacker, string $victim, string $weapon): PvpDamageInformation
{
$insight = new PvpDamageInformation();
$insight->setMatches([
'attacker' => $attacker,
'victim' => $victim,
'weapon' => $weapon,
], 0);
return $insight;
}
}

View File

@@ -20,7 +20,7 @@ class ProjectZomboidItemLogTest extends TestCase
$log = (new ProjectZomboidItemLog())->setLogFile(new PathLogFile($this->fixturePath())); $log = (new ProjectZomboidItemLog())->setLogFile(new PathLogFile($this->fixturePath()));
$log->parse(); $log->parse();
$this->assertCount(10, $log->getEntries()); $this->assertCount(20, $log->getEntries());
} }
public function testFieldsRegexExtractsItemAndDelta(): void public function testFieldsRegexExtractsItemAndDelta(): void

View File

@@ -20,7 +20,7 @@ class ProjectZomboidPerkLogTest extends TestCase
$log = (new ProjectZomboidPerkLog())->setLogFile(new PathLogFile($this->fixturePath())); $log = (new ProjectZomboidPerkLog())->setLogFile(new PathLogFile($this->fixturePath()));
$log->parse(); $log->parse();
$this->assertCount(6, $log->getEntries()); $this->assertCount(10, $log->getEntries());
} }
public function testFieldsRegexHandlesEventRow(): void public function testFieldsRegexHandlesEventRow(): void