Skip to content

Prototype: retained Evidence references and project store - #8035

Closed
Mutersec wants to merge 13 commits into
morluto:mainfrom
Mutersec:feat/evidence-references-composed-workflows
Closed

Mutersec wants to merge 13 commits into
morluto:mainfrom
Mutersec:feat/evidence-references-composed-workflows

Conversation

@Mutersec

Copy link
Copy Markdown

Draft prototype for direction

This draft is not requesting merge yet. I am looking for maintainer guidance on
scope and the preferred integration path.

Problem

Composed MCP workflows required full Evidence records inline, so agents had to
re-send large dossiers and captures. Each new session also started without the
Evidence a previous session had already authenticated.

What this branch changes

  • build_call_path, find_changed_behavior, correlate_static_and_runtime,
    and compare_process_captures accept retained and Evidence-file references.
  • Managed member comparison, managed/native verification, managed application
    graph projection, and the Android/Apple/Harmony inventory projections accept
    the same reference forms.
  • Adds an opt-in project store under .rea/evidence, enabled with
    REA_EVIDENCE_STORE=project. Records are content-addressed, written
    atomically, re-authenticated on read, and flushed at final session close.
  • Adds a reproducible workflow baseline that reports the agent-visible catalog
    and per-workflow token, wall-time, CPU, and RSS estimates.

Validation

  • check:fast, docs:check, knip, and test discovery pass.
  • Focused MCP/integrity suites pass (166+ tests).
  • Full MCP suite: 1630/1646 passed. Two message-format failures reproduce on the
    base commit; three stdio resource tests fail under full-suite load and pass in
    isolation.
  • No real-provider verification and no model bake-off were run.

Scope questions

  • Is persistent project Evidence the right direction for REA?
  • Should the store stay opt-in and project-local?
  • Would you prefer this as an upstream PR, a design discussion first, or an
    independent fork?

I do not have write access to morluto/rea; this branch is on
Mutersec/rea:feat/evidence-references-composed-workflows. I am happy to split
or reduce the prototype to whichever slice you want to review first.

build_call_path, find_changed_behavior, and compare_process_captures
previously required inline Evidence. Callers had to re-send large records
that a session or Evidence file already retained.

Resolve retained and file references for these workflows through the shared
Evidence resolver, retain the selected records' available source closure,
and keep missing or mismatched links an integrity error. Update the MCP
contract documentation and cover both reference forms through the public
MCP boundary.
Record the default MCP catalog and representative composed workflows with
tokenx estimates, wall time, in-process CPU and RSS deltas. Compare inline
inputs with retained and Evidence-file references so later optimization has
a reproducible baseline.

The catalog profiles show the default full output schemas exceed a 1M token
context; compact output or output-off profiles are required for large models.
Fixtures use a simulated provider and never establish provider behavior.
Extend retained-evidence and evidence-file inputs to the remaining
inline-only MCP consumers: static/runtime correlation, managed member
comparison, managed/native verification, managed application graph
projection, and the Android, Apple, and Harmony inventory projections.

Resolve references before domain authentication, retain available source
closure, and fall back to the existing domain validation for malformed
inline input so error precedence stays unchanged. Cover retained and file
forms through the public MCP boundary.
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.
@greptile-apps

greptile-apps Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 0/5 Tier: apex

[High impact] The PR expands Evidence reuse across several MCP workflows and adds optional cross-session storage.

This draft is not ready to merge: saved-file reads can still freeze the server, persistence recovery remains broken, and the latest CLI wiring misses completed records.

Findings

  1. P1 CLI records are not saved ▶
  2. P1 Security Stored files can freeze REA ▶
  3. P1 Failed writes cannot recover ▶
  4. P1 Snapshot imports skip persistence ▶
  5. P1 Verification accepts missing sources ▶
  6. P2 Corrected paths revert later ▶
  7. P2 Closed investigations keep their memory ▶
  8. P2 Baseline leaves out task costs ▶
  9. P2 Failed staging files are abandoned ▶
  10. P2 Successful flush can lose records ▶
Fix with agent prompt
### Issue 1
src/composition/binary.ts:157-159
With `REA_EVIDENCE_STORE=project`, managed CLI inspections and Apple `.app` resource reads can succeed without saving their returned Evidence. Managed sessions have no analysis profile, so `BinarySession.execute` skips recording. `runManagedProviderAnalysis` builds the final Evidence only after the session closes. The app-resource branch also returns before `importEvidenceBundle`.

The new store wiring therefore leaves these returned IDs unavailable next session. Record the final Evidence through a shared owner before closing. Test actual commands rather than manually calling `recordEvidence`.

### Issue 2
src/application/investigation/ProjectEvidenceStore.ts:50-55
With project storage enabled, retained references read files synchronously before checking their type or available memory. If the expected filename contains a FIFO, the read can hang the server. A large file can exhaust memory before authentication. Cancellation cannot interrupt this read. Reuse the shared regular-file reader and its resource checks.

**How this was verified:** Retained references reach `ProjectEvidenceStore.read`, which calls `readFileSync` before authenticating the file contents.

### Issue 3
src/application/investigation/ProjectEvidenceStore.ts:32-37
If a write fails because the disk is full or permissions deny it, the ID stays in `#scheduled` and the error stays in `#failure`. After the storage problem is fixed, `persist` still skips the record and `flush` returns the old error without retrying. `close` also clears session records before flushing, removing the remaining export path. Retain failed writes and their Evidence until a retry succeeds.

### Issue 4
src/application/binary/BinarySessionRecords.ts:232-235
The new persistence hook covers `importEvidenceBundle`, but `importAnalysisSnapshot` merges Evidence directly into `#records` without scheduling writes. A user can open with `snapshot_path`, close successfully, and find every imported ID missing in the next session. Persist committed records at the shared ledger owner so both import routes are covered, rather than scanning the whole session only in this wrapper.

### Issue 5
src/application/EvidenceInputResolver.ts:174-176
Missing links are skipped here, but managed verification never performs the promised later check. If a saved `analyze_function` record names an unavailable source, `verify_managed_native_boundaries` can succeed and retain an incomplete Evidence chain. That breaks the new contract that missing linked Evidence is an integrity error. Check required links in the shared source resolver after gathering the selected sources.

### Issue 6
src/application/investigation/ProjectEvidenceStore.ts:30-33
Importing a relocated record updates the ledger’s path and name without changing its `evidence_id`. Here, `persist` skips that replacement because the ID was already scheduled, so the next session restores the old metadata. Cached reads can also keep the old value. Coalesce pending writes rather than all future metadata updates, and refresh the cache when a replacement is written.

### Issue 7
src/application/investigation/ProjectEvidenceStore.ts:undefined-58
Every stored record read stays in `#cache` for the server’s lifetime. `close_binary` clears the session ledger but never clears or limits this second collection, so repeated investigations keep complete dossiers in memory after closing. `AGENTS.md` requires retained state to be bounded. Bound or release this cache before merging.

### Issue 8
tests/evaluation/rea2Baseline.test.ts:107-112
The baseline omits costs that `AGENTS.md` requires:
- Sources are preloaded outside the measurements.
- Output counts include only `structuredContent`, not the delivered text copy.
- The first run is discarded, and RSS deltas are not peak memory.

Include whole-task costs, separate cold and warm results, and measure peak process-family memory. Otherwise, clearly label these as partial warm-call measurements and list the omitted costs. The repository’s measurement requirements 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!

### Issue 9
src/application/investigation/ProjectEvidenceStore.ts:106-108
If writing or renaming fails and removing the temporary file also fails, this catch discards the cleanup error and filename. No later close can retry removal. `AGENTS.md` requires ownership of resources whose cleanup failed to be retained. Keep the temporary-file owner and report both failures before merging.

### Issue 10
src/application/investigation/ProjectEvidenceStore.ts:100-105
`flush` promises durable writes, but `#write` only writes and renames. It never syncs the file contents or directory changes. If the host crashes after a successful close, a supposedly durable record can disappear. Use the shared durable-publication approach to sync the file and supported directories before reporting success.

---

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

Summary

Adds retained and saved-file Evidence inputs to composed workflows, plus opt-in project storage.

  • REA workflows accept retained Evidence IDs and selected records from Evidence files.
  • Sessions can reuse authenticated Evidence from an opt-in project store.
  • A workflow baseline reports catalog size and estimated call costs.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  Input["Inline, retained, or saved-file Evidence"] --> Resolve["Resolve selected records and linked sources"]
  Resolve --> Workflow["Run composed workflow"]
  Workflow --> Records["Session records"]
  Environment["Opt-in environment"] --> Root["Shared store-root selection"]
  Root --> Store["ProjectEvidenceStore"]
  Records -->|queue writes| Store
  Store -->|lookup by evidence_id| Records
  Close["Session close"] -->|flush writes| Store
Loading

Reviews (2) · Last reviewed commit: "fix(evidence): wire project store into a..." · Reviewed by Greptile

Comment on lines +50 to +55
const path = join(this.#recordsDirectory, `${evidenceId}.json`);
if (!existsSync(path)) return undefined;
try {
const parsed = readImmutableEvidence(
JSON.parse(readFileSync(path, "utf8")),
);

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 security Stored files can freeze REA

With project storage enabled, retained references read files synchronously before checking their type or available memory. If the expected filename contains a FIFO, the read can hang the server. A large file can exhaust memory before authentication. Cancellation cannot interrupt this read. Reuse the shared regular-file reader and its resource checks.

How this was verified: Retained references reach ProjectEvidenceStore.read, which calls readFileSync before authenticating the file contents.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/application/investigation/ProjectEvidenceStore.ts
Line: 50-55

Comment:
**Stored files can freeze REA**

With project storage enabled, retained references read files synchronously before checking their type or available memory. If the expected filename contains a FIFO, the read can hang the server. A large file can exhaust memory before authentication. Cancellation cannot interrupt this read. Reuse the shared regular-file reader and its resource checks.

**How this was verified:** Retained references reach `ProjectEvidenceStore.read`, which calls `readFileSync` before authenticating the file contents.

---

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

Comment on lines +32 to +37
if (!EVIDENCE_ID.test(id) || this.#scheduled.has(id)) return;
this.#scheduled.add(id);
const write = this.#writeChain.then(() => this.#write(evidence));
this.#writeChain = write.catch(() => undefined);
const pending = write.catch((cause: unknown) => {
this.#failure ??= cause;

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 Failed writes cannot recover

If a write fails because the disk is full or permissions deny it, the ID stays in #scheduled and the error stays in #failure. After the storage problem is fixed, persist still skips the record and flush returns the old error without retrying. close also clears session records before flushing, removing the remaining export path. Retain failed writes and their Evidence until a retry succeeds.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/application/investigation/ProjectEvidenceStore.ts
Line: 32-37

Comment:
**Failed writes cannot recover**

If a write fails because the disk is full or permissions deny it, the ID stays in `#scheduled` and the error stays in `#failure`. After the storage problem is fixed, `persist` still skips the record and `flush` returns the old error without retrying. `close` also clears session records before flushing, removing the remaining export path. Retain failed writes and their Evidence until a retry succeeds.

---

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

Comment on lines +232 to +235
if (imported.value.changed) {
this.#emitSnapshotChanged();
for (const evidence of this.immutableEvidenceBundle().records)
this.#evidenceStore?.persist(evidence);

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 Snapshot imports skip persistence

The new persistence hook covers importEvidenceBundle, but importAnalysisSnapshot merges Evidence directly into #records without scheduling writes. A user can open with snapshot_path, close successfully, and find every imported ID missing in the next session. Persist committed records at the shared ledger owner so both import routes are covered, rather than scanning the whole session only in this wrapper.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/application/binary/BinarySessionRecords.ts
Line: 232-235

Comment:
**Snapshot imports skip persistence**

The new persistence hook covers `importEvidenceBundle`, but `importAnalysisSnapshot` merges Evidence directly into `#records` without scheduling writes. A user can open with `snapshot_path`, close successfully, and find every imported ID missing in the next session. Persist committed records at the shared ledger owner so both import routes are covered, rather than scanning the whole session only in this wrapper.

---

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

Comment on lines +30 to +33
persist(evidence: Evidence): void {
const id = evidence.evidence_id;
if (!EVIDENCE_ID.test(id) || this.#scheduled.has(id)) return;
this.#scheduled.add(id);

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 Corrected paths revert later

Importing a relocated record updates the ledger’s path and name without changing its evidence_id. Here, persist skips that replacement because the ID was already scheduled, so the next session restores the old metadata. Cached reads can also keep the old value. Coalesce pending writes rather than all future metadata updates, and refresh the cache when a replacement is written.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/application/investigation/ProjectEvidenceStore.ts
Line: 30-33

Comment:
**Corrected paths revert later**

Importing a relocated record updates the ledger’s path and name without changing its `evidence_id`. Here, `persist` skips that replacement because the ID was already scheduled, so the next session restores the old metadata. Cached reads can also keep the old value. Coalesce pending writes rather than all future metadata updates, and refresh the cache when a replacement is written.

---

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

);
if (!parsed.ok || parsed.value.evidence_id !== evidenceId)
return undefined;
this.#cache.set(evidenceId, parsed.value);

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 Closed investigations keep their memory

Every stored record read stays in #cache for the server’s lifetime. close_binary clears the session ledger but never clears or limits this second collection, so repeated investigations keep complete dossiers in memory after closing. AGENTS.md requires retained state to be bounded. Bound or release this cache 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: 58

Comment:
**Closed investigations keep their memory**

Every stored record read stays in `#cache` for the server’s lifetime. `close_binary` clears the session ledger but never clears or limits this second collection, so repeated investigations keep complete dossiers in memory after closing. `AGENTS.md` requires retained state to be bounded. Bound or release this cache 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.

Comment on lines +174 to +176
const linked = lookup?.(id);
// Missing or mismatched links remain for the workflow's closure check.
if (linked?.evidence_id === id) pending.push(linked);

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 Verification accepts missing sources

Missing links are skipped here, but managed verification never performs the promised later check. If a saved analyze_function record names an unavailable source, verify_managed_native_boundaries can succeed and retain an incomplete Evidence chain. That breaks the new contract that missing linked Evidence is an integrity error. Check required links in the shared source resolver after gathering the selected sources.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/application/EvidenceInputResolver.ts
Line: 174-176

Comment:
**Verification accepts missing sources**

Missing links are skipped here, but managed verification never performs the promised later check. If a saved `analyze_function` record names an unavailable source, `verify_managed_native_boundaries` can succeed and retain an incomplete Evidence chain. That breaks the new contract that missing linked Evidence is an integrity error. Check required links in the shared source resolver after gathering the selected sources.

---

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

Comment on lines +107 to +112
const evidence = parseEvidence(response.structuredContent);
if (run >= WARMUP_RUNS) {
output = evidence;
elapsed.push(finished - started);
cpu.push((cpuDelta.user + cpuDelta.system) / 1000);
rss.push(process.memoryUsage().rss - rssBefore);

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 Baseline leaves out task costs

The baseline omits costs that AGENTS.md requires:

  • Sources are preloaded outside the measurements.
  • Output counts include only structuredContent, not the delivered text copy.
  • The first run is discarded, and RSS deltas are not peak memory.

Include whole-task costs, separate cold and warm results, and measure peak process-family memory. Otherwise, clearly label these as partial warm-call measurements and list the omitted costs. The repository’s measurement requirements 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/evaluation/rea2Baseline.test.ts
Line: 107-112

Comment:
**Baseline leaves out task costs**

The baseline omits costs that `AGENTS.md` requires:
- Sources are preloaded outside the measurements.
- Output counts include only `structuredContent`, not the delivered text copy.
- The first run is discarded, and RSS deltas are not peak memory.

Include whole-task costs, separate cold and warm results, and measure peak process-family memory. Otherwise, clearly label these as partial warm-call measurements and list the omitted costs. The repository’s measurement requirements 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!

Comment on lines +106 to +108
} catch (cause) {
await rm(temporary, { force: true }).catch(() => undefined);
throw cause;

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 Failed staging files are abandoned

If writing or renaming fails and removing the temporary file also fails, this catch discards the cleanup error and filename. No later close can retry removal. AGENTS.md requires ownership of resources whose cleanup failed to be retained. Keep the temporary-file owner and report both failures 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 staging files are abandoned**

If writing or renaming fails and removing the temporary file also fails, this catch discards the cleanup error and filename. No later close can retry removal. `AGENTS.md` requires ownership of resources whose cleanup failed to be retained. Keep the temporary-file owner and report both failures 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.

Comment on lines +100 to +105
await writeFile(
temporary,
`${canonicalize(evidence) ?? JSON.stringify(evidence)}\n`,
{ mode: 0o600 },
);
await rename(temporary, path);

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 Successful flush can lose records

flush promises durable writes, but #write only writes and renames. It never syncs the file contents or directory changes. If the host crashes after a successful close, a supposedly durable record can disappear. Use the shared durable-publication approach to sync the file and supported directories before reporting success.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/application/investigation/ProjectEvidenceStore.ts
Line: 100-105

Comment:
**Successful flush can lose records**

`flush` promises durable writes, but `#write` only writes and renames. It never syncs the file contents or directory changes. If the host crashes after a successful close, a supposedly durable record can disappear. Use the shared durable-publication approach to sync the file and supported directories before reporting success.

---

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

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.
Comment thread src/composition/binary.ts
Comment on lines +157 to +159
selectedEnvironment === undefined
? undefined
: evidenceStoreFor(selectedEnvironment),

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 CLI records are not saved

With REA_EVIDENCE_STORE=project, managed CLI inspections and Apple .app resource reads can succeed without saving their returned Evidence. Managed sessions have no analysis profile, so BinarySession.execute skips recording. runManagedProviderAnalysis builds the final Evidence only after the session closes. The app-resource branch also returns before importEvidenceBundle.

The new store wiring therefore leaves these returned IDs unavailable next session. Record the final Evidence through a shared owner before closing. Test actual commands rather than manually calling recordEvidence.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/composition/binary.ts
Line: 157-159

Comment:
**CLI records are not saved**

With `REA_EVIDENCE_STORE=project`, managed CLI inspections and Apple `.app` resource reads can succeed without saving their returned Evidence. Managed sessions have no analysis profile, so `BinarySession.execute` skips recording. `runManagedProviderAnalysis` builds the final Evidence only after the session closes. The app-resource branch also returns before `importEvidenceBundle`.

The new store wiring therefore leaves these returned IDs unavailable next session. Record the final Evidence through a shared owner before closing. Test actual commands rather than manually calling `recordEvidence`.

---

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

@Mutersec

Copy link
Copy Markdown
Author

Superseded in parts by #8359 (store slice) after #8299 landed.

Leaving this PR open as the prototype record and the measurement context; closing it on my side if a maintainer prefers.

@N0zoM1z0

Copy link
Copy Markdown
Collaborator

Thanks for the prototype. Its retained-reference half landed through #8299 (src/application/EvidenceInputResolver.ts), and the persistence half continues in #8359, so we're closing this prototype in favor of #8359 for the remaining scope discussion.

@N0zoM1z0 N0zoM1z0 closed this Nov 14, 2026
@morluto morluto added the area: evidence Evidence, artifacts, and reconstruction label Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: evidence Evidence, artifacts, and reconstruction

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants