Skip to content

feat(ghidra): select a pre-imported project with -process - #2358

Closed
goncalompontes wants to merge 18 commits into
morluto:mainfrom
goncalompontes:feat/1048-existing-project-wiring
Closed

goncalompontes wants to merge 18 commits into
morluto:mainfrom
goncalompontes:feat/1048-existing-project-wiring

Conversation

@goncalompontes

Copy link
Copy Markdown

Summary

Adds the selection surface for the existing-project -process path introduced
by #2150, so a caller can open a project produced outside REA and pay import +
auto-analysis once, outside the provider startup deadline. This is the
product-wiring slice tracked by #2147 (items 1-3); it addresses #1048's
"documented environment variable" selection entry.

  • New REA_GHIDRA_EXISTING_PROJECT (directory holding rea-project.grez or
    rea-project.rep) and REA_GHIDRA_EXISTING_PROGRAM (program name for
    -process).
  • Both are required together and rejected when combined with import-time options
    (REA_GHIDRA_LANGUAGE_ID, REA_GHIDRA_COMPILER_SPEC_ID,
    REA_GHIDRA_SEED_FILE, REA_GHIDRA_DISABLED_ANALYZERS), which only apply to
    a fresh import.
  • Threaded through AppConfig to GhidraHeadlessLauncher.existingProject.
  • Rejected with an explicit reason at profile resolution for the Windows launch
    path and for DOS, raw-binary, and PSP targets.
  • The analysis profile records import_mode: "existing-project-copy"
    (provenance); the bridge's existing executable SHA-256 check rejects a stale
    or mismatched project.
  • GhidraExistingProject moves to src/config/ and is imported by the launcher,
    matching the GhidraLanguageOverride pattern.
  • Docs: pre-import analyzeHeadless command plus the read-only/copy-first
    provenance and mutation guarantees.

Stacks on #2150 (the launcher existingProject branch). Until #2150 merges,
this PR's diff also contains its two commits; I will rebase on main once it
lands. Ready for review once #2150 is in, or together with it.

Refs #1048, #2147.

Validation

  • npm run check — typecheck, lint (incl. module boundaries), format, knip,
    metadata, architecture guards: pass.
  • npm run test:focused -- src/config.test.ts src/ghidra/GhidraProvider.behavior.test.ts
    — 101 pass, including 12 new cases for the existing-project path (pairing,
    absolute-path, whitespace, import-time conflicts, profile mode, launcher
    hand-off, raw-binary and Windows rejection).
  • npx vitest run src/ghidra tests/boundary/providers/ghidra — 444 pass, 1
    skipped (includes feat(ghidra): open pre-imported projects with -process instead of re-importing #2150's launcher boundary tests).
  • npm run docs:check — pass.

Real-provider coverage

Not run in this slice (fixture/behavior harness only), matching #2150's own
note. Separately, the underlying -process -noanalysis reuse was exercised
against a real Ghidra 12.1.4 on Linux: a cold import + auto-analysis of a
445 KB PE took 27.7 s and the warm -process open took 6.3 s with identical
analysis results. I can post that evidence to #1048/#2150 or add a real-provider
lane here if wanted.

AI disclosure

This change (code, tests, and this description) was developed with AI
assistance, under human direction. Every validation command above was executed
on this branch's tip.

akushonkamen and others added 3 commits October 12, 2026 21:35
…-importing

Every session paid a fresh -import plus auto-analysis into a per-session
project that -deleteProject removed, so large targets re-paid the
cold-import tax on every open and could not fit the startup deadline
(morluto#1048).

Add an opt-in existing-project launch path following the first-slice
spec from the issue. ghidraHeadlessArguments gains an existing-project
branch that selects the project location, project name and program
explicitly with -process <program> -noanalysis, keeps -readOnly and
drops -import/-deleteProject. Import-only selections (DOS, raw binary,
language override, PSP, analysis seeds, analyzer overrides, MIPS
soft-float) are rejected with their reasons, and Windows keeps its
current P0 launch path unchanged. GhidraHeadlessLauncher copies the
caller's project into the owned runtime project root before launching
(copy-first), so Ghidra never touches the original project files and a
missing project directory fails before any process starts.

Wiring the profile/CLI selection surface is left for a follow-up slice.
The headless invocation selects the fixed project name rea-project while
copyExistingGhidraProject copied caller entries verbatim, so a directory
holding any other project file was copied and spawned successfully only
to fail inside Ghidra with an opaque error. Reject that layout before any
copy or process start with its actual reason, and state the fixed-name
contract on GhidraExistingProject and the copy helper.

Also open morluto#2147 to track the product wiring, target-digest binding with
stale/mismatch rejection, provenance/mutation documentation, and the
real-provider verification lane this fixture-only slice has not run
(morluto#1048).
Add REA_GHIDRA_EXISTING_PROJECT and REA_GHIDRA_EXISTING_PROGRAM so a caller can
open a project produced outside REA with '-process -noanalysis' instead of
re-importing and re-analyzing the target inside the provider startup deadline.

Both settings are required together and validated against import-time options
(language, compiler spec, seeds, disabled analyzers) that only apply to a fresh
import. The pair is threaded through AppConfig to the launcher, and rejected for
the Windows launch path and DOS, raw-binary, and PSP targets. The analysis
profile records import_mode: existing-project-copy; the bridge's executable
SHA-256 check already rejects a stale or mismatched project.

Stacks on morluto#2150, which adds the launcher existingProject branch.

Refs morluto#1048, morluto#2147.
@goncalompontes
goncalompontes force-pushed the feat/1048-existing-project-wiring branch from 97353b7 to 000f379 Compare October 12, 2026 20:37
@goncalompontes
goncalompontes marked this pull request as ready for review October 12, 2026 20:42
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@matbrgz

matbrgz commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

Review Finding & Architecture Verification

While threading REA_GHIDRA_EXISTING_PROJECT and REA_GHIDRA_EXISTING_PROGRAM through configuration solves opening pre-imported Ghidra databases with -process -noanalysis, there is an edge case at target admission and launcher instantiation:

1. Late Failure for Incompatible Targets (dos-mz, dos-com, raw-binary)

In GhidraLauncher.ts, ghidraHeadlessArguments() explicitly throws if existingProject is combined with dosMz, dosCom, or rawBinary:

if (options.existingProject !== undefined && (options.dosMz || options.dosCom || options.rawBinary)) {
  throw new Error("Cannot combine existing Ghidra project with fresh import options");
}

However, in GhidraProvider.ts#inspectTargetSupport(target):

  • inspectTargetSupport still marks a dos-mz or dos-com target as status: "supported".
  • When an analyst configures REA_GHIDRA_EXISTING_PROJECT and opens a DOS target (open_binary), provider selection succeeds at admission time, only to throw an unhandled internal error during launcher subprocess construction in GhidraProviderClient.ts.

2. Suggested Fix

In GhidraProvider.ts#inspectTargetSupport(target), if this.config.ghidraExistingProject !== undefined, verify whether target.format is among the forbidden formats (dos-mz, dos-com, raw-binary, or PSP) and fail closed with target_format_unsupported during provider discovery, before attempting process launch.

@morluto

morluto commented Oct 13, 2026

Copy link
Copy Markdown
Owner

@greptileai review

@greptile-apps

greptile-apps Bot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

This PR is set for a Plus review. TREX isn't supported with Plus or Apex reviews yet, so Greptile reviews this PR at Base while TREX is on.

@greptile-apps

greptile-apps Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] Adds support for opening pre-imported Ghidra analysis projects.

The normal restart path is fixed, but restoration can still return stale saved-project answers and should be fixed before merging.

Findings

  1. P1 Restart returns old answers ▶
Fix with agent prompt
### Issue 1
src/ghidra/GhidraProvider.ts:301-309
`session_id` is created when the profile is resolved, not when the project is copied. When Ghidra exits and `open_binary` reopens the same target without `providerId`, REA reuses the route and profile but copies the saved project again. If the caller edited that project meanwhile, the cache still matches and returns answers from the old copy. Cached and fresh queries can then describe different saved states.

Bind cache identity to the copy's lifetime, or clear and rebind cached answers whenever a new copy is opened.

---

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

Summary

Adds environment settings for opening a saved Ghidra project through a private copy.

  • REA opens a saved Ghidra program without importing it again.
  • Cached answers follow the saved-project copy used by each client.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Open saved project] --> B[Resolve selected provider profile]
  B --> C[Copy project into private runtime]
  C --> D[Open with process and noanalysis]
  D --> E[Serve queries and cache answers]
  E --> F{Retained client alive?}
  F -->|Yes| E
  F -->|No| G[Refresh selected profile]
  G --> C
Loading

Reviews (13) · Last reviewed commit: "fix(session): recommit the profile for a..." · Reviewed by Greptile

Comment thread src/ghidra/GhidraProviderClient.ts Resolved
Comment thread src/ghidra/GhidraLauncher.ts Resolved
Comment thread src/ghidra/GhidraLauncher.ts Resolved
Comment thread src/ghidra/GhidraLauncher.ts Resolved
Copy only selected project files through a cancelable sequential stream traversal, reject symlinks, use the regular-file ownership helper, keep import-only derived flags out of existing-project launches and reject caller import overrides during profile resolution.

Source inspection and git diff --check; tests/builds/typechecks/CI reruns skipped at explicit user request.
Comment thread src/ghidra/GhidraLauncher.ts Resolved
Keep the established missing-project message for ENOENT and preserve other filesystem failures instead of relabeling them as absence.

Source inspection and git diff --check only. Tests, builds and typechecks skipped by explicit user request. GitHub review writes paused globally.
Comment thread src/ghidra/GhidraAnalysisProfile.ts Resolved
Comment thread src/config/parseConfig.ts Resolved
@morluto

morluto commented Oct 13, 2026

Copy link
Copy Markdown
Owner

Review findings addressed at their producing boundaries and consumers. Latest changes were reviewed from source; tests and provider runs were skipped at the maintainer's request. Findings requiring separate decisions or verification remain open.

  1. thread 1

Fixed in 676326e.

Root cause and structural fix: ENOENT retains the established missing-project diagnostic. Other lstat failures preserve their original reason; an existing nonregular directory or symlink is separately refused.

Validation: source inspection and git diff --check only. Tests, builds and typechecks were skipped by the user's explicit request; no runtime or real-provider pass is claimed. No directly related cleanup remains identified.

@morluto

morluto commented Oct 13, 2026

Copy link
Copy Markdown
Owner

Review findings addressed at their producing boundaries and consumers. Latest changes were reviewed from source; tests and provider runs were skipped at the maintainer's request. Findings requiring separate decisions or verification remain open.

  1. thread 1

Fixed in bd8633c (snapshot identity commit be9c21f). The executable digest and import mode cannot identify a saved project's program analysis. Until that saved state has a verified content commitment, the Ghidra provider now creates a fresh existing_project.session_id for each profile resolution and commits the selected program name with it. Shared snapshot import/cache matching already compares the complete profile digest, so another session's snapshot fails the existing mismatch gate; repeated queries in one immutable owned copy retain their session cache. The installation guide explicitly documents this lifetime. A regression was authored for repeated resolutions of one project and a second project producing distinct digests, but was not run. Source inspection followed profile composition, route capture, snapshot import validation and cache binding; git diff --check passed. Validation: inspected the producing boundary and affected consumers in source; no tests, builds, lint, typechecks, provider workloads or CI reruns were executed, as explicitly requested. Cross-session reuse intentionally remains unavailable until saved-state hashing is implemented; no downstream cache reinterpretation was added.

  1. thread 1

Fixed in bd8633c. The parser correctly identified the missing setting but generated the constraint from the supplied setting, reversing the remediation. The paired-settings owner now emits one symmetric constraint: REA_GHIDRA_EXISTING_PROJECT and REA_GHIDRA_EXISTING_PROGRAM must be set together. Both one-sided configuration cases now assert that exact guidance in the existing regression. Source inspection followed ConfigurationError projection and both parser branches; git diff --check passed. Validation: inspected the producing boundary and affected consumers in source; no tests, builds, lint, typechecks, provider workloads or CI reruns were executed, as explicitly requested. No duplicate direction-dependent message remains.

@morluto morluto added enhancement New feature or request area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior area: cli CLI adapter and one-shot commands area: setup Setup, packaging, upgrade, install, Doctor, and client registration P2: medium Medium priority issue labels Oct 13, 2026
Comment thread src/ghidra/GhidraAnalysisProfile.ts Resolved
Comment thread src/ghidra/GhidraProviderClient.ts Resolved
Comment thread src/ghidra/GhidraAnalysisProfile.ts Resolved
@greptile-apps

greptile-apps Bot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

Want your agent to iterate on Greptile's feedback? Try greploops.

REA_GHIDRA_EXISTING_PROJECT / REA_GHIDRA_EXISTING_PROGRAM were rejected on
win32 at profile resolution and again in headless argument construction, so
the existing-project `-process -noanalysis -readOnly` path was Linux/macOS
only even though the Windows P0 launcher builds the same invocation.

Remove both win32 gates. The Windows batch launch already quotes the project
location, the fixed `rea-project` name and the `-process <program>` program
name, and copyExistingGhidraProject writes the caller's project into the owned
private runtime, so no POSIX-only behavior is required. Import-time selections
(DOS/raw-binary/PSP/language override/seeds/disabled analyzers) stay rejected,
and the no-return repair post-script remains POSIX-only, matching a fresh
Windows import's `disabled-windows-p0` profile.

Verified on Windows with Ghidra 12.1.4 and a pre-imported engine2.dll (6.8 MB
PE x86-64, project produced by analyzeHeadless.bat under the fixed
`rea-project` name): `rea analyze` opened the owned copy in ~12 s with
import_mode `existing-project-copy` and reported 13,302 procedures, versus a
~237 s cold import. The Windows-rejection regressions now assert the admitted
behavior, and the installation guide documents the batch pre-import command.
goncalompontes pushed a commit to goncalompontes/rea that referenced this pull request Oct 14, 2026
Reconcile morluto#2358's existing-project wiring and this branch's project cache with 254 commits of main, including main's Ghidra provider/launcher/installation refactors.

Conflicts: keep main's parsed-environment structure in parseConfig and re-apply the REA_GHIDRA_EXISTING_PROJECT and REA_GHIDRA_PROJECT_CACHE settings; keep both main's and this branch's suites in config.test.ts and GhidraProvider.behavior.test.ts; adopt main's shared GhidraInstallation fixture in the language-override, snapshot-cache and PowerPC tests and align the raw-binary profile test with main (drop the stale hard-coded digest). Skip main's POSIX-path and Windows native-replay lanes on Windows, as the suite already does elsewhere.

Install the merged lockfile (npm ci) for main's new dependency.
@CassieFox23

Copy link
Copy Markdown
Contributor

TL;DR: The two new settings work end to end on Linux. A saved project opens in about 6 seconds, where a fresh import of the same program takes about 53 seconds. A project folder with rea-project.rep but no rea-project.gpr still starts Ghidra and fails late.

I tested head 9adad2c as pushed. GitHub says it conflicts with main b7dcf78. Main does not know the settings, so I used it as "before". I ran the real command: rea search <program> --kind procedures --provider ghidra. I made the project with the documented analyzeHeadless command, then renamed three functions.

Results

Check Head Main
The 3 renamed functions come back yes no, default names
Project copy used yes no, fresh import
Open time, 12,720-byte C program (median of 3) 5.74 s 7.63 s
Open time, sqlite3 shell (median of 3) 6.26 s 53.47 s
Procedures on sqlite3 3,126, same list as main 3,126
Project files after all runs unchanged not applicable
Java process and runtime folder after each run gone gone
4 PR test files, Node 24.18.0 and 26.11.1 222 pass, 4 skipped, both not run

The 4 skipped tests are the Windows-only cases. The profile reads import_mode: existing-project-copy on head. Main reads ephemeral-source-immutable. Main ignored both settings without a word. A missing folder still gave a fresh import there.

Config errors on head came back in under 1 second, with no Java started:

  • Only one of the two settings: "must be set together".
  • Either setting with REA_GHIDRA_LANGUAGE_ID, REA_GHIDRA_SEED_FILE or REA_GHIDRA_DISABLED_ANALYZERS: "cannot be combined".
  • A relative path, or a program name with a space around it: rejected.
  • A DOS .com or raw-binary target: unsupported_target, before Ghidra starts. That covers the question matbrgz raised for those two formats.

Late failures (head)

  • A folder with only rea-project.rep (no .gpr) starts Ghidra. It fails after about 3 s: "Project marker file not found".
  • A zero-byte rea-project.grez also starts Ghidra. It fails after about 3 s: "Could not find project".
  • A wrong program name fails the same way: "Requested project program file(s) not found".
  • The CLI message for these says to run rea doctor. The real reason sits in details.diagnostics. I did not run doctor.
  • A snapshot saved in one session is refused in the next with profile_mismatch. That matches the docs.
  • The output notes still talk about auto-analysis and a fresh import. Neither fits this mode.

Not run

  • A real .grez archive. I do not know how Ghidra 12.1.4 writes one, so the zero-byte file is only a stand-in.
  • PSP targets, and a RISC-V or MIPS program with a pinned language.
  • The Windows launch path from 9adad2c, and macOS.
  • The MCP route (CLI only).
  • CI: only the Greptile check ran on this head. No test shards ran.
  • Head merged onto current main.
  • Node 22.

Thanks, Gonçalo Pontes, for the feature. Thanks, morluto, for the copy and cancel rework.

Load average (busy tasks over 1 minute, on 24 threads) read 5.0 to 5.6 during the timing runs. A benchmark shared the box, so read the times as rough.

Test setup
  • Box: Nobara 44 (Fedora 44 base), Linux 7.2.9
  • CPU: AMD Ryzen 9 5900X, 12 cores / 24 threads
  • RAM: 32 GB DDR4-3600
  • Node: 24.18.0, 26.11.1 (tests); 24.18.0 (CLI runs)
  • Head: 9adad2c
  • Main: b7dcf78
  • Base: 2652570
  • Other: Ghidra 12.1.4 (Apache-2.0)
  • Other: JDK 21.0.12.1
  • Other: sqlite3 from Fedora. Its license is blessing.
Commands
npm ci && npm run build && npm run test:prepare
analyzeHeadless <dir> rea-project -import <program>
analyzeHeadless <dir> rea-project -process <program> -noanalysis -postScript HumanRename.java
REA_GHIDRA_EXISTING_PROJECT=<dir> REA_GHIDRA_EXISTING_PROGRAM=<program> \
  node scripts/rea.mjs search <program> --kind procedures --mode regex --pattern . --provider ghidra --format json
node scripts/run-development-tests.mjs focused src/config.test.ts src/ghidra/GhidraProvider.behavior.test.ts src/ghidra/GhidraMipsProfile.test.ts tests/boundary/providers/ghidra/ghidraLauncher.test.ts

Each run sat under nice -n 19 and systemd-run --user --scope -p MemoryMax=6G. Head and main runs alternated. Times are wall clock for the whole CLI call, Node start included.

🤖 Generated with Claude Code (Sonnet 5.5, verified by Opus 5.5) 🦊

# Conflicts:
#	src/config.test.ts
#	src/config/parseConfig.ts
#	src/ghidra/GhidraProvider.behavior.test.ts
#	tests/boundary/filesystem/artifactComparison.test.ts
@kaoru0822-kitauji

Copy link
Copy Markdown
Collaborator

Merged latest main into this branch to resolve conflicts in four files. No rebase or force-push was used.

  • src/config/parseConfig.ts: main moved environment cross-validation into parseEnvironment in src/config/environment.ts, which now also honors settings that client registrations cannot resolve. This PR's existing-project rules moved there as existingGhidraProjectIssue, with the same settings and constraint messages. REA_GHIDRA_EXISTING_PROJECT and REA_GHIDRA_EXISTING_PROGRAM must be set together, and cannot be combined with the language, compiler-spec, seed-file or disabled-analyzer settings. parseConfig builds ghidraExistingProject from the parsed environment.
  • src/config.test.ts and src/ghidra/GhidraProvider.behavior.test.ts: kept main's new describe blocks and this PR's complete existing-project blocks. On main, installationHost takes the platform (installationHost("win32")) so Windows paths are consistent, and the Windows existing-project test now uses it. Previously it only overrode platform and failed on main's launch path.
  • tests/boundary/filesystem/artifactComparison.test.ts: main's version, which supersedes this PR's 2-line describe split.

I checked that no test title this PR added since the merge base was lost.

Validation:

  • GhidraProvider.behavior.test.ts: 77 passed;
  • config, ManagedCilDecoding, GhidraMipsProfile and setupEnvironment tests: 225 passed;
  • ghidraLauncher and artifactComparison boundary tests: 55 passed, 4 skipped;
  • typecheck and lint, via the pre-push hook.

Not verified: a real Windows host or Ghidra project.

Comment on lines +301 to +309
// Saved project analysis is not committed by the executable digest.
// Bind snapshots to this resolution's owned copy; cross-session replay
// stays unavailable until the selected program's saved state is hashed.
...(existingProject === undefined
? {}
: {
existing_project: {
program_name: existingProject.programName,
session_id: randomUUID(),

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.

P1 Restart returns old answers

session_id is created when the profile is resolved, not when the project is copied. When Ghidra exits and open_binary reopens the same target without providerId, REA reuses the route and profile but copies the saved project again. If the caller edited that project meanwhile, the cache still matches and returns answers from the old copy. Cached and fresh queries can then describe different saved states.

Bind cache identity to the copy's lifetime, or clear and rebind cached answers whenever a new copy is opened.

Knowledge Base Used:

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/ghidra/GhidraProvider.ts
Line: 301-309

Comment:
**Restart returns old answers**

`session_id` is created when the profile is resolved, not when the project is copied. When Ghidra exits and `open_binary` reopens the same target without `providerId`, REA reuses the route and profile but copies the saved project again. If the caller edited that project meanwhile, the cache still matches and returns answers from the old copy. Cached and fresh queries can then describe different saved states.

Bind cache identity to the copy's lifetime, or clear and rebind cached answers whenever a new copy is opened.

**Knowledge Base Used:**
- [Ghidra integration](https://app.greptile.com/pre/-/custom-context/knowledge-base/morluto/rea/-/docs/ghidra-integration.md)
- [Reverse-engineering toolchains](https://app.greptile.com/pre/-/custom-context/knowledge-base/morluto/rea/-/docs/reverse-engineering-toolchains.md)

---

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

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.

@goncalompontes I traced the potential stale-cache mechanism at head 2a637760d a little further. resolveSessionTarget in BinarySessionOpen.ts reuses current.route for a same-target open_binary without providerId; when a retained provider is dead, BinarySession.#openWithinTransition starts a new client from that route. Its old profile is not re-resolved. AnalysisSnapshotCache.select only clears entries when the target/profile changes. A new copy of an externally edited saved project can therefore retain the previous copy's cache identity.

I reproduced these branch decisions in an isolated Node model, not an authentic REA provider restart or Ghidra run. A useful regression sequence would be: query a saved project, lose the Ghidra process while keeping the REA session, edit the external saved project, reopen the same target with provider_id omitted, and assert that the current answer comes from the newly copied state. An explicit provider re-selection would make a useful control. The fix likely belongs at copy-lifetime identity or snapshot invalidation, while preserving historical Evidence.

This extends the existing review finding, not a competing implementation. Happy to prepare a focused reproducible regression for incorporation.

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.

Thanks for tracing this through resolveSessionTarget and the retained-provider restart path. This confirms the original finding: session_id is generated only when the profile is first resolved, so it does not identify each subsequent private-project copy. When the route/profile is reused, AnalysisSnapshotCache.select can retain answers even though existingProject has been copied again from a potentially edited external project.

The regression sequence you described is the right one, with explicit provider re-selection as the control. The fix should either generate/cache identity at the copy boundary and use it for snapshot selection, or invalidate/rebind the snapshot whenever a new copy is opened; preserving historical Evidence is important. A focused regression covering the retained-session restart would be useful for incorporation.

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.

@goncalompontes I turned the restart/cache sequence from my earlier review reply into a regression using REA's actual BinarySession, SessionProviderRouter, and AnalysisSnapshotCache, with a production-composed fixture provider. It is based directly on #2358 head 2a637760da8d4d91c7aca5231645339d573f811a.

Test commit in my fork | GitHub Actions run

The existing nine liveness tests pass. The new test fails as expected: after a dead provider is replaced and the simulated saved project changes from old_saved_project_name to new_saved_project_name, the re-opened session still returns the old name from its retained snapshot. This is a real REA session/cache regression with a fixture child, not a real Ghidra process/project test. It ran on Ubuntu 24.04 with Node 24.18.0 after npm ci and the build.

I have deliberately stopped before changing the cache/profile architecture. Refreshing the copied-project identity on provider restart, or invalidating only the retired copy's cache, needs to preserve warm-query reuse while keeping historical Evidence. If the regression fits your PR, you're welcome to incorporate it; I'm happy to work with your preferred owning boundary. I have not modified your branch or opened a competing PR.

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.

@goncalompontes, following up on my verified restart regression with a focused correction against PR head 2a637760da8d4d91c7aca5231645339d573f811a.

Isolated fix branch | passing expanded GitHub Actions run | original failing run

Cause/fix: The same-target open_binary path correctly retains the selected provider, but on a dead client it also retained that provider's previous analysis profile. I added SessionProviderRouter.refreshBoundProfile, which recommits the original selected provider's profile only when its client must be replaced, preserving its selection source/authority. BinarySession binds the replacement client and snapshot selection to that refreshed profile, and validates any caller-supplied snapshot against it before retiring the previous client. A still-live client keeps the existing fast path.

The source changes are router and session transition; the branch contains the independently cherry-pickable regression and subsequent assertions, without needing the fork-only workflow.

Verified: The original fixture test failed with the stale saved-project name. The corrected branch passed 59 focused tests (2 skips) across session liveness, snapshot cache, direct snapshot replay and MCP workflow replay; test discovery, docs checks, fresh typecheck/lint (zero cached static tasks) and source cleanliness passed under Node 24.18.0 on Ubuntu 24.04. Controls confirm a changed profile digest, refusal of the prior copy's snapshot, and warm cache reuse within the new copy.

This exercises actual REA routing/snapshot/session code with a fixture provider, not a real Ghidra process restart. Historical Evidence records are not cleared by the change; the snapshot binding is replaced. I haven't modified your branch or opened a competing PR.

If you agree with the approach, please feel free to incorporate the patch into #2358. Happy to adjust the refresh owner to fit your architecture or help with a real-Ghidra restart test.

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.

@goncalompontes, I completed the follow-up real-Ghidra provider-restart acceptance test for the copy-lifetime correction on my fork.

Successful real-provider GitHub Actions run | isolated verifier branch | previously verified minimal source fix

Using Ghidra 12.1.4 (official archive SHA-256 verified), JDK 21, Node 24.18.0 and a wholly source-owned PE fixture, the verifier:

  1. Prepared saved rea-project with function saved_first_version.
  2. Opened it from REA's copy-first mode, then changed the external saved project using a separate real Ghidra -process run to saved_second_version.
  3. Located the REA-owned JVM using the authenticated binary_session status, checked its command line, terminated only that child on the disposable runner, and called open_binary again in the same MCP connection without provider_id.
  4. Confirmed fresh pseudocode uses saved_second_version, not the cached first name; the provider remained ghidra, profile digest changed 71f28001... -> d93bb1e0..., original target digest stayed 0c641432..., and owned cleanup finished.

The successful run also passed the focused session/snapshot tests, fresh static checks, and source-cleanliness checks. Earlier failed real-provider attempts were verifier-side response-shape mistakes, fixed by using the canonical MCP lifecycle schema and Evidence digest; they were not failures of the provider's restart behavior.

This closes the real-provider gap I noted in my prior handoff. The actual source correction and unit tests remain on the smaller branch linked above; the second branch adds only test scripts and the fork-only CI workflow. Please incorporate only what fits your PR's design, and let me know if you'd like a further failure/recovery control. No competing upstream PR or edits to your branch.

An existing-project session mints its copy identity when the analysis
profile is resolved, but the provider copies the saved project for every
client it starts. When a dead client was replaced for the same target,
the session reused the retired profile, so the snapshot cache could
replay answers recorded from the old copy after the caller edited the
selected project.

A retained-route restart now asks the bound provider to recommit its
analysis profile before the replacement client is created, revalidates
the staged snapshot against it, and fails closed when the provider
cannot recommit its original identity. A provider whose profile is
unchanged keeps replaying its cached answers.

The restore-after-a-failed-open path still recreates the previous client
with the retired profile. It is left out because it spans only a failed
open, but it needs the same treatment when that path is next touched.

Refs morluto#2358
@morluto

morluto commented Oct 26, 2026

Copy link
Copy Markdown
Owner

Thank you for the project-selection work and documentation. #7236 now provides shared CLI/MCP configuration for an existing project, verifies and copies it before read-only launch, records its provenance, and rejects incompatible import settings. I’m closing this stacked PR as superseded. The merged interface selects an expanded .gpr/.rep pair and uses different setting names; please feel free to reopen if a distinct archive-selection requirement remains. I did not rerun Ghidra in this pass.

@morluto morluto closed this Oct 26, 2026
@morluto morluto added area: runtime Process capture and runtime observation provider: ghidra Analysis provider / engine: ghidra labels Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: cli CLI adapter and one-shot commands area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior area: runtime Process capture and runtime observation area: setup Setup, packaging, upgrade, install, Doctor, and client registration enhancement New feature or request P2: medium Medium priority issue provider: ghidra Analysis provider / engine: ghidra

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants