Skip to content

feat: add persistent read-before-write ledgers - #946

Merged
jerm-dro merged 35 commits into
mainfrom
acc/persistent-read-ledgers
Sep 4, 2026
Merged

jerm-dro merged 35 commits into
mainfrom
acc/persistent-read-ledgers

Conversation

@jerm-dro

@jerm-dro jerm-dro commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • separate read-before-write evidence from filesystem content by carrying a mandatory tool.ReadLedger on each execution environment
  • add in-memory and Redis-backed ledger implementations with conformance, persistence, corruption, identity, and cleanup coverage
  • preserve fresh child evidence across Subagent, Parallel, and Team paths while retaining each child’s actual content backend and path-containment boundary
  • update ADR 0290, architecture references, acceptance criteria, API baseline, changelog, and generated documentation surfaces

Closes #888.

Large PR Justification

This change deliberately lands as one atomic compatibility migration. Making ReadLedger an independent, mandatory Environment capability changes the core execution contract, so every environment constructor, filesystem adapter, delegation path, and test fixture must move together; splitting those updates would leave intermediate commits or PRs uncompilable or weaken read-before-write safety. The Redis implementation and atomic session-deletion cleanup are included to prove that the new seam works across processes rather than only in memory. The remaining volume is the required conformance, failure-path, API-baseline, acceptance-plan, architecture, changelog, and generated-documentation coverage for that single contract change—not unrelated feature work.

Verification

  • task generate
  • task lint
  • task test
  • go run ./cmd/mecademo
  • git diff --check

All verification passed locally. Panel review was intentionally skipped at the requester’s direction.

jerm-dro and others added 21 commits August 31, 2026 19:04
Refactor the Edit/Write read-before-write ledger from an inline in-memory
map on each Workspace implementation into a standalone, error-bearing,
context-aware tool.ReadLedger capability (ADR 0278, issue #888). A
Workspace now composes with a SELECTED ReadLedger, a fresh in-memory one
by default (engine/adapter/memledger), rather than owning ledger storage
itself, so a durable ledger can be selected independently of file-content
storage in a later task.

- engine/tool/ledger.go: the ReadLedger interface (RecordRead and
  RecordedVersion, both context-aware and error-returning) plus
  ErrLedgerUnavailable, distinguishing three outcomes: a valid recorded
  token, ordinary absence, and an unavailable/corrupt lookup.
- engine/adapter/memledger: the in-memory reference ReadLedger.
- engine/adapter/ledgerconformance: the shared behavioral suite every
  ReadLedger implementation runs.
- tool.Workspace.RecordRead/RecordedVersion signatures change to thread
  context.Context and return an error (Changed/breaking, pre-v1 minor
  bump per engine/COMPATIBILITY.md); every in-tree Workspace
  implementation is migrated: osfs, memfs, nofs, the ACP fs-delegation
  workspace (kept independently synchronized from its fs RPC path,
  AC3.8), remoteenv, the escape-policy wrapper, and the engine/agent stub
  workspaces (forkjudge, usermodelreview).
- engine/adapter/fstools: Read/Edit/Write thread the ledger's errors
  through to the model. A failed RecordRead is reported as unretained
  evidence, failing closed on the next mutation; an unavailable/corrupt
  RecordedVersion lookup refuses before ReplaceFile is ever called; a
  post-mutation record failure is reported honestly without rollback.
  Create-only Write semantics and the final conditional ReplaceFile and
  CreateFile CAS are unchanged.
- engine/api/tool.txt and engine/CHANGELOG.md updated per the engine
  stability contract (ADR 0037).

Verified ACs: AC1.1-AC1.4, AC3.1-AC3.8 (AC3.7 by full-suite inspection).
Lint, go vet, and go test -race are green for both the root and engine
modules, including the engine GOWORK=off standalone build and test. The
offline mecademo binary still prints a full session.

Co-Authored-By: Claude <[email protected]>
Co-Authored-By: OpenAI Codex <[email protected]>
Adds internal/adapter/redisstore.Store.ReadLedger / DeleteReadLedger: the
first non-memory tool.ReadLedger implementation, sharing the Store's existing
Redis client generations, secure connection posture, and mecatl:<kind>: key
prefix convention. Each session gets one Redis hash (mecatl:ledger:<id>)
keyed by the already-normalized path; the value is a versioned {v,t} JSON
record carrying the caller's exact opaque FileVersion token. The (session,
path) addressing is injective by construction -- session lives in the key,
path in the hash field, never concatenated into one delimited string -- so
adversarial separators or shared prefixes between the two cannot collide.

RecordedVersion distinguishes absence (redis.Nil -> ok=false, err=nil) from
an unavailable/corrupt lookup (any other client error, an undecodable value,
or an unrecognized format tag -> err wrapping tool.ErrLedgerUnavailable).
RecordRead and DeleteReadLedger fail closed the same way. No file-content
operation is exposed; this stays a proof adapter (no production default, no
mecak8s wiring) per the plan's scope cut to #889.

Named tests (docs/acceptance/persistent-read-before-write-ledgers.md
Scenario 2 + the shared conformance run):
- TestReadLedgerConformance (AC2.5, memledger + Redis over the shared suite)
- TestPersistentReadLedgers_Scenario2_RedisReopen (AC2.1)
- TestPersistentReadLedgers_Scenario2_RedisSessionIsolation (AC2.2)
- TestInvariant_persistent_read_ledger_storage_independence (AC2.3)
- TestPersistentReadLedgers_Scenario2_RedisFailureClassification (AC2.4)
- TestPersistentReadLedgers_Scenario2_ConcurrentAccess (AC2.6)
- TestPersistentReadLedgers_Scenario2_DeleteAndReuseStartsEmpty (AC2.7)
- TestPersistentReadLedgers_Scenario2_InjectiveRedisIdentity (AC2.8)

Co-Authored-By: Claude <[email protected]>
Reconcile the living architecture, port, implementation, and cloud-native lifecycle documentation with ADR 0278 while preserving the final filesystem CAS and core layering boundary.

Co-Authored-By: OpenAI Codex <[email protected]>
Resolve Redis deletion, environment-constructor, generated-doc, and ADR-number conflicts while preserving both session lineage and read-ledger cleanup.

Co-Authored-By: OpenAI Codex <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR implements storage-independent “read-before-write” evidence by making tool.ReadLedger a mandatory capability of tool.Environment (separate from the file-content tool.Workspace), and wires fresh per-child ledgers across Subagent/Parallel/Team paths while preserving each child’s actual content backend and path-containment boundary.

Changes:

  • Introduces the tool.ReadLedger contract and makes it mandatory on tool.Environment; updates file tools to record/verify evidence via env.ReadLedger() instead of a Workspace-embedded ledger.
  • Adds an in-memory reference ledger (engine/adapter/memledger) and updates tests/examples to construct environments with a ledger plus ledger factories for delegation paths.
  • Ensances durable lifecycle correctness by deleting Redis ledger state atomically alongside other session sidecars.

Reviewed changes

Copilot reviewed 127 out of 128 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
perf/scenarios/team_fanout_test.go Updates perf scenario wiring to construct environments with memledger and provide a team ledger factory.
perf/scenarios/helpers_test.go Ensures scenario environments include a non-nil ReadLedger.
internal/app/task_shell_test.go Updates Subagent test wiring to provide a child-ledger factory.
internal/app/subprovider_test.go Switches Subagent construction to a helper that injects the ledger factory.
internal/app/subagent_writable_test.go Updates no-fs Subagent tests to pass a ledger into the environment.
internal/app/subagent_perm_config_test.go Injects Subagent child-ledger factory in permission-config tests.
internal/app/sourcedriver_test.go Updates skill source tests to use environments that include a ledger.
internal/app/shell_less_posture_test.go Updates shell-less / no-fs environment fixtures to include a ledger.
internal/app/roletelemetry_test.go Uses a ledger-factory-injecting Subagent helper to keep tests aligned with new env contract.
internal/app/pathescape_scenario5c_test.go Comment-only clarification of scenario helper behavior (no functional change).
internal/app/pathescape_scenario5b_test.go Updates comments to reflect confined child workspace view behavior.
internal/app/pathescape_scenario4_test.go Ensures relaxed-workspace override environments include a ledger.
internal/app/pathescape_scenario3_test.go Updates path-escape tests to pass a ledger when constructing environments.
internal/app/nofs_team_test.go Wires a team ledger factory into no-fs team test wiring.
internal/app/member_agentdef_test.go Uses a Supervisor helper that injects team ledger factory.
internal/app/environment_test.go Adds helpers for ledger-factory injection and tests that child workspace views preserve underlying content backend identity.
internal/app/catalog.go Wires a default team-tool ledger factory (memledger) into catalog registration.
internal/app/askadjudicator_test.go Updates Team tool construction to inject a ledger factory.
internal/app/agentdefs_test.go Uses Subagent helper that injects ledger factory in agent-def tests.
internal/app/agentdef_mcp_test.go Uses Supervisor helper that injects team ledger factory in MCP-related member tests.
internal/adapter/tools/tools_test.go Updates tool test harness to build environments with a per-workspace test ledger.
internal/adapter/tools/abspath_tools_test.go Uses the per-workspace test ledger when constructing an environment.
internal/adapter/telemetry/metrics_test.go Updates environment construction in telemetry tests to include a ledger.
internal/adapter/skills/lifecycle_drafter_test.go Updates skill-draft tool tests to pass a ledger into the environment.
internal/adapter/server/workspace_authority_scenario_test.go Ensures environment overrides constructed in tests include a ledger.
internal/adapter/server/workspace_authority_internal_test.go Updates internal authority override tests to construct environments with a ledger.
internal/adapter/server/team.go Constructs the team base environment with a ledger and injects a team ledger factory.
internal/adapter/server/subagent_cause_eventlog_test.go Uses server Subagent helper that injects a ledger factory.
internal/adapter/server/eventlog_test.go Uses server Subagent helper that injects a ledger factory.
internal/adapter/server/environment_override_test.go Adds helper constructors that inject Subagent/Team tool ledger factories; updates env override fixture to include a ledger.
internal/adapter/server/cancelchild_test.go Uses server Subagent/Team helpers that inject ledger factories.
internal/adapter/server/caller_separation_live_test.go Updates test environment construction to include a ledger.
internal/adapter/server/adoption.go Ensures adopted no-fs sessions get an environment that includes a ledger.
internal/adapter/remoteenv/remoteenv_test.go Removes calls to Workspace-embedded ledger APIs now that evidence is externalized.
internal/adapter/remoteenv/forkmerge.go Ensures remoteenv forks construct environments with a non-nil ledger.
internal/adapter/redisstore/metadata_index.go Updates Redis delete Lua scripts to delete ledger state atomically with other session sidecars.
internal/adapter/osfs/version_alias_test.go Migrates osfs ledger tests to use a test ReadLedger rather than Workspace-embedded state.
internal/adapter/osfs/testledger_test.go Adds test-only helpers to record/lookup ledger state via a ReadLedger.
internal/adapter/osfs/osfs.go Removes Workspace-embedded ledger state, keeping osfs Workspace content-only.
internal/adapter/osfs/osfs_abspath_test.go Migrates absolute/relative ledger-key tests to use the test ledger helpers.
internal/adapter/memory/namespaced_store_test.go Updates no-fs test environment for memory tools to include a ledger.
internal/adapter/memory/loop_search_integration_test.go Updates loop integration test environment to include a ledger.
internal/adapter/llmresilience/loop_stall_test.go Updates test environment construction to include a ledger.
internal/adapter/hookexec/loop_integration_test.go Updates loop integration test environment to include a ledger.
internal/adapter/forker/forker.go Ensures forked child environments are constructed with a non-nil ledger.
internal/adapter/acp/agent.go Updates ACP per-session environment override construction to include a ledger.
examples/first-agent/main.go Updates example to construct an environment with memledger.
examples/first-agent-tool/main.go Updates example to construct an environment with memledger.
examples/first-agent-openrouter/main.go Updates example to construct an environment with memledger.
examples/first-agent-approval/main.go Updates example to construct an environment with memledger.
engine/tool/isolation.go Updates EnvironmentForker contract doc to specify child environments include a fresh ledger.
engine/tool/fileversion_test.go Adds round-trip tests for FileVersion persistence encoding/decoding.
engine/tool/envtest_test.go Updates tool-package test environment to include a stub ReadLedger.
engine/api/agent.txt Updates public API baseline for the new ledger factories and WithSharedChildWorkspace signature change.
engine/agent/usermodelreview.go Updates user-model review environment to include a non-nil ReadLedger.
engine/agent/readledger_test.go Sets a test-default ledger factory for constructor-focused fixtures.
engine/agent/forkjudge.go Updates judge environment construction to include a non-nil ReadLedger.
engine/agent/export_env_test.go Reuses the package testEnvironment helper to ensure envs include a ledger.
engine/agent/envtest_test.go Updates agent test environment helpers to include a ledger.
engine/agent/environment_ledger_test.go Adds tests asserting child environments preserve the intended content backend and always get a fresh ledger.
engine/agent/bashtool_internal_test.go Updates bash test environment fixtures to include a ledger.
engine/agent/attempt_correlation_test.go Updates agent loop tests to build environments with a ledger.
engine/adapter/webfetch/webfetch_test.go Updates tool execution env fixture to include a ledger.
engine/adapter/webfetch/webfetch_e2e_test.go Updates agent loop env fixture to include a ledger.
engine/adapter/skillfs/tool_test.go Updates stub tool test env construction to include a stub ledger.
engine/adapter/search/websearch_test.go Updates tool execution env fixtures to include a ledger.
engine/adapter/search/websearch_e2e_test.go Updates agent loop env fixture to include a ledger.
engine/adapter/nofs/nofs.go Removes the no-fs Workspace’s legacy ledger methods now that evidence is externalized.
engine/adapter/nofs/nofs_test.go Drops now-obsolete assertions about Workspace-embedded ledger behavior.
engine/adapter/memledger/memledger.go Adds the in-memory reference tool.ReadLedger implementation.
engine/adapter/memfs/memfs.go Removes Workspace-embedded ledger state, keeping memfs Workspace content-only.
engine/adapter/fstools/read.go Records read evidence via env.ReadLedger() using a normalized ledger key.
engine/adapter/fstools/edit.go Enforces read-before-edit via env.ReadLedger() and re-records evidence after successful CAS writes.
engine/adapter/fsconformance/fsconformance.go Updates conformance tests to stop asserting Workspace-embedded ledger semantics.
engine/adapter/eventsource/review_test.go Updates loop execution env fixtures to include a ledger.
engine/adapter/eventsource/determinism_test.go Updates loop execution env fixtures to include a ledger.
docs/adr/README.md Adds ADR index entry for ADR 0281.
docs/acceptance/README.md Adds acceptance plan index entry for persistent read-before-write ledgers.
.golangci.yml Adds depguard configuration for memledger and ledgerconformance and linter exclusions for the new conformance package.
.claude/plans/persistent-read-before-write-ledgers/tasks/07-repair-docs-and-acceptance.md Adds orchestration task record for docs/acceptance repairs.
.claude/plans/persistent-read-before-write-ledgers/tasks/06-redis-ledger-hardening.md Adds orchestration task record for Redis ledger hardening.
.claude/plans/persistent-read-before-write-ledgers/tasks/05-environment-ledger-separation.md Adds orchestration task record for separating content and evidence seams.
.claude/plans/persistent-read-before-write-ledgers/tasks/04-docs-and-layering.md Adds orchestration task record for docs/layering reconciliation.
.claude/plans/persistent-read-before-write-ledgers/tasks/03-redis-ledger.md Adds orchestration task record for Redis ledger proof work.
.claude/plans/persistent-read-before-write-ledgers/tasks/02-fork-ledger-isolation.md Adds orchestration task record for child ledger isolation.
.claude/plans/persistent-read-before-write-ledgers/README.md Adds orchestration plan README tying tasks to acceptance plan and accumulator branch.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread engine/adapter/fstools/edit.go Resolved
Comment thread engine/adapter/memledger/memledger.go Resolved
jerm-dro and others added 2 commits September 2, 2026 10:31
Renumber the persistent-ledger ADR to 0289 after upstream claimed 0281, regenerate documentation, and keep benchmark fixture allocation outside the measured BuildRequest hot path.

Co-Authored-By: OpenAI Codex <[email protected]>
Resolve the generated documentation conflict and renumber the persistent-ledger ADR to 0290 after upstream assigned 0289.

Co-Authored-By: OpenAI Codex <[email protected]>
Comment thread engine/tool/ledger.go
// Conformance: engine/adapter/ledgerconformance is the shared behavioral suite
// every implementation must pass (the in-memory reference adapter
// engine/adapter/memledger runs it; a durable adapter runs it over its client).
type ReadLedger interface {

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.

I think this is good and both makes sense for the short term and prepares for the long term. Since I think you read the attentuation proposal I was wondering if you have any thoughts about how this work might evolve towards that proposal?

I was wondering (with some AI brainstorming/sketching) if we should add as the next evolution a bunch of references to content sources to under EnvironmentRef something like:

EnvironmentRef
             └── NamespaceSpec
                   ├── Mount /project
                   │     └── SourceRef{kind: disk, id: ...}
                   │         recovery: required
                   ├── Mount /attachments
                   │     └── SourceRef{kind: blob-store, id: ...}
                   │         recovery: required
                   └── Mount /scratch
                         └── SourceRef{kind: memfs, id: ...}
                             recovery: reset-on-restart

and then have a service that would resolve that EnvironmentRef to an environment while binding the sourceRefs into a workspace.

Concretely, this would allow us to have per-session attachments or artifacts in a filesystem projection.

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.

I'm not sure that this has to take that into account. By the time we get to the Environment the filesystem is fully composed and the various mounts don't really matter. The read ledger works with the agent's view and doesn't need to know about filesystem composition.

The only thing that may play in here is if we have some sort of file aliasing that the agent knows about. Things like hard or soft links. A read from one direction should probably count as a read from another direction (reads keyed on inode id instead of file path) but that is more of an optimization than anything else.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That’s an interesting idea. I think it’s valuable, but the factoring seems tricky: the composed namespace should ideally be implemented below both the agent’s filesystem tools and Bash, so they see the same filesystem regardless of whether Bash is enabled.

// Command execution is not part of the Workspace; use CommandRunner for that.
// Workspace is the in-memory session-scoped content seam. Command execution
// and read-before-write evidence are carried separately by tool.Environment.
type Workspace struct {

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.

At this point, is it worth collapsing Workspace and Filesystem for memfs?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed. The distinction is confusing now that the ledger is separate. I’d eventually like to collapse both the interfaces and implementations into a smaller filesystem surface, but handle that as a separate API cleanup since these types are exported.

Comment thread engine/agent/forkjudge.go

// emptyReadLedger is for shell-less, tool-less helper engines. Their catalog cannot
// create file-read evidence, so retaining it would have no observable effect.
type emptyReadLedger struct{}

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.

It might make sense to break this out into it's own package. Or, at the very least, it's own file as it is used in other places in this package and it feels like this is where it just ended up.

}
ref := session.EnvironmentRef{Kind: base.Ref().Kind, ID: root, Revision: base.Ref().Revision}
return tool.NewEnvironment(ref, ws, runner)
return tool.NewEnvironment(ref, ws, memledger.New(), runner)

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.

Is the memledger the right thing here? Do we sometimes want to persist child environments and, as such, need a persistent ledger? I'm unsure of the existing behavior.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch. The child session is persisted, but its ledger currently is not: internally created children always receive a fresh in-memory ledger instead of the configured session-state storage. That looks like a gap. A child should use the same storage mechanism as its parent, while retaining its own session-scoped ledger state. We don’t need to fix that here; the session-owned extensible state model proposed in #1025 would address it at the right layer.

@@ -719,20 +719,15 @@ func pathLock(canon string) *sync.Mutex {
// without any shell at all.
type Workspace struct {
fs *FileSystem

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.

Another example of where FileSystem now equals Workspace so perhaps we want to collapse these?

Comment thread internal/app/placement.go
runner = p.runnerForRoot(ws.Root())
}
env, err := tool.NewEnvironment(ref, ws, runner)
env, err := tool.NewEnvironment(ref, ws, memledger.New(), runner)

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.

This really feels like it should not be a memledger. Is the plan to come back and fix these up to have real persistence? Or was this the previous behavior?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This preserves the previous default behavior. When persistent ledger storage is configured, the service replaces this temporary in-memory ledger with the session’s durable ledger after reattaching the placement. The construction is awkward, though, and the session-owned storage model proposed in #1025 should remove the need to select ledger storage while constructing an environment.

@jbeda jbeda left a comment

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.

The approach looks good to me. Some questions/comments but that may be my lack of full understanding. Overall, the refactor feels right and the filesystem/workspace shouldn't hold the ledger.

@jerm-dro
jerm-dro merged commit 8842415 into main Sep 4, 2026
25 checks passed
@jerm-dro
jerm-dro deleted the acc/persistent-read-ledgers branch September 4, 2026 15:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support persistent read-before-write ledgers

4 participants