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

# contracts — Functions

> Functions and classes for the contracts package

Functions and classes exported by this package.

## isValidStatus()

**Signature**

```typescript theme={null}
(entityType: EntityType, value: string) => boolean
```

## SessionView

SessionView — typed wrapper over Session\[] with collection helpers.  Provides discoverable query methods for common session lookups. Does NOT change the DataAccessor interface — consumers create views from Session\[].

**Signature**

```typescript theme={null}
typeof SessionView
```

**Methods**

### from()

Create a SessionView from a Session array.

```typescript theme={null}
(sessions: Session[]) => SessionView
```

### findActive()

Find the currently active session (if any).

```typescript theme={null}
() => Session | undefined
```

### findById()

Find a session by ID.

```typescript theme={null}
(id: string) => Session | undefined
```

### filterByStatus()

Filter sessions by one or more statuses.

```typescript theme={null}
(...statuses: SessionStatus[]) => Session[]
```

### findByScope()

Find sessions matching a scope type and optional rootTaskId.

```typescript theme={null}
(type: string, rootTaskId?: string) => Session[]
```

### sortByDate()

Sort sessions by a date field. Returns a new array (does not mutate).

```typescript theme={null}
(field: "startedAt" | "endedAt", descending?: boolean) => Session[]
```

### mostRecent()

Get the most recently started session.

```typescript theme={null}
() => Session | undefined
```

### toArray()

Convert back to a plain Session array (shallow copy).

```typescript theme={null}
() => Session[]
```

### \[Symbol.iterator]\()

Support for-of iteration.

```typescript theme={null}
() => Iterator<Session>
```

## normalizeError(error, fallbackMessage)

Normalize any thrown value into a standardized error object.  Handles: - Error instances (preserves stack trace info) - Strings (wraps in Error) - Objects with message property - null/undefined (provides fallback)

**Signature**

```typescript theme={null}
(error: unknown, fallbackMessage?: string) => Error
```

**Parameters**

| Name              | Type       | Description                           |
| ----------------- | ---------- | ------------------------------------- |
| `error`           | `unknown`  | The thrown value to normalize         |
| `fallbackMessage` | `: string` | Message to use if error provides none |

**Returns** — Normalized error with consistent shape

**Example**

```typescript theme={null}
try {
  await riskyOperation();
} catch (err) {
  const error = normalizeError(err, 'Operation failed');
  console.error(error.message);
}
```

## getErrorMessage(error, fallback)

Extract a human-readable message from any error value.  Safe to use on unknown thrown values without type guards.

**Signature**

```typescript theme={null}
(error: unknown, fallback?: string) => string
```

**Parameters**

| Name       | Type       | Description                          |
| ---------- | ---------- | ------------------------------------ |
| `error`    | `unknown`  | The error value                      |
| `fallback` | `: string` | Fallback message if extraction fails |

**Returns** — The error message string

**Example**

```typescript theme={null}
const message = getErrorMessage(err, 'Unknown error');
```

## formatError(error, context, includeStack)

Format error details for logging or display.  Includes stack trace for Error instances when includeStack is true.

**Signature**

```typescript theme={null}
(error: unknown, context?: string, includeStack?: boolean) => string
```

**Parameters**

| Name           | Type        | Description                                      |
| -------------- | ----------- | ------------------------------------------------ |
| `error`        | `unknown`   | The error to format                              |
| `context`      | `: string`  | Optional context to prepend                      |
| `includeStack` | `: boolean` | Whether to include stack traces (default: false) |

**Returns** — Formatted error string

**Example**

```typescript theme={null}
console.error(formatError(err, 'Database connection'));
// Output: [Database connection] Connection refused
```

## isErrorType(error, codeOrName)

Check if an error represents a specific error type by code or name.  Useful for conditional error handling based on error types.

**Signature**

```typescript theme={null}
(error: unknown, codeOrName: string) => boolean
```

**Parameters**

| Name         | Type      | Description                     |
| ------------ | --------- | ------------------------------- |
| `error`      | `unknown` | The error to check              |
| `codeOrName` | `string`  | The error code or name to match |

**Returns** — True if the error matches

**Example**

```typescript theme={null}
if (isErrorType(err, 'E_NOT_FOUND')) {
  // Handle not found specifically
}
```

## createErrorResult(error)

Create a standardized error result object.  Common pattern for operations that return  success: boolean, error?: string

**Signature**

```typescript theme={null}
(error: unknown) => { success: false; error: string; }
```

**Parameters**

| Name    | Type      | Description     |
| ------- | --------- | --------------- |
| `error` | `unknown` | The error value |

**Returns** — Error result object

**Example**

```typescript theme={null}
return createErrorResult(err);
// Returns: { success: false, error: "Something went wrong" }
```

## createSuccessResult()

Create a standardized success result object.

**Signature**

```typescript theme={null}
() => { success: true; }
```

**Returns** — Success result object

**Example**

```typescript theme={null}
return createSuccessResult();
// Returns: { success: true }
```

## isErrorResult(result)

Type guard for error results.

**Signature**

```typescript theme={null}
(result: { success: boolean; error?: string; }) => result is { success: false; error: string; }
```

**Parameters**

| Name     | Type                                    | Description         |
| -------- | --------------------------------------- | ------------------- |
| `result` | `{ success: boolean; error?: string; }` | The result to check |

**Returns** — True if the result is an error result

**Example**

```typescript theme={null}
const result = await someOperation();
if (isErrorResult(result)) {
  console.error(result.error);
}
```

## isErrorCode()

Check if an exit code represents an error (1-99).

**Signature**

```typescript theme={null}
(code: ExitCode) => boolean
```

## isSuccessCode()

Check if an exit code represents success (0 or 100+).

**Signature**

```typescript theme={null}
(code: ExitCode) => boolean
```

## isNoChangeCode()

Check if an exit code indicates no change (idempotent operation).

**Signature**

```typescript theme={null}
(code: ExitCode) => boolean
```

## isRecoverableCode()

Check if an exit code is recoverable (retry may succeed).

**Signature**

```typescript theme={null}
(code: ExitCode) => boolean
```

## getExitCodeName()

Human-readable name for an exit code.

**Signature**

```typescript theme={null}
(code: ExitCode) => string
```

## isLafsSuccess(envelope)

Type guard for success responses.

**Signature**

```typescript theme={null}
<T>(envelope: LafsEnvelope<T>) => envelope is LafsSuccess<T>
```

**Parameters**

| Name       | Type              | Description            |
| ---------- | ----------------- | ---------------------- |
| `envelope` | `LafsEnvelope<T>` | The envelope to check. |

**Returns** — `true` if the envelope represents a successful operation.

**Example**

```ts theme={null}
const result: LafsEnvelope<Task[]> = await fetchTasks();
if (isLafsSuccess(result)) {
  console.log(result.data); // Task[]
}
```

## isLafsError(envelope)

Type guard for error responses.

**Signature**

```typescript theme={null}
<T>(envelope: LafsEnvelope<T>) => envelope is LafsError
```

**Parameters**

| Name       | Type              | Description            |
| ---------- | ----------------- | ---------------------- |
| `envelope` | `LafsEnvelope<T>` | The envelope to check. |

**Returns** — `true` if the envelope represents a failed operation.

**Example**

```ts theme={null}
const result: LafsEnvelope<Task[]> = await fetchTasks();
if (isLafsError(result)) {
  console.error(result.error.message);
}
```

## isGatewayEnvelope(envelope)

Type guard for gateway responses (has \_meta).

**Signature**

```typescript theme={null}
<T>(envelope: CleoResponse<T>) => envelope is GatewayEnvelope<T>
```

**Parameters**

| Name       | Type              | Description            |
| ---------- | ----------------- | ---------------------- |
| `envelope` | `CleoResponse<T>` | The response to check. |

**Returns** — `true` if the response includes gateway metadata.

**Example**

```ts theme={null}
const response: CleoResponse<Task> = await handleRequest();
if (isGatewayEnvelope(response)) {
  console.log(response._meta.gateway);
}
```
