Architecture Review · Persistence Layer

Dagu Persistence Layer Refactoring

Deep Module redesign: introduce a single pluggable Backend interface so control-plane stores share one file-I/O implementation. Boundary established and the first wave of stores ported; ~9 still run behind their original leaf packages (incremental, ongoing), while DAG-run and proc stay file-specific by design. The seam makes future PostgreSQL/etcd backends possible without rewriting every store.

Control-plane stores → Backend interface id + data blob (Temporal pattern) DAG-run stays backend-specific Zero data-layout changes
Current branch as of May 27, 2026 — DAG-run compatibility slice Queue/dagrun/proc file compatibility done · distributed CAS done · SQL backend pending

What Temporal Got Right

Distilled from studying temporal/common/persistence/

🏭

Single Factory, Many Backends

DataStoreFactory is the sole interface any database driver must implement. Cassandra, PostgreSQL, SQLite — all satisfy one interface. Swapping backends is a config change.

📦

id + opaque DataBlob

Complex domain objects (ActivityInfo, TimerInfo, MutableState) are serialized to protobuf/JSON blobs. Backends store id + bytes, not per-field columns. Domain model changes never touch the schema.

🧅

Layered Concerns

Store layer (raw CRUD + blobs) → Manager layer (serialization + business logic) → Client layer (metrics, retry, rate-limit). Each layer adds one responsibility. Callers only see the outermost layer.

Key insight we borrow for Dagu

Temporal stores execution state as opaque blobs alongside a few indexed key columns (namespace_id, workflow_id, run_id). Dagu's equivalent: a records table with collection + id + data + encoding + created_at + updated_at + expires_at. No per-domain columns. Domain model evolves freely inside the blob.

Current State

The friction that motivates this refactoring

30

separate file-store packages

~9k

lines to rewrite per new backend

0

shared storage seams

∞

file-I/O duplication

Original Architecture — Each Store Owned Its Own File I/O

graph TB subgraph App["Application Layer"] direction LR RT["runtime"] SC["scheduler"] CO["coordinator"] AU["auth"] WH["webhook"] AG["agent / session"] end subgraph Stores["30 File Stores · internal/persis/"] FDR["filedagrun\n~1,400 lines"] FQ["filequeue\nremoved"] FP["fileproc\n~300 lines"] FD["filedistributed\n~600 lines"] FU["fileuser\n~250 lines"] FS["filesecret\n~200 lines"] FW["filewebhook\n~150 lines"] FA["fileaudit\n~200 lines"] FK["fileapikey\n~200 lines"] FSS["filesession\n~650 lines"] FEV["fileeventstore\n~300 lines"] FM["... 19 more stores"] end subgraph FS2["Filesystem"] F[("📂 File System")] end RT --> FDR SC --> FQ & FP CO --> FD AU --> FU & FS & FK WH --> FW AG --> FSS & FA & FEV FDR & FQ & FP & FD & FU & FS & FW & FA & FK & FSS & FEV & FM --> F style App fill:#f0f9ff,stroke:#bae6fd style Stores fill:#fef2f2,stroke:#fecaca style FS2 fill:#f9fafb,stroke:#e5e7eb

Shallow modules

Each store's interface is almost as complex as its implementation — mostly file I/O boilerplate wrapping JSON marshal/unmarshal.

No backend seam

To add PostgreSQL you must rewrite all 30 stores independently. There is no single interface to implement.

Duplicated I/O logic

Atomic writes, directory scanning, prefix filtering, cursor pagination, and file locking are reimplemented in every package.

DELETION TEST

Delete the file I/O logic inside any single store (e.g. filedagrun) — the complexity (directory creation, atomic rename, JSON parse, prefix scan) does not vanish; it moves to a shared FileBackend where it belongs once. This is the seam we are making real.

Backend Abstraction Layer

STRONG

The primary refactoring — the seam that makes every other backend possible

FILES INVOLVED

