Skip to content

feat(storage): define and implement the Session Bundle filesystem codec #1528

Closed

Description

@MicroGery

Parent RFC: #1286

Depends on:

Related:

Summary

Define and implement the V1 filesystem codec for portable Maka Session Bundles.

The codec consumes an already prepared, quiescent snapshot containing a single-Session state/ tree, a prepared workspace/ tree, and an opaque state-identity descriptor produced by the state-export layer. It produces and consumes a deterministic, versioned tar.zst archive.

The filesystem codec owns:

  • bundle layout and manifest encoding;
  • deterministic archive generation;
  • canonical payload tree digests;
  • full-archive transport digests;
  • streaming validation and quota enforcement;
  • safe extraction;
  • crash-safe hydration into a fresh Session root.

It does not understand Maka's internal Session, SQLite, JSONL, runtime-event, artifact, or workspace schemas.

Motivation

A Cloud Session must be portable across fresh ephemeral sandboxes:

prepared state + workspace snapshot
                │
                ▼
      Session Bundle filesystem codec
                │
                ▼
       session-bundle.tar.zst
                │
                ▼
       SessionRepository / transport
                │
                ▼
       fresh Session root hydration

The format must be safe to consume as untrusted input, deterministic under a fixed codec version and settings, and independent of the storage backend, OpenSandbox, and Activation orchestration.

This issue is the filesystem-facing portion of Work Item 3 in #1286.

Responsibility boundary

Input precondition

The codec accepts a prepared, quiescent snapshot:

interface PreparedSessionBundleSnapshot {
  stateRoot: string;
  workspaceRoot: string;
  stateIdentity: OpaqueStateIdentityDescriptor;
}

interface OpaqueStateIdentityDescriptor {
  mediaType: string;
  bytes: Uint8Array;
}

The producer guarantees that:

  • stateRoot contains exactly one exported Maka Session;
  • state and workspace represent one consistent logical snapshot;
  • SQLite and any other mutable stores are safe to copy;
  • the roots do not change while pack is running;
  • credentials, host configuration, temporary activation inputs, and logs have already been excluded;
  • the state-identity descriptor is semantically valid for the prepared state.

Cross-store snapshot coordination remains a separate follow-up. This codec does not read directly from live SQLite or a workspace that is still being modified.

Filesystem codec responsibility

The codec owns only:

prepared snapshot
    ↕
versioned manifest + deterministic tar.zst
    ↕
validated fresh Session root

It may integrity-check the opaque identity descriptor as bytes, but it must not:

  • import SessionHeader or other Maka state schemas;
  • inspect or rewrite Maka SQLite rows;
  • parse Session JSONL or runtime events;
  • infer makaSessionId from directory names;
  • perform semantic state migration or re-keying.

Proposed API

type Sha256Digest = `sha256:${string}`;

interface SessionBundleSource {
  path: string;

  /**
   * Optional for standalone/local inspection.
   * Required when the source comes from SessionRepository.
   */
  expectedArchiveDigest?: Sha256Digest;
}

interface SessionBundleLimits {
  maxCompressedBytes: number;
  maxDecompressedTarBytes: number;
  maxPayloadBytes: number;
  maxFileBytes: number;
  maxEntryCount: number;
  maxManifestBytes: number;
  maxStateIdentityBytes: number;
  maxPathBytes: number;
  maxPathDepth: number;
}

interface SessionBundleEnvelopeInput {
  /**
   * Cloud Session binding allocated by the control plane.
   */
  sessionId: string;

  /**
   * Provenance only. This is not the activation-deduplication authority.
   */
  lastCommittedActivationId?: string;
}

interface SessionBundlePackInput {
  snapshot: PreparedSessionBundleSnapshot;
  envelope: SessionBundleEnvelopeInput;
  destination: string;
  limits: SessionBundleLimits;
}

interface SessionBundleReadInput {
  source: SessionBundleSource;
  limits: SessionBundleLimits;
}

interface SessionBundleHydrateInput extends SessionBundleReadInput {
  expectedSessionId: string;
  destinationRoot: string;
}

interface SessionBundleHydrationCleanupInput {
  destinationRoot: string;
}

interface SessionBundleArtifact {
  path: string;
  archiveDigest: Sha256Digest;
  compressedBytes: number;
  decompressedTarBytes: number;
  payloadBytes: number;
  entryCount: number;
}

interface SessionBundleInspection {
  manifest: SessionBundleManifestV1;
  stateIdentity: OpaqueStateIdentityDescriptor;
  archiveDigest: Sha256Digest;
  verified: true;
}

interface SessionBundleHydration extends SessionBundleInspection {
  destinationRoot: string;
  stateRoot: string;
  workspaceRoot: string;
}

interface SessionBundleHydrationCleanupResult {
  destinationRoot: string;
  removedStagingDirectories: number;
  removedOwnershipRecords: number;
}

interface SessionBundleFileService {
  pack(input: SessionBundlePackInput): Promise<SessionBundleArtifact>;
  inspect(input: SessionBundleReadInput): Promise<SessionBundleInspection>;
  hydrate(input: SessionBundleHydrateInput): Promise<SessionBundleHydration>;
  cleanupHydrationStaging(
    input: SessionBundleHydrationCleanupInput,
  ): Promise<SessionBundleHydrationCleanupResult>;
}

The limits object is required: validation must never run with implicit unlimited extraction.

V1 physical layout

manifest.json
state-identity.json
state/
workspace/

After successful hydration:

<destinationRoot>/
├── state-identity.json
├── state/
└── workspace/

state-identity.json is produced and semantically validated by the state-export/import layer. The filesystem codec treats its contents as opaque bytes.

V1 manifest

interface SessionBundleManifestV1 {
  schemaVersion: 1;

  codec: {
    name: "maka-session-bundle";
    version: 1;
    canonicalizationVersion: 1;
    archive: "ustar";
    compression: "zstd";
    compressionLevel: 3;
  };

  envelope: {
    sessionId: string;
    lastCommittedActivationId?: string;
  };

  stateIdentity: {
    path: "state-identity.json";
    mediaType: string;
  };

  payload: {
    statePath: "state/";
    workspacePath: "workspace/";
    treeDigest: Sha256Digest;
    payloadBytes: number;
    entryCount: number;
  };
}

manifest.json is encoded as canonical JSON using RFC 8785/JCS UTF-8 bytes, with no BOM or trailing newline.

The manifest does not contain:

  • Repository revision or head;
  • forkedFrom;
  • activation dedupe records or terminal outcomes;
  • leases or sandbox identities;
  • scheduler registrations;
  • credentials or connection configuration;
  • temporary activation inputs or logs.

Authority rules

Cloud sessionId

The control plane/SessionRepository allocates the Cloud sessionId and remains authoritative.

The manifest envelope carries it as a required binding. hydrate compares it with expectedSessionId and fails with identity_mismatch on any mismatch. It must not silently rebind the bundle.

Maka state identity

The state-export/import layer owns the semantics of makaSessionId.

It produces a minimal, versioned state-identity.json, validates that descriptor against the Maka state during export/import, and performs any required semantic re-keying.

The filesystem codec:

  • does not parse the descriptor;
  • includes its exact bytes in the canonical payload tree;
  • returns its exact bytes and media type from inspect and hydrate;
  • detects any byte-level change through the payload tree digest and, when supplied, the transport digest.

Activation metadata

lastCommittedActivationId is optional provenance identifying the Activation that produced a committed bundle.

It is not authoritative for deduplication or terminal outcomes. Those remain in the control plane's Activation store.

A newly forked target clears lastCommittedActivationId, because its initial revision was produced by a fork operation rather than by an Activation in the target Session.

Repository revision/head

Revision and head remain exclusively in SessionRepository metadata and are never embedded in the bundle.

Fork lineage

forkedFrom: { sessionId, revision } remains authoritative only in control-plane Session metadata, as defined by #1415. It is not duplicated in the V1 bundle manifest.

Canonical payload tree digest

The manifest carries:

payload.treeDigest = SHA-256(canonical payload tree record stream)

The canonical tree contains:

state-identity.json
state/
state/**
workspace/
workspace/**

It excludes manifest.json to avoid self-reference.

Entry paths

V1 paths:

  • are valid UTF-8;
  • are relative;
  • use / as the only separator;
  • reject NUL, backslash, absolute paths, drive prefixes, ., and ..;
  • preserve their UTF-8 bytes without Unicode normalization or rewriting;
  • use a host-independent portable segment subset: ASCII controls, < > : " | ? *, trailing dots/spaces, and case-insensitive Windows device names such as CON, NUL, COM1, and LPT1 are rejected even on POSIX;
  • are ordered lexicographically by their raw UTF-8 bytes;
  • reject duplicate paths and file/directory parent conflicts;
  • end in / for directories and never end in / for regular files.

Both root directories and all empty directories participate in the digest.

Normalized metadata

V1 normalizes:

  • directories to mode 0755;
  • regular files to 0644 or 0755, preserving only executable/non-executable semantics;
  • timestamp/mtime to zero;
  • uid/gid to zero;
  • uname/gname to empty strings.

V1 does not preserve xattrs, ACLs, ownership, platform-specific metadata, symlinks, or hardlinks.

Exact tree-record encoding

The canonical byte stream is:

ASCII("MAKA_SESSION_BUNDLE_TREE") + 0x00
uint32be(canonicalizationVersion = 1)
uint64be(entryCount)

for each entry in raw-UTF-8 path order:
  uint8(entryType)
    0x01 = directory
    0x02 = regular file

  uint32be(pathByteLength)
  path UTF-8 bytes

  uint16be(normalizedMode)
  uint64be(contentByteLength)
  32 raw digest bytes

For a directory:

normalizedMode    = 0755
contentByteLength = 0
digest            = 32 zero bytes

For a regular file:

normalizedMode    = 0644 or 0755
contentByteLength = exact file byte length
digest            = raw 32-byte SHA-256(file contents)

The final tree digest is the raw SHA-256 of this complete canonical byte stream, represented in the manifest as lowercase:

sha256:<64 lowercase hexadecimal characters>

Golden contract fixtures must pin the exact bytes and expected digest.

Deterministic USTAR encoding

V1 uses POSIX USTAR without PAX or GNU extensions.

Archive entry order is:

  1. manifest.json;
  2. all canonical payload entries in raw UTF-8 path order.

USTAR fields are normalized as follows:

  • mode: canonical mode described above;
  • uid and gid: zero;
  • size: exact payload size;
  • mtime: zero;
  • typeflag: regular file or directory only;
  • uname and gname: empty;
  • devmajor and devminor: zero;
  • checksum: standard USTAR checksum;
  • exactly two zero blocks terminate the archive.

For paths longer than the USTAR name field, the encoder uses the rightmost / split for which:

prefix <= 155 bytes
name   <= 100 bytes

A path not representable by the V1 USTAR contract is rejected with unsafe_path.

The writer and reader reject PAX headers, GNU extensions, links, sparse files, devices, FIFOs, sockets, and unknown entry types.

Deterministic Zstandard encoding

V1 uses Node 24 native Zstandard with fixed settings:

compressionLevel = 3
checksumFlag     = enabled
contentSizeFlag  = disabled
dictIDFlag       = disabled
workers          = 0
dictionary       = none

Byte-for-byte tar.zst determinism is guaranteed only for fixed:

codec version
canonicalization version
USTAR rules
Zstandard settings
encoder implementation contract

Any intentional change that alters canonical tree bytes or deterministic archive bytes requires an appropriate codec or canonicalization version change and updated golden fixtures.

Transport digest

The full-archive transport digest is separate from the payload tree digest:

archiveDigest = SHA-256(final tar.zst bytes)

It is not stored inside manifest.json, because doing so would create a self-reference.

Pack path

pack:

  1. writes the archive to a sibling temporary file;
  2. computes SHA-256 over the exact compressed bytes while writing;
  3. closes and validates the output;
  4. atomically renames the temporary file to destination;
  5. returns the computed archiveDigest.

Repository path

SessionRepository stores the returned digest as trusted revision/blob metadata alongside the bundle reference.

Inspect/hydrate path

inspect and hydrate:

  1. open the source once per operation;
  2. compute SHA-256 over the compressed bytes actually consumed;
  3. complete decompression, structural validation, quota enforcement, and payload-tree verification;
  4. compare the computed digest with expectedArchiveDigest, when supplied;
  5. fail with integrity_mismatch on any mismatch.

hydrate must delete staging and publish nothing when transport-digest verification fails.

A standalone Bundle without an externally trusted expected digest can still use its internal tree digest to detect accidental corruption, but the tree digest alone does not authenticate against an attacker able to replace both payload and manifest.

Shared streaming validator

inspect and hydrate are two sinks over one internal streaming validator:

readAndValidateSessionBundle({
  source,
  limits,
  sink,
});

Conceptually:

source file descriptor
        │
        ├── compressed-byte limit
        ├── archive SHA-256
        ▼
streaming Zstandard decompressor
        │
        ├── decompressed-tar-byte limit
        ▼
streaming USTAR parser
        │
        ├── manifest validation
        ├── path and entry validation
        ├── declared-size preflight
        ├── actual-byte counters
        ├── per-file and total quotas
        └── canonical tree-digest builder
                │
                ├── inspect: discard payload sink
                └── hydrate: staging filesystem sink

Requirements:

  • inspect consumes and validates the complete archive;
  • inspect does not mean a manifest-only peek;
  • hydrate never trusts an earlier inspect;
  • hydrate independently revalidates the bytes it consumes;
  • tar-declared sizes are checked before allocating/writing;
  • declared sizes are verified against actual consumed bytes;
  • quota checks happen while streaming, not after extraction;
  • no destination is published until all structural, identity-binding, quota, tree-digest, and transport-digest checks succeed.

A future unverified manifest-peek API, if required, must use a different name and return type. It is out of scope here.

Quota enforcement

The validator enforces, while streaming:

  • compressed archive bytes;
  • decompressed tar bytes, including tar framing;
  • total payload bytes;
  • per-file bytes;
  • entry count;
  • manifest bytes;
  • state-identity descriptor bytes;
  • path byte length;
  • path depth.

The codec accepts explicit limits from its caller and never falls back to unlimited extraction.

Candidate cloud budgets from #1336/#1353, including the 32 MiB compressed cap and 256 KiB manifest cap, remain storage-policy inputs rather than hard-coded format invariants until that decision record lands.

Crash-safe hydration publication

V1 hydrates to one common Session root:

/session/
├── state-identity.json
├── state/
└── workspace/

The cloud runtime paths become:

state root:     /session/state
workspace root: /session/workspace

Hydration:

  1. requires destinationRoot not to exist;
  2. creates a uniquely named sibling staging directory under the same parent;
  3. verifies staging and destination are on the same filesystem;
  4. writes only into staging;
  5. closes all output handles;
  6. completes all validation and digest checks;
  7. publishes the complete Session root with one atomic directory rename.

A process crash before rename leaves no destination, only an orphan staging directory. A crash after rename leaves the complete Session root visible.

V1 guarantees process-interruption atomicity. It does not promise host-power-loss durability/fsync semantics inside an ephemeral sandbox; the control plane can rehydrate from the last committed bundle.

Orphan staging cleanup must:

  • be scoped to one exact destination and serialized with that destination's hydrate lifecycle across processes;
  • require a persistent codec ownership record bound to the exact destination and staging name; prefix matching alone does not prove ownership;
  • use an exact codec-owned naming prefix;
  • never follow symlinks;
  • never remove the final destination;
  • only remove entries proven to be codec-created staging directories.

Overwriting or merging an existing Session root is out of scope.

Security rules

V1 rejects:

  • absolute paths;
  • . and .. path segments;
  • NUL and backslash;
  • Windows drive or UNC paths;
  • duplicate or conflicting paths;
  • paths exceeding configured byte/depth limits;
  • symlinks and hardlinks;
  • PAX and GNU extension entries;
  • sparse files;
  • block/character devices;
  • FIFO and sockets;
  • xattr and ACL extension metadata;
  • unknown USTAR entry types;
  • malformed or truncated USTAR headers;
  • invalid USTAR checksums;
  • entries after the canonical archive terminator;
  • manifest, state-identity, and payload layout violations.

No validation failure may publish files outside staging.

Stable error model

type SessionBundleFileErrorCode =
  | "invalid_manifest"
  | "unsupported_schema"
  | "unsupported_codec"
  | "identity_mismatch"
  | "integrity_mismatch"
  | "quota_exceeded"
  | "unsafe_path"
  | "unsupported_entry"
  | "destination_exists"
  | "source_changed"
  | "io_failure";

Error codes remain bounded and stable. Additional context is carried in structured details without exposing unsafe or unbounded attacker-controlled strings.

Fork contract reconciliation

This contract changes one assumption currently written in #1415.

A Cloud Session fork always receives:

  • a new Cloud sessionId;
  • a new makaSessionId;
  • its own first revision and CAS sequence.

The filesystem codec does not re-key Maka state.

The fork/state layer must:

  1. checkout the exact source revision;
  2. hydrate it into private staging;
  3. allocate the target makaSessionId;
  4. call a state-semantic re-key operation that updates all Maka state consistently and emits a new versioned state-identity descriptor;
  5. call pack with the target Cloud sessionId;
  6. clear lastCommittedActivationId;
  7. create the target Session with create-if-absent semantics;
  8. record forkedFrom in control-plane Session metadata.

Therefore fork remains independent of OpenSandbox and maka activate, but it is an orchestration over SessionRepository, the filesystem codec, and a Maka state re-key layer rather than a raw Repository byte-copy operation.

The implementation of fork and state re-keying remains out of scope for this issue. #1415 must be updated to reflect this contract before its implementation begins.

Acceptance criteria

Contract and boundaries

  • Public pack, inspect, hydrate, and cleanupHydrationStaging types are defined.
  • Every archive pack/read operation requires explicit quota limits; cleanup is destination-scoped and ownership-validated.
  • The codec does not import or parse Maka Session, SQLite, JSONL, runtime-event, or artifact schemas.
  • The opaque state-identity descriptor round-trips byte-for-byte.
  • Descriptor semantic validation remains in the state-export/import layer.
  • Cloud sessionId mismatch fails with identity_mismatch.
  • Revision/head and forkedFrom are absent from the V1 manifest.
  • lastCommittedActivationId is documented as optional provenance only.

Canonicalization and integrity

  • Exact canonical tree-record bytes are covered by golden fixtures.
  • Golden fixtures pin the expected SHA-256 tree digest.
  • Empty directories and executable files are covered.
  • Timestamp, uid/gid, uname/gname, and mode normalization are covered.
  • Manifest encoding is canonical and deterministic.
  • Fixed inputs produce byte-identical USTAR output under codec V1.
  • Fixed inputs produce byte-identical tar.zst output under the fixed Node 24 codec settings.
  • pack returns the SHA-256 digest of the final compressed bytes.
  • inspect and hydrate verify the expected transport digest when supplied.
  • A transport-digest mismatch publishes nothing.

Streaming validation and safety

  • inspect and hydrate share one streaming validator.
  • hydrate does not trust a previous inspect.
  • Compressed, decompressed, payload, file, entry, manifest, descriptor, and path quotas are enforced during streaming.
  • Tar-declared sizes are checked before writing and verified against actual consumed bytes.
  • Path traversal, duplicate paths, conflicting paths, links, special entries, extensions, and truncated archives are rejected.
  • Corrupted payload, manifest, descriptor, tree digest, USTAR checksum, Zstandard stream, and archive digest cases are covered.
  • Malicious archive fixtures cannot write outside staging.

Hydration publication

  • Hydration requires an absent destination root.
  • Staging is created as a sibling on the same filesystem.
  • state-identity.json, state/, and workspace/ are published with one atomic rename.
  • Injected failures before publication leave no destination.
  • Successful publication exposes the complete Session root.
  • Orphan staging cleanup cannot remove unrelated paths or follow symlinks.
  • Overwrite and merge behavior are rejected in V1.

Coordination

  • A separate follow-up is linked for cross-store state/ + workspace/ snapshot coordination.
  • feat(cloud): fork Cloud Sessions at committed revisions #1415 is updated to require a new target makaSessionId, state-layer re-keying, and a cleared target lastCommittedActivationId.
  • Round-trip tests cover pack → inspect → hydrate.
  • End-to-end tests cover a fresh destination root and a second independent process.

Implementation split

PR 1 — Contract, canonicalization, and validation primitives

  • public types and errors;
  • Manifest V1 and canonical JSON encoding;
  • opaque state-identity descriptor contract;
  • authority rules;
  • exact canonical tree-record encoder;
  • SHA-256 tree digest;
  • quota types;
  • golden fixtures and contract tests.

PR 2 — Streaming archive implementation and hydration

  • deterministic USTAR writer;
  • Node 24 Zstandard codec;
  • full-archive transport digest;
  • shared streaming validator;
  • pack, inspect, and hydrate;
  • safe extraction;
  • streaming quota enforcement;
  • sibling staging and atomic common-root publication;
  • destination-scoped orphan staging cleanup with persistent ownership records;
  • failure cleanup, security fixtures, round-trip, and filesystem E2E tests.

Out of scope

  • live SQLite snapshotting;
  • runtime quiescence;
  • cross-store snapshot coordination;
  • workspace filtering and secret detection;
  • .git and node_modules materialization policy;
  • SessionRepository/KV/CAS implementation;
  • object-store blob offload and GC;
  • OpenSandbox transfer;
  • maka activate;
  • Activation deduplication and terminal-outcome persistence;
  • Cloud Session fork implementation;
  • Maka state identity re-key implementation;
  • revision retention;
  • Copy-on-Write;
  • pending-approval identity re-keying;
  • overwriting or merging an existing Session;
  • database migration after hydration.

Activity

  1. likun666661 commented on Jul 27, 2026

    @likun666661
    Member

    Reviewed this against the current main state and the related session-export work. The responsibility boundary, authority rules, deterministic codec contract, streaming validation model, and PR split all look solid to me. I don't have any blocking concerns—this looks ready to implement as proposed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions