Repository navigation
Conversation
Add an opt-in project store under .rea/evidence. Records are content addressed by evidence_id, written atomically with owner-only permissions, and authenticated again before a later session can adopt them. Sessions schedule durable writes, flush them during close, and fall back to the store when a retained or file reference misses session memory. A failed flush is reported as a cleanup failure instead of silently losing Evidence. Unknowns and graph queries remain outside this first store slice.
Exercise the session-close path when the project store cannot write, and document that an exported session bundle does not implicitly import the store. Persistence failures stay visible instead of being reported as durable Evidence.
Name the server process working directory as the default root and point clients that launch REA elsewhere at REA_EVIDENCE_STORE_DIR.
Keep target switches and external mutations independent of durable Evidence writes. Final close and closeWithSnapshot now flush the store and combine a failure with existing cleanup facts instead of blocking target retirement.
Provider-free CLI paths such as inspect-macho compose artifact or native sessions, so they ignored REA_EVIDENCE_STORE. Resolve the store root once from the admitted environment and pass it to artifact, native, and managed session factories as well as the deep binary session. Cover the wiring with composition tests. Verified against the arm64 Freebuff Installer app, including a retained summary read in a second MCP session.
[Medium impact] The PR adds opt-in local persistence used by session Evidence lookups. This PR needs fixes before merging for missing saves, unreadable large records, lost metadata updates, and failed file cleanup. Findings
Fix with agent prompt### Issue 1
src/composition/directAnalysis.ts:30-32
Passing the environment into the managed factory does not persist real managed CLI results. `runManagedProviderExecution()` closes its session before `runManagedProviderAnalysis()` creates the returned Evidence. The managed-only session has no analysis profile, so `BinarySession.execute()` does not record that result either. Commands succeed with the store enabled, but their returned records are never saved.
Record the final Evidence before closing. Cover a real `inspect-managed-artifact` call; the new test manually records a fixture and misses this path.
### Issue 2
src/composition/binary.ts:142-146
`evidenceStoreFor()` receives an unchecked environment on the artifact, native, and managed CLI paths. With `REA_EVIDENCE_STORE=project` and a relative `REA_EVIDENCE_STORE_DIR`, `projectEvidenceStoreRoot()` returns `undefined`, so the command succeeds with persistence silently disabled. These paths skip the parser that rejects that setting. An analyst can receive successful results and later find no saved records.
Parse the store settings at their shared entry point and return a configuration error instead.
### Issue 3
src/application/investigation/ProjectEvidenceStore.ts:178-179
The new 64 MiB read limit rejects records that the store can save successfully. The ledger accepts larger Evidence, but `#write()` has no matching size check and `flush()` reports success. A later session then receives “missing” for that record.
Check the encoded size before reporting a successful durable write, or support reading every record the writer accepts.
### Issue 4
src/application/investigation/ProjectEvidenceStore.ts:32-33
`#scheduled` blocks later writes even when an earlier write succeeded and the record's metadata changed. `importEvidenceBundle()` can accept a new `subject.local_path`, `subject.name`, or `caller_input_path` without changing `evidence_id`, but its replacement write is discarded here. A later session gets the old metadata.
Coalesce unchanged writes without dropping accepted replacements. `AGENTS.md` requires preserving caller-selected paths and metadata; that requirement must be met before merging.
### Issue 5
src/application/investigation/ProjectEvidenceStore.ts:106-108
If removing a failed write's temporary file also fails, this catch discards the removal error and leaves no owner to retry cleanup. `flush()` reports only the write failure, even though an extra Evidence file remains.
Retain the temporary file and compose its cleanup failure with the write failure. `AGENTS.md` requires failed cleanup to remain owned; that requirement must be met before merging.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.SummaryAdds opt-in project storage for authenticated Evidence, allowing later sessions to resolve saved record IDs.
DiagramsequenceDiagram
participant S as Current session
participant L as Record ledger
participant P as Project store
participant D as Record files
participant N as Later session
S->>L: Accept record or import
L-->>S: Sealed accepted records
S->>P: Queue accepted records
P->>D: Write temporary file, sync, rename
P->>D: Sync containing directory where supported
S->>P: Close waits for writes and retries queued records
N->>P: Look up retained ID
P->>D: Read regular file within size limit
P-->>N: Return authenticated matching record, or missing
Reviews (3) · Last reviewed commit: "fix(evidence): queue the ledger's record..." · Reviewed by Greptile |
| if (!EVIDENCE_ID.test(id) || this.#scheduled.has(id)) return; | ||
| this.#scheduled.add(id); |
There was a problem hiding this comment.
#scheduled blocks later writes even when an earlier write succeeded and the record's metadata changed. importEvidenceBundle() can accept a new subject.local_path, subject.name, or caller_input_path without changing evidence_id, but its replacement write is discarded here. A later session gets the old metadata.
Coalesce unchanged writes without dropping accepted replacements. AGENTS.md requires preserving caller-selected paths and metadata; that requirement must be met before merging.
Context Used: AGENTS.md (source)
Knowledge Base Used: Session evidence and results
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/application/investigation/ProjectEvidenceStore.ts
Line: 32-33
Comment:
**Saved metadata stays old**
`#scheduled` blocks later writes even when an earlier write succeeded and the record's metadata changed. `importEvidenceBundle()` can accept a new `subject.local_path`, `subject.name`, or `caller_input_path` without changing `evidence_id`, but its replacement write is discarded here. A later session gets the old metadata.
Coalesce unchanged writes without dropping accepted replacements. `AGENTS.md` requires preserving caller-selected paths and metadata; that requirement must be met before merging.
**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))
**Knowledge Base Used:** [Session evidence and results](https://app.greptile.com/-/switch-tenant?tenant=pre&next=%2Fcustom-context%2Fknowledge-base%2Fmorluto%2Frea%2F-%2Fdocs%2Fsession-evidence-and-results.md)
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.| createManagedBinarySession: async () => { | ||
| const { createManagedBinarySession } = await import("./binary.js"); | ||
| return createManagedBinarySession(); | ||
| return createManagedBinarySession(environment); |
There was a problem hiding this comment.
Passing the environment into the managed factory does not persist real managed CLI results. runManagedProviderExecution() closes its session before runManagedProviderAnalysis() creates the returned Evidence. The managed-only session has no analysis profile, so BinarySession.execute() does not record that result either. Commands succeed with the store enabled, but their returned records are never saved.
Record the final Evidence before closing. Cover a real inspect-managed-artifact call; the new test manually records a fixture and misses this path.
Knowledge Base Used: Command-line interface
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/composition/directAnalysis.ts
Line: 30-32
Comment:
**Managed CLI records disappear**
Passing the environment into the managed factory does not persist real managed CLI results. `runManagedProviderExecution()` closes its session before `runManagedProviderAnalysis()` creates the returned Evidence. The managed-only session has no analysis profile, so `BinarySession.execute()` does not record that result either. Commands succeed with the store enabled, but their returned records are never saved.
Record the final Evidence before closing. Cover a real `inspect-managed-artifact` call; the new test manually records a fixture and misses this path.
**Knowledge Base Used:** [Command-line interface](https://app.greptile.com/-/switch-tenant?tenant=pre&next=%2Fcustom-context%2Fknowledge-base%2Fmorluto%2Frea%2F-%2Fdocs%2Fcommand-line-interface.md)
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.| const evidenceStoreFor = ( | ||
| environment: Readonly<Record<string, string | undefined>>, | ||
| ): ProjectEvidenceStore | undefined => { | ||
| const root = projectEvidenceStoreRoot(environment); | ||
| return root === undefined ? undefined : new ProjectEvidenceStore(root); |
There was a problem hiding this comment.
Bad settings silently disable saving
evidenceStoreFor() receives an unchecked environment on the artifact, native, and managed CLI paths. With REA_EVIDENCE_STORE=project and a relative REA_EVIDENCE_STORE_DIR, projectEvidenceStoreRoot() returns undefined, so the command succeeds with persistence silently disabled. These paths skip the parser that rejects that setting. An analyst can receive successful results and later find no saved records.
Parse the store settings at their shared entry point and return a configuration error instead.
Knowledge Base Used: Command-line interface
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/composition/binary.ts
Line: 142-146
Comment:
**Bad settings silently disable saving**
`evidenceStoreFor()` receives an unchecked environment on the artifact, native, and managed CLI paths. With `REA_EVIDENCE_STORE=project` and a relative `REA_EVIDENCE_STORE_DIR`, `projectEvidenceStoreRoot()` returns `undefined`, so the command succeeds with persistence silently disabled. These paths skip the parser that rejects that setting. An analyst can receive successful results and later find no saved records.
Parse the store settings at their shared entry point and return a configuration error instead.
**Knowledge Base Used:** [Command-line interface](https://app.greptile.com/-/switch-tenant?tenant=pre&next=%2Fcustom-context%2Fknowledge-base%2Fmorluto%2Frea%2F-%2Fdocs%2Fcommand-line-interface.md)
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.| } catch (cause) { | ||
| await rm(temporary, { force: true }).catch(() => undefined); | ||
| throw cause; |
There was a problem hiding this comment.
If removing a failed write's temporary file also fails, this catch discards the removal error and leaves no owner to retry cleanup. flush() reports only the write failure, even though an extra Evidence file remains.
Retain the temporary file and compose its cleanup failure with the write failure. AGENTS.md requires failed cleanup to remain owned; that requirement must be met before merging.
Context Used: AGENTS.md (source)
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/application/investigation/ProjectEvidenceStore.ts
Line: 106-108
Comment:
**Failed removals are hidden**
If removing a failed write's temporary file also fails, this catch discards the removal error and leaves no owner to retry cleanup. `flush()` reports only the write failure, even though an extra Evidence file remains.
Retain the temporary file and compose its cleanup failure with the write failure. `AGENTS.md` requires failed cleanup to remain owned; that requirement must be met 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.A retained read used existsSync plus readFileSync on a name the store constructed, so a FIFO or an oversized file at that name could block the server or allocate before authentication. Reads now open the exact record without following links, require a regular file within a record-sized ceiling, and re-authenticate the content. A failed write kept its ID scheduled and its error sticky, so the record was never retried after the storage problem was fixed. Failed writes now stay queued for the next flush, only a committed write leaves the queue, the temporary is owned until it is removed or reported, and the record is synced before its rename so a reported durable write survives a host crash. Retained reads are released when the session that read them closes. Snapshot imports merged Evidence straight into the ledger without scheduling a durable write, and the bundle import rescanned the whole session. Both routes now persist exactly the records the ledger committed, which the import delta reports in bundle order.
| if (!status.isFile() || status.size > MAX_STORED_RECORD_BYTES) | ||
| return undefined; |
There was a problem hiding this comment.
Large saved records become missing
The new 64 MiB read limit rejects records that the store can save successfully. The ledger accepts larger Evidence, but #write() has no matching size check and flush() reports success. A later session then receives “missing” for that record.
Check the encoded size before reporting a successful durable write, or support reading every record the writer accepts.
Knowledge Base Used: Session evidence and results
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/application/investigation/ProjectEvidenceStore.ts
Line: 178-179
Comment:
**Large saved records become missing**
The new 64 MiB read limit rejects records that the store can save successfully. The ledger accepts larger Evidence, but `#write()` has no matching size check and `flush()` reports success. A later session then receives “missing” for that record.
Check the encoded size before reporting a successful durable write, or support reading every record the writer accepts.
**Knowledge Base Used:** [Session evidence and results](https://app.greptile.com/-/switch-tenant?tenant=pre&next=%2Fcustom-context%2Fknowledge-base%2Fmorluto%2Frea%2F-%2Fdocs%2Fsession-evidence-and-results.md)
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.recordEvidence and recordEvidenceWithUnknown scheduled the object the caller passed. That object stays mutable after the ledger seals its own copy, so an edit made before the queued write ran would persist content whose digest no longer matches its evidence_id, and the next session would reject the record as tampered. Both paths now queue the record the ledger owns.
|
@Mutersec thanks for the PR — there are 5 open review threads here:
Could you address or reply to these? Once they're resolved and CI is green we can take another look. |
|
@Mutersec also, this branch has merge conflicts with |
Summary
Adds an opt-in project Evidence store: with
REA_EVIDENCE_STORE=project, authenticated Evidence records persist as content-addressed files under.rea/evidence(orREA_EVIDENCE_STORE_DIR), so a later session can resolve a retained reference instead of receiving the record again over the wire. Default behavior is unchanged: the store is off unless the server environment opts in.This is the persistence slice carved out of #8035. The rest of that prototype (accepting retained/file references in composed workflows) is intentionally not here — #8299 shipped that direction across 20 composition tools, and this branch builds on its shared resolver instead of competing with it. #8035 stays as the broader prototype record; this PR is the smaller, reviewable part.
Related to #4394 (investigation state that survives sessions). Scope note: this persists Evidence records, not the target-keyed finding ledger #4394 describes; that ownership question stays open there.
Problem and expected behavior
Trigger: a session produced authenticated Evidence; the analyst closes it and a later session holds only the
ev_…reference.Current limitation: nothing on disk retains that record, so the caller must re-transfer the full record, and #8307 reports the same transfer cost across a session transition.
Expected: with the store enabled, the later session resolves the reference to the stored record after re-authenticating it; a record that cannot be authenticated or safely read is treated as missing rather than trusted; a failed durable write is reported and stays retryable instead of being silently lost or permanently poisoned.
Change and scope
ProjectEvidenceStore— content-addressedrecords/<evidence_id>.json; each write goes to a0600temporary that is synced before its rename, so a reported durable write survives a host crash. Reads open the exact name without following links, require a regular file within a record-sized ceiling, and re-authenticate the content.closeandcloseWithSnapshot); target switches and external mutations do not flush. A failed flush composes with any existing cleanup failure, and theclose_binaryretry handle from fix(mcp): name the close_binary retry for retained cleanup #8329 is offered on the final failure so the composed error keeps it.EvidenceImportDeltanow reports the records the ledger actually committed, and the session persists exactly those. This covers bothimport_evidence_bundleand snapshot import, and replaces the earlier whole-session rescan.REA_EVIDENCE_STORE/REA_EVIDENCE_STORE_DIRresolution at the admitted environment, threaded into the artifact, native, managed and deep-binary session factories (the provider-free CLI paths were the gap Prototype: retained Evidence references and project store #8035 caught late)..gitignore— store settings indocs/installation.md, the contract note indocs/mcp-contracts.md, and.rea/ignored.Not included, deliberately: Unknown persistence, GC/retention policy, graph queries, a store manifest, CLI parity beyond the wired session factories, and moving the lookup read onto the shared async reader.
Contract and boundary impact
EvidenceLedgerowns what an import committed and now states it in the delta instead of leaving consumers to rescan;BinarySessionRecordsowns the session ledger and schedules durable writes for what its mutations committed;ProjectEvidenceStoreowns file layout, read admission, and authentication. Consumers are later sessions resolving references. No downstream stage reinterprets these facts..rea/evidence/records/*.json) under the compatibility rule inCONTRIBUTING.md. Draft status is intentional; no compatibility guarantee is claimed for the layout yet.EvidenceImportDeltais internal (two in-repo consumers, both updated).evidence_id, or is not a readable regular file, is reported as missing, not trusted. Exported session bundles still contain only that session's records — the store is a lookup source, not an implicit import.docs/mcp-contracts.mdanddocs/installation.mdupdated in source;skills/and catalogs remain CI-generated.Expected effects (check known effects; unchecked items do not establish absence):
Evidence and regression coverage
src/application/investigation/ProjectEvidenceStore.test.ts(5) — a failed write retried by the next flush after the obstruction is removed; a directory and a symlink at an expected record name both refused; an oversized (sparse) record refused before allocation; a relocated record keeps its newest display metadata with one file on disk; retained reads released on close force re-authentication instead of answering from the stale cache.tests/composition/sessionSnapshotEvidenceStore.test.ts(1) — realManagedStaticProviderobservation, snapshot export, close, then a second session with a fresh empty store opens the same target and imports that snapshot; the imported record is durable after close.src/config/projectEvidenceStore.test.ts(4) — store off by default, explicit absolute root, working-directory default, relative root rejected.tests/boundary/mcp/projectEvidenceStoreMcp.test.ts(4) — public MCP boundary: cross-session retained reference resolution, tampered record treated as missing, failed flush reported throughclose_binary.tests/composition/artifactSessionEvidenceStore.test.ts(1) — artifact, managed, and native session factories honorREA_EVIDENCE_STORE, the gap that made provider-free CLI paths ignore it.src/application/investigation/EvidenceLedger*.test.tsandInvestigationRecords.test.ts— import deltas now state the committed records (single add, metadata replacement, and the 10,000-record unknown chain).#persistCommittedcall removed from the snapshot merge path, the run fails and the receiving store holds no record; with it, the test passes. Store-level cases above each describe the failure they prevent.evidenceStoreFor()reads the raw environment instead of the shared config parser, soREA_EVIDENCE_STORE=projectwith a relativeREA_EVIDENCE_STORE_DIRdisables persistence without a word. Observed on this host:REA_EVIDENCE_STORE=project REA_EVIDENCE_STORE_DIR=rel rea inspect-macho /bin/ls --jsonexits 0 with a full result and writes nothing, whileREA_EVIDENCE_STORE_DIR=$PWD/abswrites the record.src/config/environment.tsalready rejects that value as aConfigurationError; the fix is to resolve these factories through the same admission rather than to widen the helper, which needs a decision about how a configuration error reaches the non-deep session factories (they currently return a session, not aResult).runManagedProviderExecution()closes its session insidewithSessionCleanup, andrunManagedProviderAnalysis()builds the returnedEvidenceafterwards, so that record never reaches the ledger or the store. Established by source reading ofsrc/application/DirectAnalysis.ts:296-345; not reproduced with a liveinspect-managed-*call because no managed target file exists on this host. The session-side import and record paths are covered by the tests above.mkfifoin the toolchain), so the non-blocking open is exercised through directory and symlink refusals rather than a real pipe; no host-crash proof of the sync-before-rename ordering; no injection where removing a failed temporary also fails, so the composed cleanup failure is unexercised; no multi-process concurrent-writer test; no real Ghidra/IDA/Hopper coverage (not installed here), so deep-provider sessions are exercised only through provider-free and simulated paths; GC/retention is unimplemented, so disk growth is bounded only by the analyst's project.Validation performed
npm run test:local -- src/application/investigation/{EvidenceLedger,EvidenceLedger.residualUnknown,InvestigationRecords,InvestigationEvidence,recordEvidenceSources,ProjectEvidenceStore}.test.ts src/config/projectEvidenceStore.test.ts— 48 passed (7 files).npm run test:focused -- tests/boundary/mcp/projectEvidenceStoreMcp.test.ts— 5 passed (4 existing + the caller-mutation case), and the same run with the fix reverted failsexpected undefined to deeply equal {…}, i.e. the store holds a record whose digest no longer matches itsevidence_id.npm run test:focused -- tests/composition/sessionSnapshotEvidenceStore.test.ts tests/composition/artifactSessionEvidenceStore.test.ts tests/composition/analysis-sessions/binarySessionCleanupRetry.test.ts tests/boundary/mcp/projectEvidenceStoreMcp.test.ts tests/boundary/mcp/sessionMcp.test.ts— 30 passed (5 files), including the 12 existingclose_binaryretry regressions from fix(mcp): name the close_binary retry for retained cleanup #8329 and the snapshot-lifecycle ordering cases.npm run test:focused -- tests/boundary/filesystem/directAnalysisSnapshotReplay.test.ts tests/boundary/filesystem/composedWorkflowEvidenceLinks.test.ts tests/boundary/filesystem/analysisSnapshotProvenance.test.ts tests/boundary/mcp/evidenceImportCancellation.test.ts tests/boundary/mcp/retainedApplicationEvidenceMcp.test.ts tests/boundary/mcp/evidenceImportLifecycle.test.ts tests/boundary/mcp/analysisSnapshotProvenanceMcp.test.ts tests/composition/analysis-sessions/{investigationRecords,binarySession}.test.ts— 112 passed, 2 skipped (9 files); these are the other consumers of the import and snapshot paths.npm run typecheck— clean.npm run lint(incl.verify:module-boundaries, 3504 files) — passed.npm run docs:check— passed (9 README-consistency tests).#8299and was not re-run here.Compatibility, safety, and release
skills/are CI-owned.0700/0600, records are canonicalized JSON re-authenticated on read, link-following and blocking reads at constructed record names are refused, the queued record is the ledger's sealed copy rather than the caller's mutable object, retained reads are released at close, and nothing leaves the machine. Remaining review targets: the two verification gaps above, and routing the synchronous lookup read through the shared async reader onceEvidenceLookupgains an async contract.Author readiness
Human owner:
Before merge
type(scope): outcome.