internal/persis/backend.go (new) internal/persis/file/backend.go (new) internal/persis/file*/store.go → internal/persis/*/store.go internal/cmd/context.go (wiring)

Problem

Every store package independently manages file I/O. There is no common interface that separates what to store (domain logic) from how to store it (file system). A caller wanting to use PostgreSQL instead has no single abstraction to implement — they must rewrite 30 packages. The interface of each file store is nearly as complex as its implementation, violating Deep Module.

internal/persis/backend.go — THE SEAM (Collection: 8 methods, Backend: 2 methods)

// Package persis defines the storage backend interface for Dagu's control plane.
package persis

import (
    "context"
    "errors"
    "time"
)

// Encoding identifies the serialization format of Record.Data.
type Encoding string

const (
    EncodingJSON  Encoding = "json"
    EncodingProto Encoding = "proto3" // reserved; not yet supported
)

// Record is the universal storage primitive for all control-plane data.
// Every store (runs, users, secrets, queues, etc.) persists as Records.
// Domain model changes never require schema changes — they live inside Data.
type Record struct {
    // ID uniquely identifies this record within its collection.
    // Use "/" as a separator for hierarchical IDs.
    // Example: "mydag/run-abc/attempt-0"
    ID        string

    Data      []byte    // opaque serialized payload (JSON only; proto3 reserved, not yet supported)
    Encoding  Encoding // describes Data's format

    CreatedAt time.Time
    UpdatedAt time.Time

    // ExpiresAt, when non-nil, hints that this record may be deleted after
    // this time. Used for heartbeat / lease / TTL records.
    ExpiresAt *time.Time
}

// ListQuery controls what List returns.
type ListQuery struct {
    Prefix string     // only records whose ID starts with this value
    Since  *time.Time // CreatedAt >= Since
    Until  *time.Time // CreatedAt < Until
    Cursor string     // opaque token from a prior Page.NextCursor
    Limit  int        // 0 = backend default
}

// Page is the result of a List call.
type Page struct {
    Records    []*Record
    NextCursor string // empty = no more records exist
}

// Collection is a named, isolated namespace of Records.
// Implementations must be safe for concurrent use.
type Collection interface {
    // Get returns the record identified by id, or ErrNotFound.
    Get(ctx context.Context, id string) (*Record, error)

    // Put creates or replaces a record.
    Put(ctx context.Context, rec *Record) error

    // Create atomically inserts rec, returning ErrConflict when the
    // record already exists. Used for backend-neutral "must not exist"
    // semantics — the create-if-absent half of optimistic concurrency.
    Create(ctx context.Context, rec *Record) error

    // Delete removes the record with the given id.
    // Returns nil if the record does not exist.
    Delete(ctx context.Context, id string) error

    // CompareAndDelete atomically removes expected.ID only when the
    // current record still matches expected. ErrConflict on mismatch.
    CompareAndDelete(ctx context.Context, expected *Record) error

    // List returns a page of records ordered by CreatedAt ascending.
    List(ctx context.Context, q ListQuery) (*Page, error)

    // CompareAndSwap atomically updates record id only when its current Data
    // equals expected. Returns ErrConflict when it does not match.
    // Used for optimistic concurrency on DAGRunStatus.
    CompareAndSwap(ctx context.Context, id string, expected, next []byte) error

    // Claim atomically removes one record matching q and returns it.
    // Used by queue adapters for atomic dequeue.
    // Returns ErrNotFound when no matching record exists.
    Claim(ctx context.Context, q ListQuery) (*Record, error)
}

// Backend is the sole interface a new database driver must implement.
// It creates named Collections and manages lifecycle.
type Backend interface {
    // Collection returns the collection with the given name.
    // Collections are created lazily; the name becomes the logical table.
    Collection(name string) Collection

    // Close releases all backend resources (connections, file handles, etc.).
    Close() error
}

// Sentinel errors returned by Collection methods.
var (
    ErrNotFound = errors.New("persis: record not found")
    ErrConflict = errors.New("persis: compare-and-swap conflict")
)

Before → After

Before

Application (runtime, scheduler, auth…)
filedagrun
1,400 ln
filequeue
removed
fileproc
300 ln
fileuser
250 ln
filesecret
200 ln
filewebhook
150 ln
fileaudit
200 ln
filesession
650 ln
+22 more…
↓
↓
↓
↓
↓
↓
↓
↓
↓
📂 File System

Add PostgreSQL → rewrite all 30 stores

After

Application (runtime, scheduler, auth…)
↓ same domain interfaces
dagrun/
~60 ln
queue/
~70 ln
proc/
~50 ln
user/
~60 ln
secret/
~70 ln
webhook/
~50 ln
↓ all call

THE SEAM

persis.Backend interface

Collection(name) · Close()

↓ implemented by
file/
~400 ln
sql/
future
etcd/
future

Add PostgreSQL → Backend + Collection for collection-backed stores; separate lock and DAGRunStore work remains

What a Store Adapter Looks Like

The domain store interface (exec.DAGRunStore) is unchanged. Only the implementation becomes a thin JSON adapter over persis.Collection.

BEFORE — internal/persis/filedagrun/store.go (excerpt)

func (s *Store) LatestAttempt(
  ctx context.Context, name string,
) (exec.DAGRunAttempt, error) {
  // navigate directory tree...
  root := s.dagRunRootDir(name)
  dirs, err := os.ReadDir(root)
  if err != nil { ... }
  // sort, find latest, open file...
  for _, d := range dirs {
    aDir := filepath.Join(root, d.Name(), "attempt")
    files, _ := os.ReadDir(aDir)
    // parse filenames, check timestamps...
    for _, f := range files {
      data, _ := os.ReadFile(
        filepath.Join(aDir, f.Name()),
      )
      // unmarshal JSONL, pick last line...
    }
  }
  // ... 40 more lines of file wrangling
}

AFTER — internal/persis/dagrun/store.go (same method)

type Store struct {
  col persis.Collection // "dag_runs"
}

func (s *Store) LatestAttempt(
  ctx context.Context, name string,
) (exec.DAGRunAttempt, error) {
  page, err := s.col.List(ctx, persis.ListQuery{
    Prefix: name + "/",
    Limit:  1,
  })
  if err != nil { return nil, err }
  if len(page.Records) == 0 {
    return nil, exec.ErrDAGRunIDNotFound
  }
  var status exec.DAGRunStatus
  json.Unmarshal(page.Records[0].Data, &status)
  return &attempt{status: status}, nil
}

// Testable with any mock Collection.
// Zero file-system dependencies.

How FileBackend Implements Backend

The file.Backend consolidates all existing file I/O patterns from the 30 store packages into a single implementation. The data layout is preserved — this is a non-destructive refactoring.

Directory layout (unchanged on disk)

{dataDir}/ ├── dag_runs/ │ └── {dagName}/ │ └── {runID}/ │ └── {attemptID}.json ├── queue_items/ │ └── {queueName}/ │ └── high_{uuid}.json ├── proc_entries/ │ └── {group}/{name}.json ├── users/ │ └── {userId}.json ├── secrets/ │ └── {workspace}/{name}.json ├── webhooks/ │ └── {webhookId}.json └── ... other collections

Future SQL backend schema (entire schema)

CREATE TABLE records ( collection TEXT NOT NULL, id TEXT NOT NULL, data BYTEA NOT NULL, encoding TEXT NOT NULL DEFAULT 'json', created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL, expires_at TIMESTAMPTZ, PRIMARY KEY (collection, id) ); CREATE INDEX idx_records_time ON records (collection, created_at); CREATE INDEX idx_records_expires ON records (expires_at) WHERE expires_at IS NOT NULL; -- That's it. No per-domain columns ever. -- Domain changes live inside data BYTEA.

Collection(name) → directory

Each collection is a subdirectory. Collection("dag_runs") opens/creates {dataDir}/dag_runs/.

ID "/" → path separator

id = "mydag/run-1/att-0" maps to dag_runs/mydag/run-1/att-0.json. Prefix queries become directory scans.

Claim → file lock + rename

Atomic dequeue: lock directory, pick first matching file, read + delete atomically. SQL equivalent: SELECT FOR UPDATE SKIP LOCKED.

Benefits: Leverage and Locality

⬆

Leverage

9 methods unlock every collection-backed control-plane store including the distributed ones — they now run on CompareAndSwap + Create alone. Adding a new database still requires a backend-specific exec.DAGRunStore.

🎯

Locality

All file I/O complexity lives in one place (file/backend.go). Bugs in directory scanning, atomic writes, or cursor pagination are fixed once.

🧪

Testability

Domain store adapters become pure Go — no filesystem fixtures needed. Test with an in-memory Collection mock. Backend gets its own integration tests.

🔒

Schema stability

Collection-backed SQL records can keep a stable envelope as fields evolve. DAG-run remains a separate backend-specific store, so it is not covered by this generic schema claim.

🔀

Incremental migration

Port one store at a time. File layout on disk is unchanged. Run old and new implementations side-by-side during migration.

🏗️

Simpler wiring

One backend := file.New(dir) call replaces 30+ individual store constructor calls in cmd/context.go.

Codec / Serialization Layer

WORTH EXPLORING

Secondary refactoring — complements Candidate 1 but not required for it

Problem

Every store adapter will call json.Marshal/Unmarshal directly. This duplicates encoding error handling, makes it hard to add proto3 support later, and provides no hook for schema versioning.

Solution

A thin persis/codec.go with two generic helpers:

// Encode marshals v to JSON, returning the bytes and encoding.
func Encode(v any) ([]byte, Encoding, error)

// Decode unmarshals rec.Data into *v using rec.Encoding.
func Decode[T any](rec *Record, v *T) error

Benefits

  • → One place to change encoding later (currently JSON-only; file backend rejects non-JSON)
  • → One place to add a version field for future migrations
  • → Store adapters become 2-line encode/decode calls
  • → Codec is tested in isolation, independently of backend

Recommendation: implement this alongside Candidate 1 — the marginal cost is ~50 lines and it prevents scattered json.Marshal calls from proliferating across 30 adapters.

Proposed Package Structure

What moves where

BEFORE — internal/persis/

internal/persis/
filedag/ (dag YAML — not changing)
filedagrun/ 1,400 ln impl
filequeue/ removed after queue port
fileproc/ 300 ln impl
filedistributed/ 600 ln impl
fileuser/ 250 ln impl
filesecret/ 200 ln impl
filewebhook/ 150 ln impl
fileaudit/ 200 ln impl
fileapikey/ 200 ln impl
filesession/ 650 ln impl
fileeventstore/ 300 ln impl
filememory/ impl
fileserviceregistry/ impl
filenotification/ 937 ln impl
filewatermark/ impl
filebaseconfig/ impl
fileagent*/ 4× impl
file*/ ... 12 more
legacy/
testutil/

AFTER — internal/persis/

internal/persis/
backend.go ← Backend, Collection, Record
codec.go ← Encode, Decode[T]
errors.go ← ErrNotFound, ErrConflict
── adapters (thin, pure Go) ──
store/ ── ported adapters (persis/store/) ──
✅ apikey.go 254 ln
✅ secret.go 453 ln
◐ session.go 528 ln · ported, unwired; awaits non-file backend (prod uses filesession)
✅ user.go 303 ln
✅ webhook.go 319 ln
✅ license.go 76 ln · filelicense removed; on-disk format byte-identical to pre-refactor activation.json
✅ upgradecheck.go 62 ln · fileupgradecheck removed; single-record cache at upgrade-check.json, layout preserved
✅ githubdispatch.go filegithubdispatch removed; single tracked.json map preserved
✅ workspace.go fileworkspace removed; per-workspace JSON, byName index rebuilt on startup
✅ agentconfig.go fileagentconfig removed; single config.json, env override preserved
✅ agentmodel.go fileagentmodel removed; per-model JSON, byName index rebuilt
✅ agentoauth.go fileagentoauth removed; per-provider encrypted credential, RFC3339Nano timestamps preserved
✅ remotenode.go fileremotenode removed; per-node JSON with encrypted credentials, byName index rebuilt
✅ watermark.go 122 ln · lives in persis/schedulerstore/, not store/
✅ workerheartbeat.go 168 ln
✅ queue*.go collection-backed QueueStore; filequeue removed
◐ proc*.go collection-backed ProcStore · unwired in production (file backend uses file/proc); for future non-file backends/tests
✅ distributed*.go collection-backed records; CAS-only optimistic concurrency — no file-lock dependency
── backend implementations ──
✅ file/ FileBackend 480 ln (backend.go 50 + collection.go 430)
backend.go
collection.go
✅ dag_store.go file-backed DAGStore wiring boundary
✅ agent_stores.go file-backed agent store wiring boundary
✅ service_stores.go file-backed service/CLI store wiring boundary
✅ dagrun/ DAG-run file layout compatibility implementation
✅ proc/ file-backed ProcStore preserving released .proc paths and payloads
sql/ future Backend + collection adapters; separate DAGRunStore required
etcd/ future
legacy/ unchanged
✅ testutil/ memory.go 217 ln — in-memory Backend for unit tests
filedag/ ← untouched leaf implementation; composition roots use file.NewDAGStore, app/engine code receives exec.DAGStore
◐ file*/ ← ~9 leaf packages still in use (audit, eventstore, notification, session, serviceregistry, baseconfig, incident, agentsoul, memory), each wrapped by a file/ boundary; ported incrementally, not yet behind Backend

Wiring Change in cmd/context.go

BEFORE — 30+ separate constructors

// context.go — NewContext()
drs := filedagrun.New(cfg.Paths.DAGRunsDir, ...)
// queue had its own file-backed constructor here; that package is now removed
ps  := fileproc.New(cfg.Paths.ProcDir, ...)
sm  := fileserviceregistry.New(cfg.Paths.ServiceRegistryDir)
dls := filedistributed.NewDAGRunLeaseStore(...)
ads := filedistributed.NewActiveDistributedRunStore(...)
dts := filedistributed.NewDispatchTaskStore(...)
whs := filedistributed.NewWorkerHeartbeatStore(...)
us  := fileuser.New(cfg.Paths.UsersDir, ...)
ss  := filesecret.New(cfg.Paths.SecretsDir, ...)
// ... 20+ more lines like this

AFTER — current branch wiring

// context.go — NewContext()
drs := file.NewDAGRunStore(cfg, ...)
ds  := file.NewDAGStore(cfg, ...)
qs  := store.NewQueueStore(file.NewCollection(cfg.Paths.QueueDir))
ps  := file.NewProcStore(cfg)
sr  := file.NewServiceRegistry(cfg)
leaseCollection := file.NewCollectionWithLockRoot(filepath.Join(distributedDir, "leases"), distributedDir)
activeRunCollection := file.NewCollectionWithLockRoot(filepath.Join(distributedDir, "active-runs"), distributedDir)
dls := store.NewDAGRunLeaseStore(leaseCollection)
ads := store.NewActiveDistributedRunStore(activeRunCollection)
dts := store.NewDispatchTaskStore(file.NewCollection(distributedDir))
us  := store.NewUserStore(file.NewCollection(cfg.Paths.UsersDir), ...)
ss  := store.NewSecretStore(file.NewCollection(cfg.Paths.SecretsDir), encryptor)
// DAG-run, DAG definition, proc, and service-registry wiring should go through the file backend boundary instead of leaf file packages.
// Agent config/model/soul/memory/OAuth/session wiring follows the same file boundary for CLI, server, worker, and snapshots.
// Service stores such as audit, event, notification, incident, workspace, license, token secret, and upgrade cache also go through the same file boundary.
// frontend.NewServer receives backend-neutral StoreFactories; cmd/process supplies the file-backed factory bundle.

Collection Naming & ID Conventions

Collections map to directories (FileBackend) or rows in a single records table (SQL). IDs use / as a hierarchy separator — prefix queries support tree traversal.

Collection Domain ID Format Notes
dag_runs DAGRunStore {dagName}/{runID}/{attemptID} Prefix by dagName or dagName/runID for scoped queries. CAS used for status updates.
queue_items QueueStore {queueName}/{high|low}_{uuid} Priority encoded in ID sort order. Claim = atomic dequeue.
proc_entries ProcStore (collection backend only) {group}/{procName} Not used by the file backend. File-backed proc uses internal/persis/file/proc and keeps the released .proc layout.
dispatch_tasks DispatchTaskStore {taskID} Claim for atomic worker assignment.
worker_heartbeats WorkerHeartbeatStore {workerID} ExpiresAt for stale-worker detection.
dag_run_leases DAGRunLeaseStore {queueName}/{attemptKey} ExpiresAt for lease expiry.
active_runs ActiveDistributedRunStore {dagName}/{runID} Coordinator's index of live runs.
users UserStore {userID} Username lookup via in-memory index rebuilt on List.
secrets SecretStore {workspace}/{secretName} Adapter encrypts Data before Put, decrypts after Get.
api_keys APIKeyStore {keyID} Simple CRUD.
webhooks WebhookStore {webhookID} DAG-name lookup via prefix or in-memory index.
audit_log AuditStore {YYYY-MM-DD}/{uuid} Append-only. Since/Until on ListQuery for time-range queries.
events EventStore {YYYY-MM-DDHH}/{eventID} Committed vs inbox via ID prefix convention.
sessions SessionStore {userID}/{sessionID} Prefix by userID for user-scoped listing.
agent_memory MemoryStore global or dag/{dagName} Plain text blob in Data (EncodingJSON = "raw").
service_registry ServiceRegistry {serviceName}/{instanceID} ExpiresAt for stale instance detection.
notifications NotificationStore {notificationID} Adapter handles per-field encryption.
base_config BaseConfigStore config Single-record collections. Get("config") / Put.
What does NOT move to Backend: DAG YAML definition files (filedag/, behind file.NewDAGStore), step execution logs, artifact outputs, and any user-managed files remain on disk as-is. The Backend only owns control-plane metadata — the records that describe what runs, not the artifacts of running.

Migration Strategy

Incremental, non-destructive — one store at a time

✅ File layout compatibility preserved ◐ Backend-neutral gaps remain
graph LR A["✅ Step 1\nDefine interfaces\npersis/backend.go\npersis/codec.go\npersis/errors.go"] --> B["✅ Step 2\nFileBackend\npersis/file/\nbackend.go + collection.go\n480 ln total"] --> C["✅ Step 3\nPort stores\napikey, webhook, user\nsecret, session\nwatermark, workerheartbeat"] --> D["✅ Step 4\nComplex stores\nqueue ✅\nproc ✅\ndistributed CAS ✅"] --> E["✅ Step 5\nMove dagrun file store\npreserve exact layout"] --> F["⏳ Step 6\nBackend-neutral locks\nSQL backend\nbackend-specific DAGRunStore"] --> G["✅ Step 7\nMemoryBackend\npersis/testutil/\nmemory.go 217 ln"] style A fill:#dcfce7,stroke:#16a34a style B fill:#dcfce7,stroke:#16a34a style C fill:#dcfce7,stroke:#16a34a style D fill:#dcfce7,stroke:#16a34a style E fill:#dcfce7,stroke:#16a34a style F fill:#fef9c3,stroke:#ca8a04 style G fill:#dcfce7,stroke:#16a34a

Why this is safe

  • • FileBackend maps collection IDs to the same directory layout for collection-backed stores. No data migration.
  • • DAG-run is a strict compatibility refactor: physical paths, sidecar files, status log shape, indexes, and lock behavior must not change.
  • • Removing filedagrun means removing the legacy package/API, not moving file-layout code into the DB-neutral store package.
  • • API, worker, and engine code must depend on persistence interfaces/factories such as exec.DAGRunStore; only composition wiring and tests should import file backend implementations such as internal/persis/file/dagrun.
  • • Old and new code can run together during porting (different stores).
  • • Each store port is independently testable and reviewable.
  • • File format (JSON) unchanged — existing file-backed data remains readable immediately.

How to add PostgreSQL later

  • • Create persis/sql/backend.go implementing Backend + Collection.
  • • Single records table schema can support the collection-backed stores.
  • • Distributed stores still need backend-neutral lock/claim semantics before they are portable beyond the file backend.
  • • DAG-run needs a backend-specific exec.DAGRunStore implementation; do not force its file-layout mechanics into persis/store.

Status — current refactor branch as of May 27, 2026

Phase 1 Complete · Phase 2 Compatibility Refactor In Progress

The seam exists. persis.Backend and persis.Collection are live. Queue and proc use collection-backed stores. Distributed records are collection-backed but still depend on file-backend lock behavior. DAG-run is moved from filedagrun to internal/persis/file/dagrun as a file-backed exec.DAGRunStore; its physical paths and JSON shape remain unchanged.

Interface surface

10

Collection 8 + Backend 2 (Create added)

Stores ported

18+

collection-backed adapters plus file-backed DAG-run compatibility

Neutrality gaps

1

backend-specific DAGRunStore (distributed CAS done)

Backend surface

480

shared collection backend; DAG-run file layout remains in file/dagrun

✅ Done / preserved

  1. ✓ persis/backend.go — Backend, Collection, Record, ListQuery, Page
  2. ✓ persis/codec.go — Encode(v any) ([]byte, Encoding, error), Decode[T]
  3. ✓ persis/errors.go — ErrNotFound, ErrConflict
  4. ✓ persis/file/ — FileBackend + FileCollection (480 ln)
  5. ✓ persis/testutil/memory.go — MemoryBackend (217 ln)
  6. ✓ persis/store/ — collection-backed adapters with tests; proc remains collection-only and is not wired to the file backend
  7. ✓ internal/persis/filequeue — removed after queue wiring moved to store.NewQueueStore(file.NewCollection(cfg.Paths.QueueDir))
  8. ✓ internal/persis/filelicense — removed; replaced in file.NewLicenseStore(cfg) (pre-creates license dir at 0o700, then uses store.NewLicenseStore(NewCollection(dir, WithIndentedJSON()))) with byte-identical on-disk format
  9. ✓ internal/persis/fileupgradecheck — removed; replaced in file.NewUpgradeCheckStore(cfg) (creates {DataDir}/upgrade/ at 0o750, then uses store.NewUpgradeCheckStore(NewCollection(dir, WithIndentedJSON()))); invalid-JSON quirk preserved (returns nil cache, no error)
  10. ✓ internal/persis/file/dagrun — file-backed DAG-run store with exact existing file-layout compatibility
  11. ✓ DAG-run wiring goes through file.NewDAGRunStore and service code depends on exec.DAGRunStore
  12. ✓ internal/persis/file/proc — file-backed ProcStore keeps released .proc paths and payloads; no collection JSON is written under the proc directory

⏳ Next — Phase 2

  1. ✓ Replace distributed stores' file-lock dependency with backend-neutral lock/claim semantics. Lease/active/dispatch now use CompareAndSwap + a new Collection.Create primitive; persis/store/ no longer imports dirlock.
  2. 5. Keep DAG-run behind exec.DAGRunStore; add a backend-specific SQL implementation when DBMS support is added.
  3. 6. Continue deleting old file*/ packages only when their file-layout compatibility has a clear replacement.
  4. 7. Unify wiring where it is honest to do so; do not hide file-specific behavior inside persis/store.