Skip to content

feat(windows): inspect Shell Link (.lnk) shortcut files - #7859

Merged
morluto merged 36 commits into
morluto:mainfrom
mvanhorn:feat/windows-shortcut
Nov 9, 2026
Merged

morluto merged 36 commits into
morluto:mainfrom
mvanhorn:feat/windows-shortcut

Conversation

@mvanhorn

@mvanhorn mvanhorn commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add inspect_windows_shortcut / inspect-windows-shortcut so one selected local Windows Shell Link (.lnk) can be read as Evidence without resolving or executing the target.

Problem and expected behavior

REA had no Shell Link reader. A local .lnk with HeaderSize 0x4C and CLSID 00021401-0000-0000-C000-000000000046 should return header flags and FILETIMEs, IDList items, LinkInfo volume/network names, StringData, ExtraData (including Tracker droid facts labelled derived), and derived observations such as argument length and a minimized ShowCommand. Coverage is never complete when issues are present.

Change and scope

Portable parser, provider, service, CLI, and MCP follow the existing binary-diagnostics inspectors. The selected path is a regular file; size, IDList, ExtraData, and string budgets apply; cancellation is honored. Unknown IDList items and ExtraData signatures stay raw with SHA-256. The target path is not opened. inspect_artifact routing is unchanged: artifactFormatMetadata.ts is occurrence metadata, not a sniff table.

Follow the contribution scope.
Unresolved scope, authority, side effects, or required verification block
integration. Link the required maintainer scope decision for new providers or
capabilities involving target execution, injection, mutation, or protection
recovery; ordinary fixes within existing boundaries may state "not applicable".
Draft PRs may leave the scope decision pending and the readiness and merge checklists
unchecked. Maintainers can help resolve open questions.

Contract and boundary impact

  • Semantic owner and earliest changed stage: parseWindowsShortcut owns Shell Link bytes. WindowsShortcutProvider owns the stable regular-file read. WindowsShortcutService owns Evidence provenance (subject.format: "file"). CLI/MCP consume that Evidence.
  • Contribution scope fit and linked maintainer decision: not applicable. Static read of a caller-selected local file; no target execution, injection, mutation, or protection recovery.
  • CLI and MCP/tool-catalog contract: new inspect-windows-shortcut / inspect_windows_shortcut. MCP path is an absolute local path. CLI resolves relative paths against the working directory.
  • Provider, bridge, target-format, or platform compatibility: built-in rea-windows-shortcut. Portable on supported Node hosts; no Windows SDK, COM, or engine.
  • Evidence, artifact, provenance, or reconstruction contract: observed rows plus derived observations (arguments_present, argument_length, target_extension, show_command_minimized, icon_location_differs_from_target). Tracker version-1 MAC/timestamp is labelled derived.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): regular file only; symlinks rejected. readStableArtifact + ArtifactResourceScope; cleanup retained through native finalization and stable-artifact consumer regressions.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact (CI generates and validates ignored catalogs and skills/; edit authored instructions in .agents/skills/reverse-engineer-anything/ and never commit build outputs): authored skill, README rows including translations, docs/windows-shortcut.md, catalog-builder identity for WINDOWS_SHORTCUT_PROVIDER. No generated catalogs committed.

Expected effects (check known effects; use documentation-only on its own).
Unchecked items do not establish absence; leave uncertainties visible.

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

  • Tests added or updated: synthesized fixtures (PowerShell hidden-window + icon spoof, network-share LinkInfo, Tracker v1, ANSI strings, truncated StringData, unknown ExtraData signature, wrong CLSID), parser/domain/service tests, CLI+stdio MCP acceptance, MCP advertisement, filesystem symlink/budget/cancellation, shared local-tool contracts, CLI coverage, stable-artifact consumers, native acquisition finalization, early cancellation.
  • Base reproduction or other evidence: on upstream/main, inspect-windows-shortcut is not a CLI command and inspect_windows_shortcut is not advertised.
  • User-visible CLI/MCP output (if applicable): CLI JSON for the synthesized PowerShell fixture reports show_command.decoded: "minimized", arguments containing -WindowStyle Hidden, and derived icon_location_differs_from_target: true with coverage.status: "complete". A wrong CLSID returns invalid_request / invalid_format.
  • Remaining proof gaps: real Explorer-written .lnk files and original-system ANSI code pages were not used. ANSI strings use a Latin1 projection.

For boundary fixes, identify the applicable boundary regressions
and lifecycle regressions
covered by the evidence above, and explain relevant gaps.

Covered: regular-file / symlink rejection, malformed HeaderSize/CLSID, truncated StringData with failing_offset, ExtraData overrun, IDList budget fail-closed, MCP relative-path rejection, cancellation before validation and during acquisition, descriptor close failure/cancel during finalization. No child-process launch in this workflow.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Validation performed

  • npm run check:fast — typecheck and lint passed after rebase onto upstream/main.
  • npm run test:local -- src/domain/native/windowsShortcut.test.ts src/native/windows/WindowsShortcutParser.test.ts src/application/binaryDiagnostics/WindowsShortcutService.test.ts src/application/binaryDiagnostics/BinaryDiagnosticsCancellation.test.ts — 4 files, 25 tests passed.
  • npm run test:focused -- tests/acceptance/windowsShortcutCli.test.ts tests/boundary/mcp/windowsShortcutMcp.test.ts tests/boundary/filesystem/windowsShortcut.test.ts tests/boundary/cli/cliToolCoverage.test.ts tests/acceptance/tools/localToolContracts.test.ts tests/process-global/stableArtifactConsumers.test.ts tests/boundary/providers/nativeArtifactFinalization.test.ts — 7 files, 217 tests passed.
  • npm run verify:test-discovery — discovered all 2743 test files exactly once.
  • npm run docs:check — passed, including tests/conformance/readmeConsistency.test.ts (9 tests passed).

Compatibility, safety, and release

  • Breaking changes or migration steps: none. Additive CLI/MCP operation.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable. No engine. Windows host not required.
  • Package or release metadata impact: new catalog identity rea-windows-shortcut; generated catalogs remain CI outputs.
  • Security, privacy, process, or containment review: reads one caller-selected regular file under existing artifact budgets. Does not follow the link target, call COM, or use the network.

Author readiness

Human owner: @mvanhorn

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

Demo

demo

Add inspect_windows_shortcut / inspect-windows-shortcut to read one
local Shell Link without resolving or executing the target. The report
keeps header flags and FILETIMEs, IDList items, LinkInfo volume and
network names, StringData, ExtraData including Tracker droid facts
labelled derived, and derived observations such as argument length
and a minimized ShowCommand.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-28T15:36:58.249533Z
We couldn’t complete this review. Comment @codex review to try again.
f08e340 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5 · The required deep-path regression test must distinguish the fixed code from the old memory-heavy implementation before merging.RetriggerView in GreptileConfidence Score: 4/5 Tier: plus

[Medium impact] The PR adds a bounded local-file inspection workflow for CLI and MCP callers.

The required deep-path regression test must distinguish the fixed code from the old memory-heavy implementation before merging.

Findings

  1. P2 Test misses excessive memory use ▶
Fix with agent prompt
### Issue 1
tests/boundary/filesystem/windowsShortcut.test.ts:365-371
The new deep-path test passes with the old eager `windowsAncestors` too. `linkedWindowsAncestor` already stops at the first failed `lstat`, so both assertions hold even when every parent string was built first. Excessive memory use could return without this test catching it.

The testing guide requires a regression for the demonstrated failure. Add a bounded check of memory growth or lazy parent construction that distinguishes the old implementation. This repository requirement must be satisfied 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!

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds static Windows Shell Link inspection through CLI and MCP without opening or executing the recorded target.

  • REA can show what a selected Windows shortcut records without following its target.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  Client[CLI or MCP] --> Input[Check caller input]
  Input --> Parents[Check local path and parents]
  Parents --> Read[Read one stable file]
  Read --> Parse[Parse shortcut bytes]
  Parse --> Evidence[Return Evidence with coverage]
  Parents --> Error[Return typed error]
  Read --> Error
  Parse --> Error
Loading

Reviews (34) · Last reviewed commit: "fix(native): walk Windows shortcut paren..." · Reviewed by Greptile

Comment thread src/cli/binaryDiagnosticsCommands.ts Resolved
- Decode counted StringData over its full CountCharacters payload.
- Locate LinkInfo string terminators before charging max_string_bytes
  and before decoding; an unterminated string is a coverage issue.
- Mark an IDList without a TerminalID and an out-of-range
  LinkInfoHeaderSize as partial coverage.
- Report arguments_present and argument_length as null when
  HasArguments is set but the field could not be read.
