> ## Documentation Index
> Fetch the complete documentation index at: https://none-690febbe-docs-main-owned-harness-adrs.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# simulator/src

> Code-first simulator API.

# simulator/src

*`packages/simulator/src`*

## Purpose

Code-first simulator API.

## Public surface

### [`AgentConnection`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/router.ts#L84)

*Interface*

```ts theme={null}
export interface AgentConnection<Name extends string = string> {
  readonly agent: AgentHandle<Name>;
  readonly key: AgentKey;
  readonly routerUrl: ServerBaseUrl;
}
```

Runtime connection issued by every router implementation. It carries the
credential and address a runtime dials; each runtime chooses its own startup
deadline and owns whatever readiness evidence its process exposes.

### [`AgentHandle`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/participant.ts#L58)

*Class*

```ts theme={null}
export class AgentHandle<
  Name extends string = string,
> extends ParticipantHandle<Name> {
  readonly [agentHandleTypeId] = agentHandleTypeId;

  private constructor(name: Name, id: AgentId) {
    super(name, id);
  }

  static [agentHandleConstruction]<const Name extends string>(
    name: Name,
    id: AgentId,
  ): AgentHandle<Name> {
    return new AgentHandle(name, id);
  }
}
```

A participant whose autonomous runtime is owned by the run scope.

### [`AgentProcessExited`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L85)

*Class*

```ts theme={null}
export class AgentProcessExited extends Schema.TaggedClass<AgentProcessExited>()(
  "moltzap.agent-process-exited/v1",
  {
    agentName: agentName,
    agentId: agentId,
    runtime: Schema.NonEmptyString,
    code: Schema.NonNegativeInt,
  },
) {}
```

A roster runtime process terminated with an operating-system exit code.

### [`AgentProcessSignaled`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L96)

*Class*

```ts theme={null}
export class AgentProcessSignaled extends Schema.TaggedClass<AgentProcessSignaled>()(
  "moltzap.agent-process-signaled/v1",
  {
    agentName: agentName,
    agentId: agentId,
    runtime: Schema.NonEmptyString,
    signal: Schema.NonEmptyString,
  },
) {}
```

A roster runtime process terminated because it received a signal.

### [`AgentRuntimeCompleted`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L64)

*Class*

```ts theme={null}
export class AgentRuntimeCompleted extends Schema.TaggedClass<AgentRuntimeCompleted>()(
  "moltzap.agent-runtime-completed/v1",
  {
    agentName: agentName,
    agentId: agentId,
    runtime: Schema.NonEmptyString,
  },
) {}
```

An autonomous runtime completed normally.

### [`AgentRuntimeFailed`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L74)

*Class*

```ts theme={null}
export class AgentRuntimeFailed extends Schema.TaggedClass<AgentRuntimeFailed>()(
  "moltzap.agent-runtime-failed/v1",
  {
    agentName: agentName,
    agentId: agentId,
    runtime: Schema.NonEmptyString,
    cause: Schema.NonEmptyString,
  },
) {}
```

An autonomous runtime completed with a recorded failure.

### [`AgentRuntimeReady`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L44)

*Class*

```ts theme={null}
export class AgentRuntimeReady extends Schema.TaggedClass<AgentRuntimeReady>()(
  "moltzap.agent-runtime-ready/v1",
  {
    agentName: agentName,
    agentId: agentId,
    runtime: Schema.NonEmptyString,
  },
) {}
```

A roster runtime has acquired its identity and completed readiness.

### [`AgentRuntimeStartFailed`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L54)

*Class*

```ts theme={null}
export class AgentRuntimeStartFailed extends Schema.TaggedClass<AgentRuntimeStartFailed>()(
  "moltzap.agent-runtime-start-failed/v1",
  {
    agentName: agentName,
    runtime: Schema.NonEmptyString,
    cause: Schema.NonEmptyString,
  },
) {}
```

A roster runtime failed before it established readiness.

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

*Class*

```ts theme={null}
export class ClusterError extends Data.TaggedError("ClusterError")<{
  readonly detail: string;
}> {
  override get message(): string {
    return this.detail;
  }
}
```

Cluster loss that ends a run without exposing its backend.

### [`ClusterLost`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/run/execute.ts#L97)

*Class*

```ts theme={null}
export class ClusterLost<
  Definitions extends Readonly<Record<string, AgentRuntimeLike>>,
> extends Data.TaggedClass("ClusterLost")<{
  readonly cause: Cause.Cause<SimulatorRunFailure<Definitions>>;
  readonly receipt: LedgerReceipt;
}> {}
```

Post-allocation cluster error plus all durable evidence retained.

### [`ClusterServices`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/definition.ts#L76)

*TypeAlias*

```ts theme={null}
export type ClusterServices = LedgerStorage | RouterProvider | Cluster;
```

Opaque service set supplied by a local-Kubernetes or GKE Layer.

### [`CompletedLedgerReceipt`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/run/execute.ts#L64)

*Class*

```ts theme={null}
export class CompletedLedgerReceipt extends Schema.TaggedClass<CompletedLedgerReceipt>()(
  "CompletedLedgerReceipt",
  {
    ledger: ledgerRef,
    completion: LedgerCompletion,
  },
) {}
```

Physical receipt for a ledger whose completion marker is durable.

### [`ConversationAddress`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/conversation.ts#L34)

*Class*

```ts theme={null}
export class ConversationAddress {
  readonly [conversationAddressTypeId] = conversationAddressTypeId;

  readonly conversationId: ConversationId;
  readonly participants: ConversationParticipants;

  private constructor(
    conversationId: ConversationId,
    participants: ConversationParticipants,
  ) {
    this.conversationId = conversationId;
    this.participants = participants;
  }

  static [conversationAddressConstruction](
    conversationId: ConversationId,
    participants: ConversationParticipants,
  ): ConversationAddress {
    return new ConversationAddress(conversationId, participants);
  }
}
```

A participant-independent network address. Binding an endpoint produces a
conversation socket; the address itself never implies a sender.

### [`ConversationOpened`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L107)

*Class*

```ts theme={null}
export class ConversationOpened extends Schema.TaggedClass<ConversationOpened>()(
  "moltzap.conversation-opened/v1",
  {
    openedBy: agentId,
    conversationId: conversationId,
    participants: Schema.NonEmptyArray(agentId),
  },
) {}
```

A participant allocated a conversation address for a nonempty group.

### [`ConversationParticipants`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/conversation.ts#L25)

*TypeAlias*

```ts theme={null}
export type ConversationParticipants = readonly [
  ParticipantHandle,
  ...(readonly ParticipantHandle[]),
];
```

Every conversation has at least one participant of any network role.

### [`ConversationSocket`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/conversation.ts#L95)

*Class*

```ts theme={null}
export class ConversationSocket {
  readonly [conversationSocketTypeId] = conversationSocketTypeId;

  /**
   * The ordered receive cursor for this endpoint and conversation. Repeated
   * consumption advances the cursor instead of replaying old delivery.
   */
  readonly messages: Stream.Stream<ReceivedMessage, NetworkError>;

  readonly endpoint: ParticipantHandle;
  readonly address: ConversationAddress;
  private readonly sendMessage: (
    content: MessageParts,
  ) => Effect.Effect<Message, NetworkError>;

  private constructor(
    endpoint: ParticipantHandle,
    address: ConversationAddress,
    messages: Stream.Stream<ReceivedMessage, NetworkError>,
    sendMessage: (
      content: MessageParts,
    ) => Effect.Effect<Message, NetworkError>,
  ) {
    this.endpoint = endpoint;
    this.address = address;
    this.sendMessage = sendMessage;
    this.messages = messages;
  }

  static [conversationSocketConstruction](
    endpoint: ParticipantHandle,
    address: ConversationAddress,
    messages: Stream.Stream<ReceivedMessage, NetworkError>,
    sendMessage: (
      content: MessageParts,
    ) => Effect.Effect<Message, NetworkError>,
  ): ConversationSocket {
    return new ConversationSocket(endpoint, address, messages, sendMessage);
  }

  /**
   * Commit one message through the bound endpoint.
   * @param content Value supplied to the operation.
   * @returns The created conversation socket.
   */
  send(content: string | MessageParts): Effect.Effect<Message, NetworkError> {
    return validateParts(parts(content)).pipe(Effect.flatMap(this.sendMessage));
  }

  /**
   * Receive the next ordered delivery. Selection policy belongs in the
   * consuming Effect, so the socket never skips an earlier message.
   * @returns The created conversation socket.
   */
  receive(): Effect.Effect<ReceivedMessage, NetworkError> {
    return this.messages.pipe(
      Stream.runHead,
      Effect.flatMap(
        Option.match({
          onNone: () =>
            Effect.fail(
              networkError(
                "receive",
                `conversation ${this.address.conversationId} ended before another message arrived`,
              ),
            ),
          onSome: Effect.succeed,
        }),
      ),
    );
  }
}
```

A conversation address bound to exactly one controlled endpoint.

### [`coreEvents`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L284)

*Variable*

```ts theme={null}
export const coreEvents = EventCatalog.merge(
  runEvents,
  routerEvents,
  runtimeEvents,
  endpointEvents,
  linkEvents,
)
```

The exact event classes readable from every simulator run ledger.

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

*Interface*

```ts theme={null}
export interface CustomerEvents<Catalog extends AnyEventCatalog> {
  readonly emit: (
    event: EventOf<Catalog>,
    metadata?: EventMetadata,
  ) => Effect.Effect<LedgerRecord<Catalog>, LedgerFailure>;
}
```

Definition-bound emission of customer-owned event classes only.

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

*TypeAlias*

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

The closed encoded union persisted for a catalog.

### [`Endpoint`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/endpoint.ts#L53)

*Class*

```ts theme={null}
export class Endpoint<Name extends string = string> {
  readonly [endpointTypeId] = endpointTypeId;

  readonly participant: ParticipantHandle<Name>;
  private readonly transport: EndpointTransport;
  private readonly inbox: EndpointInbox;

  private constructor(
    participant: ParticipantHandle<Name>,
    transport: EndpointTransport,
    inbox: EndpointInbox,
  ) {
    this.participant = participant;
    this.transport = transport;
    this.inbox = inbox;
  }

  static [endpointConstruction]<const Name extends string>(
    attachment: AttachedEndpoint<Name>,
    inbox: EndpointInbox,
  ): Endpoint<Name> {
    return new Endpoint(attachment.participant, attachment.transport, inbox);
  }

  /**
   * Observe messages delivered after this stream is subscribed. Conversation
   * sockets retain their own ordered delivery queues independently.
   * @returns Live endpoint delivery stream.
   */
  messages(): Stream.Stream<ReceivedMessage, NetworkError> {
    return this.inbox.messages;
  }

  /**
   * Open a conversation through this endpoint's ordinary protocol attachment.
   * The opener is included in the resulting address automatically.
   * @param participants Nonempty addressed participant set.
   * @returns A conversation socket bound to this endpoint.
   */
  open(
    ...participants: ConversationParticipants
  ): Effect.Effect<ConversationSocket, NetworkError> {
    const [first, ...rest] = participants;
    const ids: ParticipantIds = [
      first.id,
      ...rest.map((participant) => participant.id),
    ];
    const addressed = addressedParticipants(this.participant, participants);
    return this.transport.openConversation(ids).pipe(
      Effect.flatMap((opened) =>
        this.inbox.conversation(opened.conversationId).pipe(
          Effect.map((messages) => ({
            messages,
            opened,
          })),
        ),
      ),
      Effect.map(({ messages, opened }) => {
        const address = makeConversationAddress(
          opened.conversationId,
          addressed,
        );
        return makeConversationSocket(
          this.participant,
          address,
          messages,
          (content) => this.transport.send(address.conversationId, content),
        );
      }),
    );
  }

  /**
   * Bind this endpoint as the sender for an existing address.
   * @param address Participant-independent conversation address.
   * @returns Endpoint-bound socket when this endpoint is addressed.
   */
  socket(
    address: ConversationAddress,
  ): Effect.Effect<ConversationSocket, NetworkError> {
    const isParticipant = address.participants.some(
      (participant) => participant.id === this.participant.id,
    );
    return isParticipant
      ? this.inbox
          .conversation(address.conversationId)
          .pipe(
            Effect.map((messages) =>
              makeConversationSocket(
                this.participant,
                address,
                messages,
                (content) =>
                  this.transport.send(address.conversationId, content),
              ),
            ),
          )
      : Effect.fail(
          networkError(
            "socket",
            `participant ${this.participant.name} is not addressed by the conversation`,
          ),
        );
  }
}
```

A run-scoped participant controlled directly by the experiment program.

### [`EndpointMessageReceived`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L128)

*Class*

```ts theme={null}
export class EndpointMessageReceived extends Schema.TaggedClass<EndpointMessageReceived>()(
  "moltzap.endpoint-message-received/v1",
  {
    endpointId: agentId,
    conversationId: conversationId,
    messageId: messageId,
    senderId: agentId,
    parts: messageParts,
  },
) {}
```

A controlled endpoint received a message through the data plane.

### [`EndpointMessageSent`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L117)

*Class*

```ts theme={null}
export class EndpointMessageSent extends Schema.TaggedClass<EndpointMessageSent>()(
  "moltzap.endpoint-message-sent/v1",
  {
    endpointId: agentId,
    conversationId: conversationId,
    messageId: messageId,
    parts: messageParts,
  },
) {}
```

A controlled endpoint committed a message through the data plane.

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

*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#L59)

*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#L48)

*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#L10)

*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#L40)

*TypeAlias*

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

The closed constructor union declared by a catalog.

### [`EventMetadata`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/run/events.ts#L26)

*Interface*

```ts theme={null}
export interface EventMetadata {
  readonly causationId?: string;
  readonly correlationId?: string;
}
```

Causality metadata accepted from a customer event producer.

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

*TypeAlias*

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

The closed instance union declared by a catalog.

### [`IncompleteLedgerReceipt`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/run/execute.ts#L73)

*Class*

```ts theme={null}
export class IncompleteLedgerReceipt extends Schema.TaggedClass<IncompleteLedgerReceipt>()(
  "IncompleteLedgerReceipt",
  {
    ledger: ledgerRef,
  },
) {}
```

Physical receipt retained when ledger completion could not be published.

### [`isEntryModule`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/cluster/entry.ts#L31)

*Function*

```ts theme={null}
export function isEntryModule(moduleUrl: string, invoked?: string): boolean
```

Whether a module is the process entry point rather than an ordinary import.

Both sides are canonicalized because they are not the same kind of path:
Node resolves a module's real path before it becomes `import.meta.url`, while
`process.argv[1]` is whatever the caller typed. Every executable in this
package reaches its module through a symlink in the controller image, where
`/opt/moltzap/dist` points at the installed package directory. Comparing the
two without canonicalizing makes a directly invoked entry point look like an
import, so the process exits successfully having done nothing.

`realPath` returns undefined for a path that does not exist, so a missing or
deleted `argv[1]` is a plain false rather than a thrown ENOENT.

**Returns:** Whether both locations name the same real file.

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

*TypeAlias*

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

Represents ledger failure conditions.

### [`LedgerReceipt`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/run/execute.ts#L88)

*TypeAlias*

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

Decoded physical ledger receipt.

### [`LedgerReceipt`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/run/execute.ts#L82)

*Variable*

```ts theme={null}
export const LedgerReceipt = Schema.Union(
  CompletedLedgerReceipt,
  IncompleteLedgerReceipt,
)
```

Schema for the complete physical ledger-receipt universe.

### [`LinkController`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/link.ts#L148)

*Class*

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

Experiment-facing directed-link control installed by the run kernel.

### [`LinkControllerService`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/link.ts#L118)

*Interface*

```ts theme={null}
export interface LinkControllerService {
  /**
   * Keep one directed link disabled for the lifetime of the current Scope.
   * Overlapping acquisitions share a single physical down/up transition.
   */
  readonly disable: (
    from: ParticipantHandle,
    to: ParticipantHandle,
  ) => Effect.Effect<void, NetworkError, LinkDriver | Scope.Scope>;
  /** Delay every delivery on one directed link for the current Scope. */
  readonly delay: (
    from: ParticipantHandle,
    to: ParticipantHandle,
    duration: Duration.DurationInput,
  ) => Effect.Effect<void, NetworkError, LinkDriver | Scope.Scope>;
  /** Park every delivery on one directed link for the current Scope. */
  readonly hold: (
    from: ParticipantHandle,
    to: ParticipantHandle,
  ) => Effect.Effect<void, NetworkError, LinkDriver | Scope.Scope>;
  /** Install one custom policy on a directed link for the current Scope. */
  readonly shape: (
    from: ParticipantHandle,
    to: ParticipantHandle,
    policy: LinkPolicy,
    description: string,
  ) => Effect.Effect<void, NetworkError, LinkDriver | Scope.Scope>;
}
```

Run-scoped, evidence-producing directed-link control.

### [`LinkDelivery`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/link.ts#L17)

*Interface*

```ts theme={null}
export interface LinkDelivery {
  /** Message sender identity. */
  readonly from: AgentId;
  /** Receiving participant identity. */
  readonly to: AgentId;
  /** Router message carried by the delivery. */
  readonly message: Message;
}
```

One committed message about to cross a directed link.

### [`LinkDown`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L148)

*Class*

```ts theme={null}
export class LinkDown extends Schema.TaggedClass<LinkDown>()(
  "moltzap.link-down/v1",
  {
    from: agentId,
    to: agentId,
  },
) {}
```

A directed participant link transitioned from available to unavailable.

### [`LinkMessageDelayed`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L195)

*Class*

```ts theme={null}
export class LinkMessageDelayed extends Schema.TaggedClass<LinkMessageDelayed>()(
  "moltzap.link-message-delayed/v1",
  {
    from: agentId,
    to: agentId,
    conversationId: conversationId,
    messageId: messageId,
    delayMillis: Schema.NonNegative,
  },
) {}
```

Active link policies deferred one delivery by a known total duration.

### [`LinkMessageDropped`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L183)

*Class*

```ts theme={null}
export class LinkMessageDropped extends Schema.TaggedClass<LinkMessageDropped>()(
  "moltzap.link-message-dropped/v1",
  {
    from: agentId,
    to: agentId,
    conversationId: conversationId,
    messageId: messageId,
    reason: Schema.optional(Schema.String),
  },
) {}
```

An active link policy discarded one committed message before delivery.

### [`LinkMessageHeld`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L207)

*Class*

```ts theme={null}
export class LinkMessageHeld extends Schema.TaggedClass<LinkMessageHeld>()(
  "moltzap.link-message-held/v1",
  {
    from: agentId,
    to: agentId,
    conversationId: conversationId,
    messageId: messageId,
  },
) {}
```

An active link policy parked one delivery until its lease clears.

### [`linkPolicy`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/link.ts#L45)

*Variable*

```ts theme={null}
export const linkPolicy:
```

Canonical link policies for the common traffic shapes.

### [`LinkPolicy`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/link.ts#L42)

*TypeAlias*

```ts theme={null}
export type LinkPolicy = (delivery: LinkDelivery) => Effect.Effect<LinkVerdict>;
```

Decides one delivery on a directed link. A policy reads only its input and
the ambient Clock; the link interpreter, never the policy, spends time and
records evidence.

### [`LinkPolicyCleared`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L173)

*Class*

```ts theme={null}
export class LinkPolicyCleared extends Schema.TaggedClass<LinkPolicyCleared>()(
  "moltzap.link-policy-cleared/v1",
  {
    from: agentId,
    to: agentId,
    policy: Schema.NonEmptyString,
  },
) {}
```

A described policy stopped shaping one directed participant link.

### [`LinkPolicySet`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L163)

*Class*

```ts theme={null}
export class LinkPolicySet extends Schema.TaggedClass<LinkPolicySet>()(
  "moltzap.link-policy-set/v1",
  {
    from: agentId,
    to: agentId,
    policy: Schema.NonEmptyString,
  },
) {}
```

A described policy became active on one directed participant link.

### [`LinkUp`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L157)

*Class*

```ts theme={null}
export class LinkUp extends Schema.TaggedClass<LinkUp>()("moltzap.link-up/v1", {
  from: agentId,
  to: agentId,
}) {}
```

A directed participant link transitioned from unavailable to available.

### [`linkVerdict`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/link.ts#L35)

*Variable*

```ts theme={null}
export const linkVerdict = Data.taggedEnum<LinkVerdict>()
```

Constructors and matchers for the closed verdict union.

### [`LinkVerdict`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/link.ts#L27)

*TypeAlias*

```ts theme={null}
export type LinkVerdict = Data.TaggedEnum<{
  deliver: Record<never, never>;
  drop: { readonly reason?: string };
  delay: { readonly duration: Duration.Duration };
  hold: Record<never, never>;
}>;
```

Closed per-delivery decision returned by a link policy.

### [`MessageParts`](https://github.com/chughtapan/moltzap/blob/main/packages/protocol/dist/message/parts.d.ts#L41)

*TypeAlias*

```ts theme={null}
export type MessageParts = Schema.Schema.Type<typeof messagePartsSchemaValue>;
```

Nonempty protocol message content.

### [`Network`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/endpoint.ts#L184)

*Class*

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

Network operations available to the customer program.

### [`NetworkError`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/failure.ts#L22)

*Class*

```ts theme={null}
export class NetworkError extends Schema.TaggedError<NetworkError>()(
  "NetworkError",
  {
    operation: networkOperation,
    detail: Schema.String,
  },
) {
  override get message(): string {
    return `Network ${this.operation} failed: ${this.detail}`;
  }
}
```

An operational failure at a network boundary.

### [`NetworkService`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/endpoint.ts#L177)

*Interface*

```ts theme={null}
export interface NetworkService {
  endpoint<const Name extends string>(
    name: Name,
  ): Effect.Effect<Endpoint<Name>, NetworkError>;
}
```

Controlled endpoint operations installed for one run scope.

### [`ParticipantHandle`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/participant.ts#L22)

*Class*

```ts theme={null}
export class ParticipantHandle<Name extends string = string> {
  readonly [participantHandleTypeId] = participantHandleTypeId;

  readonly name: Name;
  readonly id: AgentId;

  protected constructor(name: Name, id: AgentId) {
    this.name = name;
    this.id = id;
  }

  static [participantHandleConstruction]<const Name extends string>(
    name: Name,
    id: AgentId,
  ): ParticipantHandle<Name> {
    return new ParticipantHandle(name, id);
  }
}
```

A router-issued network identity. The hidden symbol prevents structurally
similar protocol data from being used as an identity handle.

### [`ProgramFailed`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L224)

*Class*

```ts theme={null}
export class ProgramFailed extends Schema.TaggedClass<ProgramFailed>()(
  "moltzap.program-failed/v1",
  {
    cause: Schema.NonEmptyString,
  },
) {}
```

The customer program failed with a typed failure or defect.

### [`ProgramFinished`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/run/execute.ts#L91)

*Class*

```ts theme={null}
export class ProgramFinished<A, E> extends Data.TaggedClass("ProgramFinished")<{
  readonly exit: Exit.Exit<A, E>;
  readonly receipt: CompletedLedgerReceipt;
}> {}
```

Customer-program completion plus its complete durable evidence.

### [`ProgramInterrupted`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L232)

*Class*

```ts theme={null}
export class ProgramInterrupted extends Schema.TaggedClass<ProgramInterrupted>()(
  "moltzap.program-interrupted/v1",
  {
    cause: Schema.NonEmptyString,
  },
) {}
```

The customer program was interrupted.

### [`ProgramSucceeded`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L218)

*Class*

```ts theme={null}
export class ProgramSucceeded extends Schema.TaggedClass<ProgramSucceeded>()(
  "moltzap.program-succeeded/v1",
  {},
) {}
```

The customer program returned successfully.

### [`ReadableRunLedger`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/run/events.ts#L32)

*Interface*

```ts theme={null}
export interface ReadableRunLedger<Catalog extends AnyEventCatalog> {
  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>;
}
```

Definition-bound read access to every committed core and customer event.

### [`ReceivedMessage`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/network/router.ts#L39)

*Interface*

```ts theme={null}
export interface ReceivedMessage {
  readonly message: Message;
}
```

A message delivered to one attached endpoint.

### [`RouterMessageCommitted`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L140)

*Class*

```ts theme={null}
export class RouterMessageCommitted extends Schema.TaggedClass<RouterMessageCommitted>()(
  "moltzap.router-message-committed/v1",
  {
    ...CommittedRouterMessage.fields,
  },
) {}
```

The router durably committed one message, plaintext parts included.

### [`RouterStarted`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L20)

*Class*

```ts theme={null}
export class RouterStarted extends Schema.TaggedClass<RouterStarted>()(
  "moltzap.router-started/v1",
  {
    routerUrl: serverBaseUrlSchema,
  },
) {}
```

The run-scoped router is accepting participant connections.

### [`RouterStartFailed`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L28)

*Class*

```ts theme={null}
export class RouterStartFailed extends Schema.TaggedClass<RouterStartFailed>()(
  "moltzap.router-start-failed/v1",
  {
    cause: Schema.NonEmptyString,
  },
) {}
```

Router acquisition failed before the data plane became available.

### [`RouterStopFailed`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/events/core.ts#L36)

*Class*

```ts theme={null}
export class RouterStopFailed extends Schema.TaggedClass<RouterStopFailed>()(
  "moltzap.router-stop-failed/v1",
  {
    cause: Schema.NonEmptyString,
  },
) {}
```

Router release or stopped-router evidence collection failed.

### [`Run`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/definition.ts#L310)

*Variable*

```ts theme={null}
export const Run: Readonly<{ execute: typeof executeRunSpec }> = Object.freeze({
  execute: executeRunSpec,
})
```

Discoverable execution entry point for one experiment society.

### [`RunSpec`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/definition.ts#L150)

*Interface*

```ts theme={null}
export interface RunSpec<
  Id extends SimulatorDefinitionId = SimulatorDefinitionId,
  CustomerCatalogs extends
    readonly AnyEventCatalog[] = readonly AnyEventCatalog[],
  Definitions extends Readonly<Record<string, AgentRuntimeLike>> = Readonly<
    Record<string, AgentRuntimeLike>
  >,
  A = unknown,
  E = unknown,
  R = never,
  ClusterLayer extends Layer.Layer<
    never,
    unknown,
    unknown
  > = Layer.Layer<ClusterServices>,
> {
  /**
   * Present only on the exact values RunSpec.define produced, and carrying
   * their runner. This is the one identity gate: nothing structural
   * distinguishes a definition from a lookalike, and a lookalike has no
   * runner to invoke.
   */
  readonly [runSpecTypeId]?: () => RunSpecExecution<
    Id,
    CustomerCatalogs,
    Definitions,
    A,
    E,
    R,
    ClusterLayer
  >;
  readonly id: Id;
  readonly events: CustomerCatalogs;
  readonly agents: Definitions;
  readonly cluster: ClusterLayer &
    Layer.Layer<
      ClusterServices,
      Layer.Layer.Error<ClusterLayer>,
      Layer.Layer.Context<ClusterLayer>
    >;
  readonly execute: (
    context: RunExecutionContext<Id, CustomerCatalogs, Definitions>,
  ) => Effect.Effect<A, E, R>;
}
```

Immutable code-first definition of one experiment society.

### [`RunSpec`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/definition.ts#L305)

*Variable*

```ts theme={null}
export const RunSpec: Readonly<{ define: typeof defineRunSpec }> =
  Object.freeze({ define: defineRunSpec })
```

Discoverable constructor for immutable experiment definitions.

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

*Class*

```ts theme={null}
export class RunStarted extends Schema.TaggedClass<RunStarted>()(
  "moltzap.run-started/v1",
  {
    definitionId: Schema.NonEmptyString,
  },
) {}
```

The run ledger is allocated and run-scoped acquisition has begun.

### [`SimulatorDefinitionError`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/definition.ts#L28)

*Class*

```ts theme={null}
export class SimulatorDefinitionError extends Schema.TaggedError<SimulatorDefinitionError>()(
  "SimulatorDefinitionError",
  {
    definitionId: Schema.String,
    detail: Schema.NonEmptyString,
  },
) {
  override get message(): string {
    return `Simulator definition "${this.definitionId}" is invalid: ${this.detail}`;
  }
}
```

Reports simulator definition failures.

### [`SimulatorDefinitionId`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/definition.ts#L23)

*TypeAlias*

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

Stable code identity persisted in every ledger manifest.

### [`SimulatorRunFailure`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/run/execute.ts#L112)

*TypeAlias*

```ts theme={null}
export type SimulatorRunFailure<
  Definitions extends Readonly<Record<string, AgentRuntimeLike>>,
> =
```

Represents simulator run failure conditions.

### [`SimulatorRunOutcome`](https://github.com/chughtapan/moltzap/blob/main/packages/simulator/src/run/execute.ts#L105)

*TypeAlias*

```ts theme={null}
export type SimulatorRunOutcome<
  A,
  E,
  Definitions extends Readonly<Record<string, AgentRuntimeLike>>,
> = ProgramFinished<A, E> | ClusterLost<Definitions>;
```

Closed result of every run whose ledger allocation succeeded.

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

*TypeAlias*

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

Stable persisted identity for an event class.

## Files

* `cluster.ts`
* `entry.ts`
* `definition.ts`
* `catalog.ts`
* `core.ts`
* `append.ts`
* `conversation.ts`
* `endpoint.ts`
* `failure.ts`
* `link.ts`
* `participant.ts`
* `router.ts`
* `events.ts`
* `execute.ts`
