# `@signalsafe/simulator-core`

[Repository](https://github.com/SignalSafeSoftware/simulator-core) · [Live shared device example](https://signalsafesoftware.github.io/simulator-device/) · [Package links and examples](docs/links.md)

Source, registry releases and unpublished review artifacts are tracked separately. See [current summary](docs/current-state-summary.md), [changelog](CHANGELOG.md) and [coordinated release preparation](docs/release-2026-11-10.md). Publication status and installed host versions are tracked separately.

Latest unpublished work: [November 15 summary](docs/current-state-summary.md#unpublished-follow-up--2026-11-15) and [unreleased changes](CHANGELOG.md). Review artifact `0.7.3-mail-ui.0` is local only; it does not replace registry pins.

## Historical coordinated release — approved 2026-10-21

| Package | Prepared version | Required simulator dependencies |
| --- | --- | --- |
| `@signalsafe/simulator-core` | `0.7.1` | none |
| `@signalsafe/simulator-theme-bootstrap` | `0.13.1` | none |
| `@signalsafe/simulator-react` | `0.21.1` | core `0.7.1`; optional default theme `^0.13.1` |
| `@signalsafe/simulator-device` | `0.21.1` | core `0.7.1`, React `0.21.1`, theme `0.13.1` (exact) |

These compatible patches preserve the existing public runtime API and shared UI.
React and the default theme must be adopted together: the corrected frame markup
requires the matching CSS. A custom theme remains an explicit host responsibility.
The optional theme peer does not install or require the default theme for unstyled
integrations. Node runtime support remains `>=19.0.0`; build tools use Node 22/24.

Publish core and theme first, then React, then device, only after explicit approval
and successful gated tag workflows. Download and verify each upstream registry
artifact before refreshing downstream Yarn locks and the device demo npm lock.
Future registry integrity values must never be fabricated. Before upstream
publication, coherent packed-artifact installs provide candidate evidence only;
frozen standalone registry installs remain a separate release gate.

Existing local host archives retain their recorded provenance until the approved
registry artifacts pass all host checks. Historical release notes below describe
their original checkpoints and do not authorize publication or host replacement.

Current source and planned customer-subdomain impact: [current-state summary](docs/current-state-summary.md).

Headless **TreeSpec session runtime**: step scenarios, accumulate scores, resolve outcomes — no UI, React, routing, or transport.

| | |
|---|---|
| **npm** | `@signalsafe/simulator-core` |
| **GitHub** | [SignalSafeSoftware/simulator-core](https://github.com/SignalSafeSoftware/simulator-core) |
| **Depends on** | `@signalsafe/tree-spec` |

## What this package does

- Parse and validate runtime-ready **`TreeSpecWire`** payloads.
- Run an immutable **session state machine**: `createInitialTreeSpecSession` → `dispatchTreeSpecChoice`.
- Resolve **node views**, **score deltas**, and **micro-feedback** for renderers.

## What this package does not do

- React components, device shells, or Bootstrap UI — use `@signalsafe/simulator-react`.
- HTTP APIs, authentication, routing, or persistence — host app owns transport and storage.
- Deep content security review — treat wire JSON as trusted authoring content unless the host validates it first.

## State lifecycle

1. **`parseTreeSpecRuntime(wire)`** / **`treeSpecRuntimeIssues(wire)`** — validate before play.
2. **`createInitialTreeSpecSession(wire)`** — initial `currentNodeId`, empty history, zeroed scores.
3. **`dispatchTreeSpecChoice(state, nodeId, choiceId)`** — returns `continue` (next node + delta) or `ended` (terminal outcome).
4. Session **`history`** is append-only; **`cumulativeScore`** merges deltas via `mergeScoreDelta`.
5. **`serializeTreeSpecSession`** stores only the versioned choice history; **`restoreTreeSpecSession`** validates the snapshot and replays it through the dispatcher.

## Decision / transition flow

For each choice, the runtime finds the matching transition (`findTransitionForChoice`), applies optional **score delta**, resolves **feedback** (transition overrides choice), and either lands on the next node or a terminal **outcome** when `to` is END.

## Install

```bash
npm install @signalsafe/simulator-core @signalsafe/tree-spec
```

`simulator-core` depends on `@signalsafe/tree-spec` for the wire format and shared types.

## Repository

Source code and issues are available at:
https://github.com/SignalSafeSoftware/simulator-core

## What It Provides

- Parse and validate a runtime-ready `TreeSpecWire`
- Create an initial session state
- Dispatch a choice from the current node
- Accumulate score deltas across the session
- Resolve node views for rendering
- Return transition-level or choice-level micro-feedback

## Quick Start

```ts
import { END_NODE_ID, type TreeSpecWire } from "@signalsafe/tree-spec";
import { createInitialTreeSpecSession } from '@signalsafe/simulator-core/session';
import { dispatchTreeSpecChoice } from '@signalsafe/simulator-core/session';
import { getTreeSpecNodeView } from '@signalsafe/simulator-core/nodeView';

const wire: TreeSpecWire = {
    start_node: "start",
    nodes: {
        start: {
            type: "prompt",
            prompt: "Open the attachment?",
            choices: [{ id: "open", label: "Open it" }],
        },
    },
    transitions: [
        {
            from: ["start", "open"],
            to: END_NODE_ID,
            outcome: "compromised",
            delta: { total: -10, verification: -2 },
        },
    ],
};

const session = createInitialTreeSpecSession(wire);
const currentNode = getTreeSpecNodeView(session.spec, session.currentNodeId);

// Expected output:
// Open the attachment?
console.log(currentNode.prompt);

// Expected output:
// ["Open it"]
console.log(currentNode.choices.map((choice) => choice.label));

const result = dispatchTreeSpecChoice(session, "start", "open");
if (result.status !== "ended") {
    throw new Error("Expected a terminal outcome.");
}

// Expected output:
// compromised
console.log(result.outcome);

// Expected output:
// {
//     total: -10,
//     awareness: 0,
//     verification: -2,
//     impulse_control: 0,
//     damage_containment: 0,
// }
console.log(result.state.cumulativeScore);
```

## Common Flows

### Validate a wire payload before starting a session

Use `treeSpecRuntimeIssues()` when you want a non-throwing validation pass that returns user-facing issues. Use `parseTreeSpecRuntime()` when invalid payloads should fail immediately.

```ts
import { parseTreeSpecRuntime } from '@signalsafe/simulator-core/wire';
import { treeSpecRuntimeIssues } from '@signalsafe/simulator-core/session';
import type { TreeSpecWire } from "@signalsafe/tree-spec";

const raw = someUnknownValue as TreeSpecWire;
const issues = treeSpecRuntimeIssues(raw);

if (issues.length > 0) {
    console.error(issues);
} else {
    const spec = parseTreeSpecRuntime(raw);
    console.log(spec.start_node);
}
```

### Walk a multi-step session

```ts
import { END_NODE_ID, type TreeSpecWire } from "@signalsafe/tree-spec";
import { createInitialTreeSpecSession } from '@signalsafe/simulator-core/session';
import { dispatchTreeSpecChoice } from '@signalsafe/simulator-core/session';
import { treeSpecRuntimeIssues } from '@signalsafe/simulator-core/session';

const wire: TreeSpecWire = {
    start_node: "start",
    nodes: {
        start: {
            type: "prompt",
            prompt: "A caller asks for a password reset code. What do you do?",
            choices: [
                {
                    id: "verify",
                    label: "Verify their identity first",
                    feedback: {
                        key: "good-check",
                        title: "Good instinct",
                        takeaway:
                            "Ask for a trusted callback or verified channel before sharing account details.",
                    },
                },
            ],
        },
        wrap_up: {
            type: "info",
            prompt: "You prevented an account takeover.",
            choices: [{ id: "done", label: "Finish" }],
            render_hints: { layout: "callout" },
        },
    },
    transitions: [
        {
            from: ["start", "verify"],
            to: "wrap_up",
            delta: { total: 5, verification: 3 },
        },
        {
            from: ["wrap_up", "done"],
            to: END_NODE_ID,
            outcome: "safe",
            feedback: {
                key: "complete",
                title: "Wrap-up",
                body: "Document the interaction and escalate if the request still looks suspicious.",
            },
        },
    ],
};

const runtimeIssues = treeSpecRuntimeIssues(wire);
if (runtimeIssues.length > 0) {
    throw new Error(runtimeIssues.map((issue) => issue.message).join("\n"));
}

const firstState = createInitialTreeSpecSession(wire);
const firstStep = dispatchTreeSpecChoice(firstState, "start", "verify");

if (firstStep.status !== "continue") {
    throw new Error("Expected an intermediate step.");
}

// Expected output:
// {
//     key: "good-check",
//     title: "Good instinct",
//     takeaway: "Ask for a trusted callback or verified channel before sharing account details.",
// }
console.log(firstStep.feedback);

// Expected output:
// {
//     layout: "callout",
// }
console.log(firstStep.node.render_hints);

const finalStep = dispatchTreeSpecChoice(firstStep.state, "wrap_up", "done");
if (finalStep.status !== "ended") {
    throw new Error("Expected a terminal step.");
}

// Expected output:
// safe
console.log(finalStep.outcome);

// Expected output:
// {
//     key: "complete",
//     title: "Wrap-up",
//     body: "Document the interaction and escalate if the request still looks suspicious.",
// }
console.log(finalStep.feedback);
```

### Inspect the current node and raw choices

```ts
import { getTreeSpecNodeView } from '@signalsafe/simulator-core/nodeView';
import { getWireChoices } from '@signalsafe/simulator-core/wire';
import { parseTreeSpecRuntime } from '@signalsafe/simulator-core/wire';

const spec = parseTreeSpecRuntime(wire);
const currentNode = getTreeSpecNodeView(spec, spec.start_node);
const rawChoices = getWireChoices(spec.nodes[spec.start_node]);

console.log(currentNode.render_hints);
console.log(rawChoices.map((choice) => choice.label));
```

`getTreeSpecNodeView()` returns the simplified shape most renderers need:

- `id`
- `type`
- `prompt`
- `choices`
- `render_hints`

`getWireChoices()` returns the original choice array from the source node so you can inspect metadata that is not present on `NodeView`.

### Session snapshots

Snapshots are graph-only and versioned:

```ts
import { restoreTreeSpecSession } from '@signalsafe/simulator-core/session';
import { serializeTreeSpecSession } from '@signalsafe/simulator-core/session';

const snapshot = serializeTreeSpecSession(session);
const restored = restoreTreeSpecSession(wire, snapshot);
```

The snapshot contains `{ version: 1, history }`. Derived node, score, and
terminal state are intentionally not trusted; restoration derives them by
replaying each recorded choice through `dispatchTreeSpecChoice`. Malformed
snapshots and invalid replay histories raise `TreeSpecRuntimeError`.

## Core API

### Session Lifecycle

- `createInitialTreeSpecSession(wire)`: validates the wire payload and creates initial immutable state
- `dispatchTreeSpecChoice(state, nodeId, choiceId)`: applies one choice from the current node and returns either a continue result or an ended result
- `serializeTreeSpecSession(state)`: creates a versioned, graph-only replay snapshot
- `restoreTreeSpecSession(wire, snapshot)`: validates and replays a snapshot into a fresh session
- `treeSpecRuntimeIssues(wire)`: returns structural/runtime issues without throwing

### Runtime Helpers

- `parseTreeSpecRuntime(wire)`: validates and normalizes the runtime payload
- `getTreeSpecNodeView(spec, nodeId)`: returns a renderer-friendly node view
- `findTransitionForChoice(spec, nodeId, choiceId)`: returns the matching transition for a selected choice
- `getWireChoices(node)`: returns the raw choices/options array from a node
- `resolveFeedbackForTransition(spec, nodeId, choiceId, transitionFeedback)`: resolves transition feedback first, then falls back to choice feedback

### Utility Exports

- `emptyScoreDelta()`
- `mergeScoreDelta()`
- `TreeSpecRuntimeError`

## Error messages and audiences

Thrown errors and `treeSpecRuntimeIssues()` messages are **developer/author diagnostics** (missing nodes, invalid wire shape, etc.). They are precise so editors and tests can act on them.

**Do not** surface raw `TreeSpecRuntimeError.message` text to learners. Host apps and `@signalsafe/simulator-react` map runtime/render failures to generic learner copy; see [simulator-react/docs/ERROR_BOUNDARIES.md](https://github.com/SignalSafeSoftware/simulator-react/blob/main/docs/ERROR_BOUNDARIES.md).

## Result Shapes

`dispatchTreeSpecChoice()` returns one of two result shapes:

- `status: 'continue'`: includes `state`, `node`, `appliedDelta`, and optional `feedback`
- `status: 'ended'`: includes `state`, `outcome`, `appliedDelta`, and optional `feedback`

Session state tracks:

- `currentNodeId`
- `cumulativeScore`
- `history`
- `spec`

## Example Files

- `docs/examples/basic-terminal-session.ts`: minimal terminal flow with an outcome and score delta
- `docs/examples/branching-feedback-session.ts`: multi-step flow with validation, intermediate feedback, render hints, and terminal feedback

Examples are documentation-focused TypeScript files. They illustrate package usage, but they are not part of the published runtime bundle.

## Development

Requires Node.js **>=19.0.0** (`engines.node`). CI runs checks, tests, and smoke on Node **22** and **24**; publish uses Node **24**.

`yarn build` uses `tsconfig.build.json` and resolves `@signalsafe/*` from `node_modules`. No sibling checkout is required for release validation.

```bash
yarn install
yarn build
yarn test
yarn typecheck
```

## Security

See [SECURITY.md](./SECURITY.md). Scenario payloads are **authoring/trusted content** unless the host validates them first. This library does not sandbox execution beyond stepping the scenario graph.

## Changelog and releases

- [CHANGELOG.md](./CHANGELOG.md)
- [RELEASING.md](docs/RELEASING.md)

## Historical release 0.3.2

Device contacts support `phone_numbers` and `email_addresses` containing `SimulatorContactValue` (`label`, original `value`, optional canonical `number`). Email details also preserve `bcc`. The runtime requires Node >=19.0.0 and TreeSpec ^0.4.1. See the changelog for the complete release record.

## Node runtime compatibility

The runtime requirement is Node >=19.0.0. Build, unit-test and coverage tools use
Node 22/24 (use Node 24.16+ locally). A separate CI job installs packed artifacts
with strict engine checks and tests runtime behavior on Node 19.0.0 and 19–24.

## Historical local app migration (0.4.1, release candidate)

- Add versioned local-device schemas, asset limits, record metadata, paged repository and `DeviceStore` host contracts.
- Add pure simulated mail transitions, recipient handling and strict browser action envelopes. Simulated send preserves draft identity and performs no network request.
- Add Zod 4 as a runtime dependency. Existing simulator records retain storage version 1; no data rewrite is required.

This version is prepared locally; it is not a claim of registry publication. See
[RELEASING.md](docs/RELEASING.md) for the coordinated release order. PhoneMe validates
normal packed artifacts; installed package files are never patched.

### Example verification

`npm run smoke:package` compiles and executes the repository examples in an
isolated consumer against the packed public API. The examples do not resolve
sibling source trees or private source imports. The shared React 18 local-app
workflow is in [simulator-device/docs/examples/local-apps](https://github.com/SignalSafeSoftware/simulator-device/tree/main/docs/examples/local-apps).

### Shared app identifiers

Import `SimulatorApp` and `isSimulatorApp` directly from `@signalsafe/simulator-core`.
Use `SimulatorApp.Phone`, `.Email`, `.Messages`, `.Internet`, and `.Home` for app IDs.
The frozen enum-style object also supplies the `SimulatorApp` string-union type; existing JSON
values stay compatible. Use `isSimulatorApp(value)` at untrusted boundaries and
`Object.values(SimulatorApp)` when enumerating all apps. Do not confuse app IDs with
channels (`sms`, `browser`, `contacts`), screen names, or contact/input field kinds.

See [AGENTS.md](./AGENTS.md) for module ownership and verification rules. Use the explicit declaring-module paths shown in the examples; root imports are not supported. Historical local archive adoption remains recorded by each host.

## Offline device contract export

The executable device rules also own the JSON Schema used by backend contract
checks. In this owning checkout, install locked dependencies and run `yarn build`,
then `node scripts/export-device-schema.mjs` or
`node scripts/export-device-fixtures.mjs`. The latter emits the same 304 public
validator cases used by DeliveryPlus. These are offline build tools; consumers
continue importing `validateDeviceJson` from its explicit public subpath. The
internal rule modules are not new public package exports. Runtime services do
not launch Node to validate requests.
