Repository navigation
feat(evtx): inventory Windows event log records offline - #9186
2SinceJuly wants to merge 49 commits into
Conversation
Codex Review Summary: ❌ FailedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
2118771 to
56ec543
Compare
56ec543 to
e4b9157
Compare
[Medium impact] The PR adds a bounded local-file inventory path to CLI and MCP callers. The file reads and summary delivery look sound, but the two repository-required cleanup changes should land before merging. FindingsFix with agent prompt### Issue 1
src/domain/evtxArchive/parseEvtxArchive.ts:37-38
`reader` creates a new `BinaryReader` for every field read, including several reads per event. Large inventories create thousands of avoidable short-lived objects. The tool-design guide requires holding or caching one `BinaryReader` per `Buffer`. Reuse a reader for each file and chunk to satisfy this requirement before merging.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
### Issue 2
src/application/evtxArchive/EvtxArchiveService.ts:34-38
`inputFailure` remains after file failures moved to `classifyProviderFailure`. Its only caller is behind an `isAbsolute` check that `absoluteLocalPathStringSchema` already enforces, and that caller never supplies a cause. These unreachable branches obscure which code owns file errors.
The repository requires removing superseded wrappers after checking their consumers. Remove this helper, the redundant check, and the unused `fixedAllowanceOptions` import before merging.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.SummaryAdds offline EVTX record-header inventory through CLI and MCP, with typed summaries linked to complete parent Evidence.
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart LR
CLI[CLI request] --> Service[EVTX service]
MCP[MCP request] --> Service
Service --> Read[Bounded stable file read]
Read --> Parse[Record-header inventory]
Parse --> Evidence[Complete Evidence]
Evidence --> Complete[Complete reply]
Evidence --> Retain[Retain parent Evidence]
Retain --> Summary[Typed summary with parent link]
Reviews (33) · Last reviewed commit: "Merge origin/main into feat/9174-evtx-ar..." · Reviewed by Greptile |
Windows event logs are routinely supplied during incident response, but rea could only read them by booting the source system or reaching a live Event Log service. This adds one offline reader over the existing artifact and Evidence machinery, so nothing outside the selected file is touched. This change covers the first independently mergeable step: file and chunk structure, record numbers, record-header timestamps and declared sizes, plus chunk header checksum evaluation. The channel, provider, event ID and EventData live in the embedded event XML and are deliberately absent rather than guessed, and source_coverage names each of those as not-decoded. That keeps the contract honest while the XML and template decode follow in later steps. A short or wrapped chunk does not discard the events it produced, and a chunk that fails its checksum is reported instead of corrected.
e4b9157 to
239db5a
Compare
digest() joined the prefix and the hex with ':', but prefixedDigestSchema requires '<prefix>_<64 hex>'. Every archive_id, event_id and diagnostic_id the parser produced therefore failed evtxArchiveSchema, which MCP registers as the success output — a valid inspection was rejected at the boundary, including an empty one, since it still carries an archive_id. Use the underscore the schema declares and parse the parser's own output through the schema in a regression so the two cannot drift apart again.
|
Fixed the first one; the remaining findings need more than a one-line correction and I have not attempted them in this pass — listing what I confirmed and what I did not. Fixed — "Generated IDs fail output checks" ( The remaining five threads are real work on the binary format, and I would rather say so than guess:
Each needs a fixture with real byte structure to verify against, and I did not want to push a rewrite of the chunk reader that I could not check. If you want them in one go, I will build the fixtures first and land the chunk-boundary changes together in a follow-up. |
`file_version` read 0x18/0x1a, which is the eight-byte next-record identifier and its neighbour, so a normal 3.1 file reported a version that tracked its record count. The version lives at 0x24 (minor) and 0x26 (major); read those and move the fixture's version bytes to match. `chunkChecksumMatches` summed the header words, but EVTX signs a chunk with CRC32 over 0x00..0x77 and 0x80..0x1ff. The two only agree on bytes chosen to make them agree, which is what the old test did -- it asserted an intact chunk was `mismatched` and then re-derived the same sum to produce a `matched` one. Healthy chunks from a real log were therefore reported as corrupt, and a real corruption had a 1-in-2^32 chance of passing. The fixture now writes a valid signature, and the test computes its own CRC32 rather than sharing the parser's routine.
Chunk offset 0x08 holds the first event record number, not a chunk sequence number, but the parser read it as both: every event's chunk_number and event_id were built from it, and it was compared against the physical chunk index to raise chunk-number-mismatch. An intact log whose chunks do not start at record 1 - a wrapped file, or one exported mid-stream - therefore got a false mismatch on every chunk and carried record numbers in the chunk fields. Number chunks by their physical position, which is the only value this parser can vouch for, and check 0x08 on its own: it must equal the first record's own id, reported as first-record-number-mismatch when it does not. The test fixture now states a realistic first record number instead of the chunk index, and covers both a mid-stream log and the new diagnostic.
The chunk-level first_timestamp_ms, last_timestamp_ms and record ids were stamped from the first and last value that happened to be set. An unset timestamp on the first record therefore published a later record's time, and an unset one on the last record left the previous value in place, so the endpoints described inner records instead of the chunk's actual ends. Assign them by position: the first record's values on the first iteration, and overwrite both ends on every record after it. Also drop .nonnegative() from the two timestamp fields - timestampMs already accepts pre-1970 clocks as negative Unix milliseconds, so the output schema rejected values the parser can legally produce.
readChunk scanned to the physical chunk end, so a wrapped chunk that discarded records without zeroing them could present stale bytes that still parse as a record header, and those were inventoried as live events. A real writer maintains 0x30 as the offset of its free space. Bound the scan by that field, falling back to the chunk end when it is outside the header or the chunk, because a writer that did not maintain it must not make the whole chunk unreadable. The test fixture now maintains 0x30 as a real writer does - without it every chunk would read as fully used and the bound would go untested.
The guide still said each chunk reports a number stored in its header, and that a chunk disagreeing with its position makes coverage partial. Both stopped being true when chunks were renumbered by position: the header field at 0x08 is the first event record number, and the disagreement is now reported as first-record-number-mismatch rather than as a coverage defect. An analyst reading the old wording could take a stored record number for a file position, or expect a wrapped log to read partial when it is intact.
The single describe block grew to 160 lines with the new archive tests, tripping max-lines-per-function (150) in Static checks. Grouping the record-limit and empty-log cases with the other inventory assertions and moving the chunk-header cases into their own describe keeps every assertion without a lint suppression.
The new inspect-evtx-archive command declared maxFileBytes and maxRecords straight from the domain schema, so the CLI received raw strings and the boundary test that walks every numeric option rejected both. Route them through cliDecimalField like the other numeric options so 0x10 and 1e3 stay refused instead of being coerced to 16 and 1000.
The guide said source_coverage.templates is always not-decoded, but the
output schema (templates: z.literal("not-resolved")) and the parser both
emit not-resolved. A caller following the guide would check for a value
the tool never produces.
main replaced bespoke application-tool registration with the service binding table and the contract command factory; register inspect_evtx_archive as one binding row, describe it through the shared contract metadata, and follow the artifact modules that moved to src/resources.
The merge left a duplicate src/cliCommandNames.ts that main had already moved into contracts, so the stale copy is gone and its one importer is restored to the contract path. main's guards then rejected this branch's own code: the reader now charges through BinaryReader, digests through sha256Hex, cancels through cancelledBy and refuses limits with fixedAllowanceOptions. The contract declares the CLI command its registrar already exposed, and its single format is an enum because argv has no projection for a bare literal.
format:check runs oxfmt and three of the files this branch adds or edits are not in its shape: the rule baseline JSON, the CLI command, and the service tool bindings. Formatting only, no behavior change.
The branch adds the tool, so its advertised input and output compact schemas need an entry under scripts/verify/advertised-schemas/tools/. Build package rejects a catalog with an unrecorded tool, which is what kept that job red.
The CLI advertised no --detail or --evidence_output for inspect-evtx-archive, so `--detail summary --evidence_output <path>` was rejected as an unknown flag and the acceptance test that exercises summary delivery exited 1. The retained summary projection already existed; only the producer, contract, MCP binding and CLI command never selected it. Bind the tool as a retained summary, mirroring inspect_python_pyc and inspect_erlang_beam: the contract takes a detail-discriminated delivery union, the MCP binding retains the complete Evidence behind a summary, and the CLI delivers either form beside its bundle. The summary branch advertises the summary view request rather than forbidding view, so the compact input presentation keeps a typed property.
|
Pushed Root cause: The fix mirrors Validation run locally (Node 24.22.2, macOS arm64):
Not run: the full test shard matrix, and I did not reproduce on Linux. The other red shards on this branch were not investigated in this pass. |
8c5ba18 narrowed the archive inventory input schema, which changed the input compact hash. The build job compares the committed summary against the generated one and failed because the file still carried the previous hash.
|
Pushed
|
|
Merged After the merge, locally:
CI is re-running on Two questions so this one can land without another round trip: is the step split (header inventory first, then XML event decoding) the shape you want for the evtx archive issue, or would you rather see it as one larger MCP surface? And should |
The canonical CLI catalog requires every exposed option to carry a description. inspect-evtx-archive took its format enum from the contract without one, so the product catalog boundary test reported inspect-evtx-archive.options.format as undescribed.
The CLI declares `callerPaths: ["path"]`, so it resolves a relative path before validating it. The contract still used localPathStringSchema, which admits a relative path as typed, so the CLI and the contract disagreed and cliContractCommandParity failed for inspect-evtx-archive: every other callerPath tool narrows with absoluteLocalPathStringSchema.
`readFailure` mapped an `unknown` read failure to `AnalysisError` in its own branch chain and was exempted from the provider-failure-classifier rule by a new baseline entry. The shared owner already covers every branch it reimplemented: cancellation with the reader's recorded reason, integrity, the file-size budget, path/format refusals, and the EACCES/EPERM and unreadable-path projections. Keeping a second copy meant later fixes to those branches would miss EVTX. The service now supplies a file dialect — the selected path, the "event log" description, and the `max_file_bytes` recovery — to `classifyProviderFailure`, and the baseline entry is removed so the count falls back to zero. One observable change follows from using the shared projection: an unreadable path is now an `invalid_value` issue that disagrees with the input contract, matching the other file-backed importers, instead of an `invalid_format` issue that claimed the caller's input conformed. The test asserts the new shape and a second test pins that an oversized log names `max_file_bytes` as the adjustable budget.
|
TL;DR: On head 6b77e42, the PR's 3 changed test files passed on Node 22.23.4, 24.22.1 and 26.12.1. Each run had 29 passing tests. The head is 538 commits behind main a2acbe3, and I did not merge main. My last comment tested head 5077062. This run is on head 6b77e42.
I ran CI on 6b77e42 shows mergeable Of the check runs, 30 were Not run
Test setupCommandsnpm ci --offline
npm run test:prepare
xvfb-run -a npm run test:focused -- src/application/evtxArchive/EvtxArchiveService.test.ts src/domain/evtxArchive/parseEvtxArchive.test.ts tests/acceptance/evtxSummary.test.ts🤖 Written and tested with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊 |
|
Thanks for the independent run on Noted the three items you did not run ( |
# Conflicts: # src/domain/analysisView/analysisViewResult.ts
evtxArchiveToolContracts imported evtxArchiveSummaryViewResultSchema from the analysisViewResult barrel, so registering the command resolved the heavy shared analysis-view module on every single-command startup. tests/boundary/cli/cliStartupImports.test.ts asserts a standalone command resolves no heavy shared module and failed with Set{'analysis-view-result'}. Every sibling contract imports its summary schema straight from domain/analysisView/summarySchemas/*.js; do the same here.
When max_records stopped inside a chunk, or a damaged record ended the walk before the chunk's last record, the chunk reported the last listed record as its last_event_record_id and last_timestamp_ms. Those fields describe the chunk's final record, so an analyst read the wrong ending time or record identifier while unexamined records remained. Report null for both whenever the walk stopped early, and state the rule in the guide.
The CLI now derives both bounds from inspectEvtxArchiveInputSchema, so evtxArchiveFileBytesSchema and evtxArchiveRecordsSchema have no consumer. AGENTS.md asks for superseded aliases to go once their consumers are checked, and keeps specs and task lists in the PR discussion rather than in Git, so docs/specs/evtx-archive/inventory is removed too.
CI's format:check (oxfmt) rejects the two long chunk(...) calls added in the chunk-boundary tests; wrapping them restores the shared formatter baseline.
main moved the application-workflow bindings into src/server/sessionToolBindings.ts and split the contract-command runners out of contractCommand.ts; keep those refactors, port the inspect_evtx_archive binding alongside the other application workflows, and import deliverWithService from contractCommandRunners.
| const reader = (bytes: Buffer): BinaryReader => | ||
| new BinaryReader(bytes, true, "evtx"); |
There was a problem hiding this comment.
Every field rebuilds its reader
reader creates a new BinaryReader for every field read, including several reads per event. Large inventories create thousands of avoidable short-lived objects. The tool-design guide requires holding or caching one BinaryReader per Buffer. Reuse a reader for each file and chunk to satisfy this requirement before merging.
Context Used: AGENTS.md (source)
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/evtxArchive/parseEvtxArchive.ts
Line: 37-38
Comment:
**Every field rebuilds its reader**
`reader` creates a new `BinaryReader` for every field read, including several reads per event. Large inventories create thousands of avoidable short-lived objects. The tool-design guide requires holding or caching one `BinaryReader` per `Buffer`. Reuse a reader for each file and chunk to satisfy this requirement before merging.
**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
| const inputFailure = (message: string, cause?: unknown) => | ||
| new AnalysisInputError( | ||
| operation, | ||
| { | ||
| cause, |
There was a problem hiding this comment.
inputFailure remains after file failures moved to classifyProviderFailure. Its only caller is behind an isAbsolute check that absoluteLocalPathStringSchema already enforces, and that caller never supplies a cause. These unreachable branches obscure which code owns file errors.
The repository requires removing superseded wrappers after checking their consumers. Remove this helper, the redundant check, and the unused fixedAllowanceOptions import before merging.
Context Used: AGENTS.md (source)
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/application/evtxArchive/EvtxArchiveService.ts
Line: 34-38
Comment:
**Retired failure code remains**
`inputFailure` remains after file failures moved to `classifyProviderFailure`. Its only caller is behind an `isAbsolute` check that `absoluteLocalPathStringSchema` already enforces, and that caller never supplies a cause. These unreachable branches obscure which code owns file errors.
The repository requires removing superseded wrappers after checking their consumers. Remove this helper, the redundant check, and the unused `fixedAllowanceOptions` import before merging.
**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
Refs #9174. Adds offline, read-only Windows EVTX record inventory through CLI and MCP. Event content is not executed and no live Event Log service is contacted. This inventory slice does not establish complete event semantics.
Summary delivery now has a registered, typed EVTX projector. It retains file/version facts, counts and source coverage and links the full parent Evidence rather than returning the record array inline. Bounded inventory remains partial source coverage.
Validation on head
ae3b7c4a4:readFailureclassifies the event log read throughclassifyProviderFailurewith a file dialect, and theprovider-failure-classifier-baseline.jsonexemption for this service is removed.npm run check:fastpasses (typecheck, lint, architecture guards across 2831 files), and bothEvtxArchiveService.test.tscases pass, including a new one pinning that an oversized log namesmax_file_bytesas the adjustable budget.Earlier on head 03fc414, the compiled CLI summary/readback regression passed using a generated EVTX fixture with two events and a one-record limit;
docs:check(9 README checks) and test discovery passed then. No real Windows event log, Windows runtime or full repository suite was verified.Author readiness
Human owner: @2SinceJuly