Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
519ebaa
feat(diagnostics): report a byte entropy profile for one local file
mvanhorn Oct 12, 2026
b82e190
fix(diagnostics): flag zero-size files as not shown empty
mvanhorn Oct 13, 2026
b87f511
fix(diagnostics): merge main and preserve entropy boundary failures
morluto Oct 13, 2026
7a67707
fix(mcp): reject unsupported diagnostic summaries before inspection
morluto Oct 13, 2026
eccc741
Merge remote-tracking branch 'origin/main' into fix/byte-entropy-profile
morluto Oct 13, 2026
a156b1d
fix(ci): repair integrated checks and Hopper test baseline
morluto Oct 13, 2026
a2f6136
test(entropy): use shared MCP schema verification after merge
morluto Oct 13, 2026
4df3682
chore: merge current main into PR #2331
morluto Oct 13, 2026
f54b2ae
Merge branch 'main' into fix/byte-entropy-profile
morluto Oct 13, 2026
3a794e9
Merge branch 'main' into fix/byte-entropy-profile
mvanhorn Oct 14, 2026
27c6fd9
fix(catalog): list inspect_byte_entropy under its own provider
mvanhorn Oct 15, 2026
f7367fc
fix(cli): resolve the byte-entropy path with absoluteCallerPath
mvanhorn Oct 19, 2026
4e6600d
Merge remote-tracking branch 'upstream/main' into fix/byte-entropy-pr…
mvanhorn Oct 19, 2026
e3e5891
Merge origin/main into fix/byte-entropy-profile
kaoru0822-kitauji Oct 21, 2026
1eef8d6
fix(diagnostics): retain entropy read cleanup ownership
morluto Oct 21, 2026
da99090
docs(diagnostics): explain entropy output capacity
morluto Oct 21, 2026
9be3d92
fix(diagnostics): preserve entropy cancellation outcomes
morluto Oct 21, 2026
cc585b5
fix(diagnostics): close the entropy input and warn on large reports
cursoragent Oct 21, 2026
2489602
fix(diagnostics): keep byte-entropy registration mergeable with main
cursoragent Oct 22, 2026
9d37354
fix(diagnostics): register byte entropy with the shared tool options
cursoragent Oct 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,8 @@ For headerless DOS COM, explicitly open with `format: "dos-com"` (CLI
analysis: the entry is `0x10100`, file offset zero, with imposed real-mode segment
context. PSP/stack/device state remains unmodeled. See [DOS guide](https://github.com/morluto/rea/blob/main/docs/ghidra-dos.md).

Use `inspect_byte_entropy` to triage high- and low-entropy ranges before extraction.

For other headerless images (embedded firmware without ELF/Mach-O/PE/MZ
headers), open with `format: "raw-binary"`, `architecture` (`x86`, `x86_64`,
`arm`, or `arm64`), and `entry_point` (`0x` hex). File offset 0 is mapped at
Expand Down
72 changes: 72 additions & 0 deletions docs/binary-diagnostics.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,3 +190,75 @@ Large Evidence envelopes may require a caller-configured MCP transport receive
buffer because envelope copies add overhead. Requests honor cancellation during
snapshot reading, directory traversal and payload hashing. The operation reads
regular files only and rejects symbolic links.

## Byte entropy triage

`inspect_byte_entropy` / `inspect-byte-entropy` profiles any local regular file
without an analysis engine, execution, extraction or network access.

```sh
rea inspect-byte-entropy ./firmware.bin --block-size 4096 --json
rea inspect-byte-entropy ./firmware.bin --offset 4096 --length 65536 --json
```

```json
{
"name": "inspect_byte_entropy",
"arguments": { "path": "/artifacts/firmware.bin", "detail": "summary" }
}
```

Complete Evidence includes `artifact` (original path, byte size and SHA-256),
`block_size`, `window`, `file_entropy`, `thresholds`, `blocks`, `runs` and
`limitations`. For a 4096-byte zero-filled file, the entropy fields are:

```json
{
"block_size": 4096,
"window": { "offset": 0, "length": 4096 },
"file_entropy": 0,
"thresholds": { "high": 7.2, "low": 1 },
"blocks": [{ "offset": 0, "length": 4096, "entropy": 0 }],
"runs": [{ "offset": 0, "length": 4096, "classification": "low" }]
}
```

Offsets and lengths are decimal byte counts. Blocks begin at the requested
`offset` (default zero); omitted `length` extends to EOF. Explicit windows past
EOF fail rather than silently clipping. The final block may be shorter.
`block_size` must be a power of two from 256 through 65536, default 4096.
SHA-256 and `file_entropy` always cover the entire file, including when a window
is selected. Empty files and empty windows are accepted; empty entropy is zero
by convention. The tool reads the size the file reports. A file that reports size
0, such as a Linux `/proc` entry, returns no blocks with a limitation that the
result does not show the file is empty. File identity, size and timestamps are checked across the read;
detected changes produce an error rather than Evidence.

Shannon entropy is reported in bits per byte from 0 to 8, rounded to four decimal
places. Adjacent blocks with reported entropy at least 7.2 form `high` runs;
blocks at most 1.0 form `low` runs. Other blocks interrupt runs. Entropy does not
prove encryption, and this measure cannot distinguish encrypted from compressed
data. Small blocks can underestimate entropy; the result is a triage clue.

MCP `detail: "summary"` retains complete Evidence in the session and returns
file entropy, block/run counts, thresholds, the selected window, and the ten
longest runs (ties ordered by file offset). Use its `parent_evidence_id` to
retrieve complete Evidence, or request its summary with `inspect_analysis_view`.
The CLI returns complete Evidence through the same service. Summary detail
requires a session capable of retaining Evidence.

Reads use one block-sized buffer and a 256-entry histogram. Full Evidence and
its serialization require memory proportional to the number of selected
blocks; summary delivery reduces returned output but still retains that full
series. Narrow the window or increase block size to reduce retained rows.

Local service measurement (macOS arm64, Node 24.18.0, 100,000,000-byte file,
4096-byte blocks, file already in the OS cache): first process run took 1.113 s
wall / 1.148 s CPU with 145.3 MiB peak RSS; a second run in the same process took
1.015 s / 1.035 s CPU, with cumulative peak RSS 155.8 MiB. Each read 100,000,000
bytes and produced 24,415 blocks. Measurements include Evidence construction,
summary projection and JSON serialization, with no child processes. Complete
Evidence serialized to 1,122,303 bytes and its summary to 2,705 bytes. Cold disk
I/O, token counts and an agent investigation were not measured; there was no
previous equivalent tool to benchmark. These figures do not establish constant
memory for retained Evidence or faster agent task completion.
2 changes: 2 additions & 0 deletions docs/user-visible-errors.csv
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,5 @@ Then rerun this installer.",implemented,verified by shell branch inspection
90,install.sh:version mismatch,Installed rea reports a different version,installed version ACTUAL does not match EXPECTED.,Low risk; gives exact integrity mismatch,Keep current copy,unchanged,verified by exact installer test
90.5,@modelcontextprotocol/server:tool input validation,Caller sends arguments that violate a declared tool schema,"Input validation error: Invalid arguments for tool TOOL: FIELD: Invalid input: expected TYPE, received TYPE",Low risk; public tool and field names plus exact type correction,Keep SDK-generated copy,unchanged,verified by real in-memory MCP client/server call with wrong argument type
90.6,incur:unknown CLI command,Caller enters an unknown REA command,"'COMMAND' is not a command for 'rea'. Suggested command: rea --help",Low risk; identifies input and exact discovery action,Keep framework-generated copy,unchanged,verified by real packaged dispatcher invocation
91,src/application/binaryDiagnostics/ByteEntropyService.ts,Invalid file or window,"Expected a regular file.; Selected file could not be found.; Selected byte window extends beyond the end of the file.; File size exceeds exact numeric offset representation.",Invalid selection cannot produce complete entropy Evidence,Choose a readable regular file and a window within its byte size,implemented,entropy service and MCP boundary tests
92,src/domain/analysisView/byteEntropyView.ts,Non-summary entropy view,Byte entropy Evidence supports the summary view; retrieve parent Evidence for the complete block series.,Unsupported view selection,Use the summary view or retrieve complete parent Evidence,implemented,typed input rejection
1 change: 1 addition & 0 deletions src/application/CapabilityInventory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,7 @@ export const compactToolAvailability = (
const availabilityFor = (context: AvailabilityContext): Availability => {
// These built-in workflows accept a caller-selected endpoint; they do not load the optional passive provider.
if (
context.name === "inspect_byte_entropy" ||
context.name === "observe_web_execution" ||
context.name === "inspect_web_event_listeners"
)
Expand Down
114 changes: 114 additions & 0 deletions src/application/binaryDiagnostics/ByteEntropyService.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { byteEntropySchema } from "../../domain/native/byteEntropy.js";
import { ByteEntropyService } from "./ByteEntropyService.js";

it("keeps whole-file identity and entropy while selecting unaligned blocks and a partial tail", async () => {
const root = await createTestTempDirectory("rea-entropy-");
const path = join(root, "bytes");
const bytes = Buffer.from(Array.from({ length: 1024 }, (_, i) => i % 256));
await writeFile(path, bytes);
const result = await new ByteEntropyService().inspect({
path,
offset: 3,
length: 513,
block_size: 256,
});
if (!result.ok) throw result.error;
const report = byteEntropySchema.parse(result.value.normalized_result);
expect(report.blocks).toEqual([
{ offset: 3, length: 256, entropy: 8 },
{ offset: 259, length: 256, entropy: 8 },
{ offset: 515, length: 1, entropy: 0 },
]);
expect(report.file_entropy).toBe(8);
expect(report.artifact).toEqual({
path,
bytes: 1024,
sha256: createHash("sha256").update(bytes).digest("hex"),
});
expect(result.value.subject?.digest.sha256).toBe(report.artifact.sha256);
expect(result.value.confidence).toBe("observed");
});

it("rejects missing files, non-files and windows beyond EOF, but accepts empty windows", async () => {
const root = await createTestTempDirectory("rea-entropy-input-");
const path = join(root, "empty");
await writeFile(path, "");
const service = new ByteEntropyService();
for (const input of [
{ path: join(root, "missing") },
{ path: root },
{ path, offset: 1 },
{ path, length: 1 },
{ path: "relative" },
]) {
const result = await service.inspect(input);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
}
const result = await service.inspect({ path });
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toMatchObject({
blocks: [],
runs: [],
file_entropy: 0,
window: { offset: 0, length: 0 },
});
expect(
byteEntropySchema.parse(result.value.normalized_result).limitations,
).toContainEqual(expect.stringContaining("reports a size of 0"));
});

it.skipIf(process.platform !== "linux")(
"marks a generated /proc file that reports size 0 as not shown empty",
async () => {
const result = await new ByteEntropyService().inspect({
path: "/proc/version",
});
if (!result.ok) throw result.error;
const report = byteEntropySchema.parse(result.value.normalized_result);
expect(report.artifact.bytes).toBe(0);
expect(report.limitations).toContainEqual(
expect.stringContaining("Linux /proc entries"),
);
},
);

it("adds no zero-size limitation to a file with content", async () => {
const root = await createTestTempDirectory("rea-entropy-nonempty-");
const path = join(root, "one");
await writeFile(path, "x");
const result = await new ByteEntropyService().inspect({ path });
if (!result.ok) throw result.error;
expect(
byteEntropySchema
.parse(result.value.normalized_result)
.limitations.join(" "),
).not.toContain("reports a size of 0");
});

it("honors cancellation before and during streaming", async () => {
const root = await createTestTempDirectory("rea-entropy-cancel-");
const path = join(root, "bytes");
await writeFile(path, Buffer.alloc(1024 * 1024));
const service = new ByteEntropyService();
expect(
await service.inspect({ path }, { signal: AbortSignal.abort() }),
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
const controller = new AbortController();
const pending = service.inspect(
{ path, block_size: 256 },
{ signal: controller.signal },
);
setTimeout(() => controller.abort(), 5);
expect(await pending).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
});
Comment thread
morluto marked this conversation as resolved.
Resolved
Loading
Loading