- Derive target_extension from the joined base path and suffix.
- Keep ISO dates for FILETIME and UUIDv1 timestamps before 1970.
- Retain the completed file snapshot on parse failures.
- Reject an empty CLI path before normalization.
- Select the shortcut contract from its family in focused tests.
- Fixture StringData no longer writes a NUL into the counted payload.
Comment thread src/domain/native/windowsShortcut.ts Resolved
Apply oxfmt to the two files format:check reports so Static checks passes.
inspect_windows_shortcut is advertised as offline, but the Windows path
schema admits UNC paths, and lstat on one can contact an SMB server and
offer the caller's credentials.

Reject UNC, extended UNC, and other host-prefixed device paths in the
provider before any filesystem call. Extended drive paths such as
\\?\C:\x stay allowed. A mapped network drive cannot be told from a
local drive by its path, and the docs say so.
File-entry items with bit 0x04 of the type byte, such as 0x36, store a
UTF-16LE name, but the parser always read it as Latin-1. The read stopped
at the first zero byte, so report.exe became r and an IDList-only
shortcut reported the wrong target_extension. Read those names as
UTF-16LE.
VolumeLabelOffset 0x14 selects VolumeLabelOffsetUnicode and is not itself a
label offset, and that Unicode field exists for no other value. The parser
treated any offset of 0x14 or more as having both, so a Unicode-only label such
as "OS" also produced a false ANSI label "O", and an ANSI label stored past 0x14
had its own bytes read as a Unicode offset.

Branch on the exact value in parseVolume, the one place that interprets it, and
report a VolumeID too short to hold the selected field. The fixture wrote both
encodings for a Unicode volume, which hid the false label, so it now writes one.
Resolve the docs index conflict by keeping the ESP flash image link from main
and the Windows shortcut link from this branch.
POSIX hosts read repeated leading slashes as one local root, so an
accepted selection such as ///tmp/shortcut.lnk is a local file there.
Apply the host-prefixed path check only on Windows, and take the
platform through the provider constructor so the Windows path forms
stay covered on every test host.
A stored IDList filename or relative path cannot show that an icon at a
full path is elsewhere, so the comparison reported a false difference.
Report null unless the icon and a recorded target are both full paths,
and assert the missing TerminalID issue by code and offset instead of
its message.
A walk that stopped before or inside ExtraData still reported the blocks
that HasExpString and HasExpIcon expect as absent, though they were never
checked for. Report a block as absent only after the TerminalBlock shows the
section was read in full. Without one the block stays unknown and coverage
stays partial.
Register inspect_windows_shortcut through the capability declarations and
services introduced on main instead of the removed per-service wiring in
createServer.
CommonNetworkRelativeLink NetworkProviderType is only meaningful when the
ValidNetType flag (0x2) is set. Return null otherwise.
MS-SHLLINK requires TerminalSize to be less than 4, not exactly 0. Treat
1, 2 and 3 as the terminal block instead of a malformed block.
… target

Include the EnvironmentVariableDataBlock literal target among the target
candidates for target_extension and the icon comparison. Variables are not
expanded and the target is not opened.
…con comparison

A stored environment target such as C:\Users\%USERNAME%\app.exe could be
compared as different from C:\Users\Alice\app.exe. Variable-bearing paths
are never expanded, so the icon comparison now returns null unless a fixed
target matches the icon exactly.
The testing guide asks for the typed error to be thrown before asserting a
successful Result value, and says a preceding .ok assertion adds no coverage.
Comment thread src/domain/native/windowsShortcut.ts Resolved
Resolve the docs/index.md conflict by keeping the new Binary hardening link
from main alongside the Windows shortcuts link.
Check TrackerDataBlock Length (0x58) and Version (0) before decoding.
A block with any other header is retained as raw bytes with a
malformed_structure issue, so it no longer yields MAC and timestamp
facts under complete coverage.
Collapse "." and ".." segments and repeated separators in the icon
comparison as text only, never opening a path. ".." stops at the drive
or UNC share root, and \\?\ and \\.\ paths stay verbatim.

Join LocalBasePath with CommonPathSuffix as the target and use the bare
base only when the suffix is empty, as the network share branch does.

Read the selected shortcut with lstat and open only, so a rejected
symlink's destination is never resolved.
normalizePath took the host and the next split part as the UNC root, so
\\server\\share\..\app.exe kept an empty share and let .. remove the
real share. Drop empty parts before picking the root so paths on
different shares stay different.
# Conflicts:
#	src/contracts/toolEffects.test.ts
@mvanhorn

mvanhorn commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Merged main in 11a7fe8 to clear the conflict. The only conflict was in src/contracts/toolEffects.test.ts, where main removed the execution-wording exceptions list this PR had added inspect_windows_shortcut to, so I took main's version of that file.

Comment thread src/cli/binaryDiagnosticsCommands.ts Resolved
The four inspect-windows-shortcut limit options now go through
cliDecimalField like the other inspection commands, so values such as
0x10 are rejected and cliDecimalArguments.test.ts passes.
A parent directory symlink or junction pointing at a UNC share was
followed by the first lstat, since the network check reads only the
path text and the symlink rejection covers only the final component.
On Windows, lstat each ancestor from the drive root down and reject
the path at the first link, before anything follows it.
Main reorganized the documentation layout and replaced the sidebar and
the index guide table with the docs/.vitepress/documentation.ts registry
and docs/README.md. Took main's versions and registered the Windows
shortcut guide there, and kept the Windows shortcuts row in README.md
and every translated README table.
@mvanhorn

mvanhorn commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Merged main in c762168 to clear the conflict. Main moved the sidebar and the guide index into docs/.vitepress/documentation.ts and docs/README.md, so I took main's versions of config.ts and docs/index.md and registered the Windows shortcut guide in both new lists. The Windows shortcuts row is kept in README.md and each translated README table.

Comment thread docs/getting-started/cli.md Resolved
Comment thread docs/guides/native/windows-shortcut.md Resolved
Move the Shell Link guide to docs/guides/native/windows-shortcut.md and
list it under Native binaries in the site navigation, keeping the
/windows-shortcut public route. Update README, translated README, CLI
page and authored skill links to the new physical path.

Add docs/specs/native/windows-shortcut/ with spec.md, plan.md and
tasks.md, as required by docs/development/documentation.md.
On Windows the ancestor link walk ran before the provider's resource
admission, so close() could finish while the walk kept calling lstat.
Run the walk inside the same admission as the read, and check the
caller's signal before each ancestor lstat.
The ancestor link walk checked every prefix of the path as written, so
C:\alias\..\real\a.lnk was refused when C:\alias is a directory link,
although Windows removes alias\.. before opening the file. Walk the
ancestors left after removing . and .. components, keeping the
caller's spelling, never climbing above an absolute root, and leaving
\\?\ paths as written since Windows does not normalize them.
The parent link regression matched the phrase "junction, which" in the
refusal message, so a wording edit would fail it. Report the linked
ancestor as observed.linked_ancestor on the input issue and assert that
fact instead of the explanatory text.
Race the parent walk lstat acknowledgement against inspection settling
with awaitAcknowledgement, then release the gate and join the inspect
and close work in finally so a failure reports its cause instead of
waiting for the Vitest timeout.
windowsAncestors built and kept every parent prefix before the first
lstat, so a path with thousands of components allocated memory
quadratic in its length. It now keeps only the normalized components
and yields each parent from a running prefix as the walk reaches it.
@morluto
morluto merged commit 645735f into morluto:main Nov 9, 2026
49 checks passed
@morluto morluto mentioned this pull request Nov 11, 2026
3 tasks done
Comment on lines +365 to +371
it("stops a deep missing Windows path at its first unreadable parent", async () => {
const provider = new WindowsShortcutProvider("win32");
const path = `C:\\missing${"\\a".repeat(8_000)}\\a.lnk`;
lstatCalls.mockClear();
await provider.inspect(providerInput(path));
expect(lstatCalls.mock.calls[0]).toEqual(["C:\\missing"]);
expect(lstatCalls).not.toHaveBeenCalledWith("C:\\missing\\a");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Test misses excessive memory use

The new deep-path test passes with the old eager windowsAncestors too. linkedWindowsAncestor already stops at the first failed lstat, so both assertions hold even when every parent string was built first. Excessive memory use could return without this test catching it.

The testing guide requires a regression for the demonstrated failure. Add a bounded check of memory growth or lazy parent construction that distinguishes the old implementation. This repository requirement must be satisfied before merging.

Context Used: AGENTS.md (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: tests/boundary/filesystem/windowsShortcut.test.ts
Line: 365-371

Comment:
**Test misses excessive memory use**

The new deep-path test passes with the old eager `windowsAncestors` too. `linkedWindowsAncestor` already stops at the first failed `lstat`, so both assertions hold even when every parent string was built first. Excessive memory use could return without this test catching it.

The testing guide requires a regression for the demonstrated failure. Add a bounded check of memory growth or lazy parent construction that distinguishes the old implementation. This repository requirement must be satisfied 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!

@morluto morluto added enhancement New feature or request area: runtime Process capture and runtime observation labels Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: runtime Process capture and runtime observation enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants