> ## Documentation Index
> Fetch the complete documentation index at: https://docs.moltzap.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# simulator/ledger

> Typed live and completed simulator ledgers.

# simulator/ledger

*`packages/simulator/src/ledger`*

## Purpose

Typed live and completed simulator ledgers.

## Public surface

### [`CompletedLedgerArtifacts`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/read.ts#L104)

*Interface*

```ts theme={null}
export interface CompletedLedgerArtifacts {
  readonly manifest: string;
  readonly records: string;
  readonly completion: string;
}
```

Complete immutable artifact text retrieved from a profile-owned store.

### [`CompletedRunLedger`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/read.ts#L93)

*Interface*

```ts theme={null}
export interface CompletedRunLedger<Catalog> {
  readonly ref: LedgerRef;
  readonly manifest: LedgerManifest;
  readonly completion: LedgerCompletion;
  readonly records: Stream.Stream<LedgerRecord<Catalog>>;
  readonly events: <Event extends EventClassOf<Catalog>>(
    eventClass: Event,
  ) => Stream.Stream<Schema.Schema.Type<Event>>;
}
```

Fully validated immutable ledger whose streams cannot fail.

### [`EncodedEventOf`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/catalog.ts#L45)

*TypeAlias*

```ts theme={null}
export type EncodedEventOf<Catalog> = Schema.Schema.Encoded<
  CatalogSchemaOf<Catalog>
>;
```

The closed encoded union persisted for a catalog.

### [`EventCatalog`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/catalog.ts#L132)

*Class*

```ts theme={null}
export class EventCatalog<
  SchemaType extends CatalogSchema,
  Classes extends EventClass = EventClass,
> {
  readonly schema: Schema.Schema<
    Schema.Schema.Type<SchemaType>,
    Schema.Schema.Encoded<SchemaType>
  >;
  readonly eventClasses: readonly EventClass[];
  readonly tags: readonly VersionedEventTag[];
  private readonly [eventCatalogTypeId] = eventCatalogTypeId;

  private constructor(schema: SchemaType, eventClasses: readonly EventClass[]) {
    this.schema = Schema.make<
      Schema.Schema.Type<SchemaType>,
      Schema.Schema.Encoded<SchemaType>
    >(schema.ast);
    this.eventClasses = Object.freeze([...eventClasses]);
    this.tags = Object.freeze(
      this.eventClasses.map((eventClass) => eventClass._tag),
    );
    Object.freeze(this);
  }

  static make<
    const EventClasses extends readonly [
      EventClass,
      ...(readonly EventClass[]),
    ],
  >(
    ...eventClasses: EventClasses
  ): EventCatalog<EventClassesSchema<EventClasses>, EventClasses[number]> {
    validateEventClasses(eventClasses);
    return new EventCatalog(makeEventClassesSchema(eventClasses), eventClasses);
  }

  static empty(): EventCatalog<Schema.Schema<never>, never> {
    const eventClasses: readonly never[] = [];
    return new EventCatalog(Schema.make<never>(Schema.Never.ast), eventClasses);
  }

  static merge<
    const Catalogs extends readonly [
      EventCatalog<CatalogSchema>,
      ...ReadonlyArray<EventCatalog<CatalogSchema>>,
    ],
  >(
    ...catalogs: Catalogs
  ): EventCatalog<
    MergedCatalogSchema<Catalogs>,
    CatalogClassesOf<Catalogs[number]>
  > {
    const eventClasses = catalogs.flatMap((catalog) => catalog.eventClasses);
    validateEventClasses(eventClasses);
    return new EventCatalog(mergeCatalogSchemas(catalogs), eventClasses);
  }

  has(eventClass: EventClass): eventClass is Classes {
    return this.eventClasses.some(
      (catalogEventClass) => catalogEventClass === eventClass,
    );
  }

  hasEvent(event: unknown): event is Schema.Schema.Type<SchemaType> {
    if (typeof event !== "object" || event === null) {
      return false;
    }
    const constructor: unknown = Reflect.get(event, "constructor");
    return this.eventClasses.some((eventClass) => eventClass === constructor);
  }

  decode(input: unknown) {
    return Schema.decodeUnknown(Schema.asSchema(this.schema))(input, {
      onExcessProperty: "error",
    });
  }

  encode(event: Schema.Schema.Type<SchemaType>) {
    return Schema.encode(Schema.asSchema(this.schema))(event, {
      onExcessProperty: "error",
    });
  }
}
```

The exact immutable event universe for one definition.

The private type identifier makes catalog arguments nominal: a structural
object cannot claim a schema, constructor list, and tag list that disagree.

### [`EventCatalogDefinitionError`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/catalog.ts#L61)

*Class*

```ts theme={null}
export class EventCatalogDefinitionError extends Schema.TaggedError<EventCatalogDefinitionError>()(
  "EventCatalogDefinitionError",
  {
    failure: Schema.Literal("duplicate-tag", "invalid-tag"),
    tag: Schema.String,
  },
) {
  override get message(): string {
    return definitionFailureMessage[this.failure](this.tag);
  }
}
```

Invalid catalogs fail during definition construction, before a run starts.

### [`EventCatalogDefinitionFailure`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/catalog.ts#L50)

*TypeAlias*

```ts theme={null}
export type EventCatalogDefinitionFailure = "duplicate-tag" | "invalid-tag";
```

Represents event catalog definition failure conditions.

### [`EventClass`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/catalog.ts#L12)

*TypeAlias*

```ts theme={null}
export type EventClass = Schema.Schema.AnyNoContext & {
  readonly _tag: VersionedEventTag;
};
```

A schema-backed event constructor. The catalog retains both the schema and
constructor faces so persisted values decode back into their exact class.

### [`EventClassOf`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/catalog.ts#L42)

*TypeAlias*

```ts theme={null}
export type EventClassOf<Catalog> = CatalogClassesOf<Catalog>;
```

The closed constructor union declared by a catalog.

### [`EventOf`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/catalog.ts#L39)

*TypeAlias*

```ts theme={null}
export type EventOf<Catalog> = Schema.Schema.Type<CatalogSchemaOf<Catalog>>;
```

The closed instance union declared by a catalog.

### [`JsonObject`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/schema.ts#L47)

*TypeAlias*

```ts theme={null}
export type JsonObject = typeof jsonObjectSchema.Type;
```

Represents json object values.

### [`jsonValue`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/schema.ts#L31)

*Variable*

```ts theme={null}
export const jsonValue: Schema.Schema<JsonValue> = Schema.suspend(() =>
  Schema.Union(
    Schema.String,
    Schema.Finite,
    Schema.Boolean,
    Schema.Null,
    Schema.Array(jsonValue),
    Schema.Record({ key: Schema.String, value: jsonValue }),
  ),
).annotations({ identifier: "LedgerJsonValue" })
```

Validates and decodes json value values.

### [`JsonValue`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/schema.ts#L21)

*TypeAlias*

```ts theme={null}
export type JsonValue =
  | string
  | number
  | boolean
  | null
  | readonly JsonValue[]
  | { readonly [key: string]: JsonValue };
```

Represents json value values.

### [`LEDGER_FORMAT_VERSION`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/schema.ts#L12)

*Variable*

```ts theme={null}
export const LEDGER_FORMAT_VERSION = 1
```

Provides the ledger format version runtime value.

### [`LedgerAllocation`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/storage.ts#L73)

*Interface*

```ts theme={null}
export interface LedgerAllocation {
  readonly ref: LedgerRef;
  readonly runId: string;
  readonly manifest: LedgerManifest;
  readonly append: (
    serializedRecord: string,
  ) => Effect.Effect<void, LedgerStorageError>;
  readonly complete: (
    recordCount: number,
  ) => Effect.Effect<LedgerCompletion, LedgerStorageError>;
}
```

One storage-owned live allocation.

### [`LedgerAllocationInput`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/storage.ts#L65)

*Interface*

```ts theme={null}
export interface LedgerAllocationInput {
  readonly definitionId: string;
  readonly catalogTags: readonly VersionedEventTag[];
  readonly provenance: JsonObject;
  readonly metadata: JsonObject;
}
```

Describes ledger allocation input.

### [`LedgerArtifact`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/storage.ts#L20)

*TypeAlias*

```ts theme={null}
export type LedgerArtifact = typeof ledgerArtifactSchema.Type;
```

Represents ledger artifact values.

### [`ledgerArtifactFiles`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/storage.ts#L30)

*Variable*

```ts theme={null}
export const ledgerArtifactFiles =
```

The durable file name each ledger artifact is published under.

### [`LedgerCatalogMismatch`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/read.ts#L60)

*Class*

```ts theme={null}
export class LedgerCatalogMismatch extends Schema.TaggedError<LedgerCatalogMismatch>()(
  "LedgerCatalogMismatch",
  {
    expectedTags: Schema.Array(versionedEventTag),
    actualTags: Schema.Array(versionedEventTag),
  },
) {
  override get message(): string {
    return `The ledger catalog does not match this simulator definition: expected [${this.expectedTags.join(", ")}], found [${this.actualTags.join(", ")}]`;
  }
}
```

Implements ledger catalog mismatch.

### [`LedgerCompletion`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/schema.ts#L77)

*Class*

```ts theme={null}
export class LedgerCompletion extends Schema.Class<LedgerCompletion>(
  "LedgerCompletion",
)({
  ledgerFormatVersion: Schema.Literal(LEDGER_FORMAT_VERSION),
  runId: Schema.NonEmptyString,
  recordCount: nonNegativeInteger,
  artifacts: Schema.Struct({
    manifest: ledgerDigest,
    records: ledgerDigest,
  }),
}) {}
```

The immutable publication marker for a completed ledger.

### [`LedgerDefinitionMismatch`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/read.ts#L73)

*Class*

```ts theme={null}
export class LedgerDefinitionMismatch extends Schema.TaggedError<LedgerDefinitionMismatch>()(
  "LedgerDefinitionMismatch",
  {
    expectedDefinitionId: versionedDefinitionId,
    actualDefinitionId: versionedDefinitionId,
  },
) {
  override get message(): string {
    return `The ledger belongs to definition "${this.actualDefinitionId}", not "${this.expectedDefinitionId}"`;
  }
}
```

Implements ledger definition mismatch.

### [`ledgerDigest`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/schema.ts#L56)

*Variable*

```ts theme={null}
export const ledgerDigest = Schema.String.pipe(
  Schema.pattern(/^[\da-f]{64}$/u),
  Schema.brand("LedgerDigest"),
)
```

Validates and decodes ledger digest values.

### [`LedgerDigest`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/schema.ts#L61)

*TypeAlias*

```ts theme={null}
export type LedgerDigest = typeof ledgerDigest.Type;
```

Represents ledger digest values.

### [`LedgerFailure`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/append.ts#L59)

*TypeAlias*

```ts theme={null}
export type LedgerFailure =
  | LedgerStorageError
  | ParseResult.ParseError
  | LedgerSerializationError;
```

Represents ledger failure conditions.

### [`LedgerInvalid`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/read.ts#L46)

*Class*

```ts theme={null}
export class LedgerInvalid extends Schema.TaggedError<LedgerInvalid>()(
  "LedgerInvalid",
  {
    artifact: Schema.Literal("manifest", "records", "completion"),
    reason: ledgerInvalidReasonSchema,
    detail: Schema.String,
  },
) {
  override get message(): string {
    return `${this.artifact}: ${this.detail}`;
  }
}
```

Implements ledger invalid.

### [`LedgerInvalidReason`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/read.ts#L43)

*TypeAlias*

```ts theme={null}
export type LedgerInvalidReason = typeof ledgerInvalidReasonSchema.Type;
```

Represents ledger invalid reason values.

### [`LedgerManifest`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/schema.ts#L64)

*Class*

```ts theme={null}
export class LedgerManifest extends Schema.Class<LedgerManifest>(
  "LedgerManifest",
)({
  ledgerFormatVersion: Schema.Literal(LEDGER_FORMAT_VERSION),
  definitionId: versionedDefinitionId,
  runId: Schema.NonEmptyString,
  catalogTags: Schema.Array(versionedEventTag),
  createdAt: Schema.DateTimeUtc,
  provenance: jsonObjectSchema,
  metadata: jsonObjectSchema,
}) {}
```

Definition and provenance bound to every completed ledger.

### [`LedgerOpenError`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/read.ts#L86)

*TypeAlias*

```ts theme={null}
export type LedgerOpenError =
  | LedgerCatalogMismatch
  | LedgerDefinitionMismatch
  | LedgerInvalid
  | LedgerStorageError;
```

Represents ledger open error conditions.

### [`LedgerRecord`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/schema.ts#L90)

*Interface*

```ts theme={null}
export interface LedgerRecord<Catalog> {
  readonly runId: string;
  readonly eventId: string;
  readonly logicalSequence: number;
  readonly elapsedNanos: bigint;
  readonly observedAt: number;
  readonly producer: string;
  readonly causationId?: string;
  readonly correlationId?: string;
  readonly event: EventOf<Catalog>;
}
```

One exact event envelope in a run ledger.

### [`ledgerRef`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/schema.ts#L15)

*Variable*

```ts theme={null}
export const ledgerRef = Schema.NonEmptyString.pipe(Schema.brand("LedgerRef"))
```

Storage-owned identity that never exposes a filesystem path.

### [`LedgerRef`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/schema.ts#L17)

*TypeAlias*

```ts theme={null}
export type LedgerRef = typeof ledgerRef.Type;
```

Represents ledger ref values.

### [`LedgerSerializationError`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/append.ts#L50)

*Class*

```ts theme={null}
export class LedgerSerializationError extends Schema.TaggedError<LedgerSerializationError>()(
  "LedgerSerializationError",
  {
    operation: Schema.Literal("parse", "stringify"),
    cause: Schema.Defect,
  },
) {}
```

Reports ledger serialization failures.

### [`LedgerStorage`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/storage.ts#L129)

*Class*

```ts theme={null}
export class LedgerStorage extends Context.Tag(
  "@moltzap/simulator/LedgerStorage",
)<LedgerStorage, LedgerStorageService>() {}
```

Outer layers provide the concrete ledger persistence implementation.

### [`LedgerStorageError`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/storage.ts#L49)

*Class*

```ts theme={null}
export class LedgerStorageError extends Schema.TaggedError<LedgerStorageError>()(
  "LedgerStorageError",
  {
    operation: ledgerStorageOperationSchema,
    detail: Schema.String,
    ref: Schema.optional(ledgerRef),
    artifact: Schema.optional(ledgerArtifactSchema),
  },
) {
  override get message(): string {
    const subject = this.ref ?? "ledger storage";
    return `${this.operation} ${subject}: ${this.detail}`;
  }
}
```

Stable failure at the ledger storage boundary.

### [`LedgerStorageService`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/storage.ts#L99)

*Interface*

```ts theme={null}
export interface LedgerStorageService {
  readonly allocate: (
    input: LedgerAllocationInput,
  ) => Effect.Effect<LedgerAllocation, LedgerStorageError>;
  readonly read: (
    ref: LedgerRef,
    artifact: LedgerArtifact,
  ) => Effect.Effect<string, LedgerStorageError>;
  readonly digest: (
    text: string,
  ) => Effect.Effect<LedgerDigest, LedgerStorageError>;
}
```

Describes ledger storage service.

### [`makeLedgerRecordSchema`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/schema.ts#L107)

*Function*

```ts theme={null}
export function makeLedgerRecordSchema<
  SchemaType extends Schema.Schema.All,
  Classes extends EventClass,
>(catalog: EventCatalog<SchemaType, Classes>)
```

The envelope schema shared by live commits and completed-ledger inspection.

**Returns:** The created ledger record schema.

### [`openLedger`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/read.ts#L136)

*Function*

```ts theme={null}
export function openLedger<
  SchemaType extends Schema.Schema.AnyNoContext,
  Classes extends EventClass,
>(
  catalog: EventCatalog<SchemaType, Classes>,
  ref: LedgerRef,
  expectedDefinitionId?: string,
): Effect.Effect<
  CompletedRunLedger<EventCatalog<SchemaType, Classes>>,
  LedgerOpenError,
  LedgerStorage
>
```

Validate a completed ledger before exposing its reusable typed record
stream. The exact catalog is required; no unknown-event branch escapes.

**Returns:** The open ledger result.

### [`openLedgerArtifacts`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/read.ts#L163)

*Function*

```ts theme={null}
export function openLedgerArtifacts<
  SchemaType extends Schema.Schema.AnyNoContext,
  Classes extends EventClass,
>(
  catalog: EventCatalog<SchemaType, Classes>,
  ref: LedgerRef,
  artifacts: CompletedLedgerArtifacts,
  expectedDefinitionId?: string,
): Effect.Effect<
  CompletedRunLedger<EventCatalog<SchemaType, Classes>>,
  LedgerOpenError
>
```

Validate already-retrieved durable artifacts without exposing their storage
backend through the customer program.

**Returns:** A validated completed ledger with infallible record streams.

### [`readLedgerManifest`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/read.ts#L114)

*Variable*

```ts theme={null}
export const readLedgerManifest = Effect.fn("readLedgerManifest")(function* (
  ref: LedgerRef,
): Effect.fn.Return<
  LedgerManifest,
  LedgerInvalid | LedgerStorageError,
  LedgerStorage
> {
  const reader = ledgerReaderFor(yield* LedgerStorage, ref);
  const text = yield* reader.read("manifest");
  const manifest = yield* decodeJson("manifest", LedgerManifest, text);
  yield* validateManifestTags(manifest);
  return manifest;
})
```

Inspect definition and provenance without granting access to unverified
records.

### [`RunLedger`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/ledger/append.ts#L65)

*Interface*

```ts theme={null}
export interface RunLedger<Catalog> {
  readonly ref: LedgerRef;
  readonly manifest: LedgerManifest;
  readonly records: Stream.Stream<LedgerRecord<Catalog>, LedgerFailure>;
  readonly events: <Event extends EventClassOf<Catalog>>(
    eventClass: Event,
  ) => Stream.Stream<Schema.Schema.Type<Event>, LedgerFailure>;
}
```

Readable, definition-bound live ledger capability.

### [`VersionedEventTag`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/catalog.ts#L6)

*TypeAlias*

```ts theme={null}
export type VersionedEventTag = `${string}.${string}/v${number}`;
```

Stable persisted identity for an event class.

## Files

* `append.ts`
* `filesystem.ts`
* `index.ts`
* `read.ts`
* `schema.ts`
* `storage.ts`
