Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
71814a8
add context
ENvironmentSet Jul 7, 2026
33e0805
docs: add FEP-2548 mechanism design run plan, extend domain glossary
ENvironmentSet Jul 7, 2026
16e6a5c
docs: add FEP-2548 init/load distinction mechanism design
ENvironmentSet Jul 7, 2026
fb20c55
docs: revise FEP-2548 mechanism — drop dedicated init-interception ho…
ENvironmentSet Jul 7, 2026
0006fb3
add impl plan
ENvironmentSet Jul 7, 2026
a353f51
opus 4.8
ENvironmentSet Jul 7, 2026
3100588
test(core): add create/load mechanism harness + §3 type-signature stubs
ENvironmentSet Jul 7, 2026
d83506e
feat(core): implement create/load distinction mechanism
ENvironmentSet Jul 7, 2026
fc9fbce
fix(core): allow undefined/void return from provideSnapshot (C1#8)
ENvironmentSet Jul 8, 2026
66705fe
docs(changeset): fix hook signature typos, cause.kind notation, and s…
ENvironmentSet Jul 8, 2026
86351e2
test(core): pin raw propagation when provideSnapshot/onLoadError thro…
ENvironmentSet Jul 8, 2026
ac5c7ba
test(core): verify recover:create resumes the full create pipeline (C…
ENvironmentSet Jul 8, 2026
2268a24
test(core): pin load contract edges — non-create recovery rethrows, d…
ENvironmentSet Jul 8, 2026
62cef36
test(core): cover pop/step navigation after load (C2#3)
ENvironmentSet Jul 8, 2026
382a209
test(core): load postcondition for a snapshot captured while paused (…
ENvironmentSet Jul 8, 2026
ab22fe4
chore(core): trim HOW-restating comments to WHY-only (C1#11)
ENvironmentSet Jul 8, 2026
6bb72db
fix(core): rebase snapshot events into the window after static events…
ENvironmentSet Jul 8, 2026
8cc091b
plans
ENvironmentSet Jul 8, 2026
b4be141
refactor(core): rename SnapshotLoadError cause kinds to read as the s…
ENvironmentSet Jul 9, 2026
1a74f70
refactor(core): promote onInit's initializedBy string to an initInfo …
ENvironmentSet Jul 9, 2026
c0f3d32
feat(core): run the overrideInitialEvents chain on the load path with…
ENvironmentSet Jul 9, 2026
1ff0b48
refactor(core): drop the dead setPrototypeOf workaround in SnapshotLo…
ENvironmentSet Jul 9, 2026
7929873
refactor(core): fold the load registration check into validateEvents …
ENvironmentSet Jul 9, 2026
7f2c7b2
refactor(core): rebase static events with the navigation events and d…
ENvironmentSet Jul 9, 2026
c382340
fix(core): capture only committed navigation in captureSnapshot (revi…
ENvironmentSet Jul 9, 2026
c03e3ee
fix(core): drop a whole uncommitted activity's events when capturing,…
ENvironmentSet Jul 9, 2026
4c11f32
docs(core): note the unified registration check now covers Replaced (…
ENvironmentSet Jul 9, 2026
6068107
fix(core): capture every recorded navigation event, excluding only un…
ENvironmentSet Jul 10, 2026
bd58f04
feat(core): carry every runtime event in snapshots, excluding only st…
ENvironmentSet Jul 10, 2026
1c58ead
feat(core): replay snapshot events at their recorded dates, backdatin…
ENvironmentSet Jul 10, 2026
5dbf3d7
refactor(core): type SNAPSHOT_EVENT_NAMES members as SnapshotEvent na…
ENvironmentSet Jul 11, 2026
ec02f6b
fix(core): carry the raw replay error as incompatible-events detail, …
ENvironmentSet Jul 11, 2026
135f2c7
refactor(core): drop needless optional chaining on snapshot.$schema (…
ENvironmentSet Jul 11, 2026
88f41c5
refactor(core)!: rename StackflowPluginHook to StackflowPluginInitHoo…
ENvironmentSet Jul 11, 2026
5e0b1ba
refactor(core)!: narrow provideSnapshot return to StackSnapshot | nul…
ENvironmentSet Jul 11, 2026
7e45c37
refactor(core)!: make onLoadError choose recover/propagate via an exp…
ENvironmentSet Jul 11, 2026
d3efb15
refactor(core): split initial events by isSnapshotEvent (non-static/s…
ENvironmentSet Jul 11, 2026
79ddc00
refactor(core)!: rename onInitialActivityIgnored's stale initialPushe…
ENvironmentSet Jul 11, 2026
9653237
refactor(core): stop normalizing in captureSnapshot; export the log a…
ENvironmentSet Jul 11, 2026
f15daac
style(core): apply biome formatting to isSnapshotEvent/StackflowPlugi…
ENvironmentSet Jul 11, 2026
4d4532d
docs(core): fix two spec comments that still claimed capture normaliz…
ENvironmentSet Jul 11, 2026
3c784df
docs(core): describe provideSnapshot/onLoadError as new additive hook…
ENvironmentSet Jul 11, 2026
382fb08
Merge branch 'main' into feature/fep-2548
ENvironmentSet Jul 11, 2026
aef6460
delete docs
ENvironmentSet Jul 11, 2026
69646d9
test(core): extract FEP-2548 test suites into a stacked PR
ENvironmentSet Jul 11, 2026
fd12207
docs(core): condense FEP-2548 changeset to the change surface only
ENvironmentSet Jul 11, 2026
e8cb83d
docs(core): name the added APIs and broken types in the FEP-2548 chan…
ENvironmentSet Jul 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .changeset/fep-2548-create-load-distinction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
"@stackflow/core": major
---

Distinguish how a stack is initialized — created fresh (`create`) or restored from a snapshot (`load`) — and add the surface a snapshot round-trip needs: `StackSnapshot`, `actions.captureSnapshot()`, the `provideSnapshot` / `onLoadError` plugin hooks, and `initInfo` on `onInit`. Runtime behavior is unchanged when no snapshot is provided; the breaks are type-level only — the `StackflowPluginHook` → `StackflowPluginInitHook` rename, plus new required members on `StackflowActions` and on the `onInit` / `overrideInitialEvents` hook signatures — hence the major.

**Added**

- `StackSnapshot` (with the `SnapshotEvent` / `NavigationEvent` unions) — a plain-data record of the events a stack recorded at runtime — plus `SnapshotLoadError`.
- `actions.captureSnapshot()` to export that record, and the `provideSnapshot` / `onLoadError` plugin hooks to supply a snapshot at creation time and route a failed load.
- `initInfo: { kind: "create" | "load" }` on `onInit`; `overrideInitialEvents` now runs on the load path too and receives the same `initInfo`.

**Changed**

- Renamed the `StackflowPluginHook` type to `StackflowPluginInitHook`.
- `StackflowActions` now requires `captureSnapshot`, the `onInit` / `overrideInitialEvents` hook arguments now require `initInfo`, and `overrideInitialEvents`' parameter widens from `(PushedEvent | StepPushedEvent)[]` to `SnapshotEvent[]` — hand-written mocks and wrap-and-forward plugins must adopt these.
- `validateEvents` now also rejects a `Replaced` that names an unregistered activity (does not fire in config-first usage).
39 changes: 39 additions & 0 deletions core/src/SnapshotLoadError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* Why a snapshot load failed, in three kinds that read as the
* snapshot → events → stack pipeline:
* - `unrecognized-snapshot`: the value is not a snapshot structure core
* recognizes — a catch-all over the structural checks (`$schema` mismatch,
* `events` not being an array, or an item that is not one of the six
* navigation events, including a missing `id`/`name`). `detail` names the
* check that failed.
* - `incompatible-events`: the structure is recognized but the event sequence
* is incompatible with the current config (e.g. it materializes an
* unregistered activity) — a relational failure against the config, not a
* defect intrinsic to the events. `detail` is the raw error thrown by the
* replay machinery (`aggregate`/`validateEvents`), carried unflattened —
* hence `unknown`. Narrowing it to the offending events would drop the
* thrown error's call stack, which is the useful diagnostic here.
* - `empty-stack`: replay succeeded but left zero activities in an enter
* state, so there is nothing to show. Note the condition is "zero
* enter-state activities", not an empty `activities` array — exit-done
* activities may remain.
*/
export type SnapshotLoadErrorCause =
| { kind: "unrecognized-snapshot"; detail: string }
| { kind: "incompatible-events"; detail: unknown }
Comment thread
ENvironmentSet marked this conversation as resolved.
| { kind: "empty-stack" };

/**
* Thrown when loading a provided snapshot fails. Routed to the providing
* plugin's `onLoadError` first (R5); if unrecovered, thrown out of
* `makeCoreStore` (R4).
*/
export class SnapshotLoadError extends Error {
cause: SnapshotLoadErrorCause;

constructor(cause: SnapshotLoadErrorCause, message?: string) {
super(message ?? `failed to load snapshot: ${cause.kind}`);
this.name = "SnapshotLoadError";
this.cause = cause;
}
}
53 changes: 53 additions & 0 deletions core/src/StackSnapshot.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import type {
PausedEvent,
PoppedEvent,
PushedEvent,
ReplacedEvent,
ResumedEvent,
StepPoppedEvent,
StepPushedEvent,
StepReplacedEvent,
} from "./event-types";

/**
* The six navigation events — a subset union of the existing domain event
* types (no new vocabulary is introduced).
*/
export type NavigationEvent =
| PushedEvent
| ReplacedEvent
| PoppedEvent
| StepPushedEvent
| StepReplacedEvent
| StepPoppedEvent;

/**
* The events a snapshot carries: every domain event except the static ones
* (`Initialized`, `ActivityRegistered`). Statics are config/source-grade
* information — they may legitimately differ after a reload, so the current
* config re-derives them at load time instead of trusting the snapshot.
* Everything the stack recorded at runtime, `Paused`/`Resumed` included, is
* exported as-is.
*/
export type SnapshotEvent = NavigationEvent | PausedEvent | ResumedEvent;

/**
* A plain-data value whose structure is owned by core. Encoding to a
* persistence medium (codec) is the consumer's responsibility.
*/
export type StackSnapshot = {
/**
* Structural discriminator tag. A mismatch fails the load as
* `SnapshotLoadError` — version migration is a non-goal.
*/
$schema: "stackflow.snapshot.v1";

/**
* The event log as recorded, minus the static events the current config
* re-derives at load time. Left in recorded order — load replays through
* `aggregate`, which sorts by eventDate and dedupes by id. Whether to
* capture a paused stack is the caller's choice — core exports the stack it
* is asked about, pause state and all.
*/
events: SnapshotEvent[];
};
1 change: 1 addition & 0 deletions core/src/event-utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from "./dispatchEvent";
export * from "./filterEvents";
export * from "./isSnapshotEvent";
export * from "./makeEvent";
export * from "./validateEvents";
36 changes: 36 additions & 0 deletions core/src/event-utils/isSnapshotEvent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type { DomainEvent } from "../event-types";
import type { SnapshotEvent } from "../StackSnapshot";

/**
* The events a snapshot carries — every domain event except the static ones
* (`Initialized`, `ActivityRegistered`), which the current config re-derives
* at load time. Single source of truth for the capture-side filter and the
* load-side structure check.
*
* Its members are constrained to `SnapshotEvent["name"]` at construction (a
* typo or a non-snapshot name fails to compile), but the set itself is typed
* `ReadonlySet<string>` so both membership checks below can pass a plain event
* name — a `DomainEvent["name"]` or a runtime `string` — without a cast.
*/
const SNAPSHOT_EVENT_NAMES: ReadonlySet<string> = new Set<
SnapshotEvent["name"]
>([
"Pushed",
"Replaced",
"Popped",
"StepPushed",
"StepReplaced",
"StepPopped",
"Paused",
"Resumed",
]);

/** Whether an event is one a snapshot carries (i.e. not a static event). */
export function isSnapshotEvent(event: DomainEvent): event is SnapshotEvent {
return SNAPSHOT_EVENT_NAMES.has(event.name);
}

/** Whether a value is the name of an event a snapshot carries. */
export function isSnapshotEventName(name: unknown): boolean {
return typeof name === "string" && SNAPSHOT_EVENT_NAMES.has(name);
}
10 changes: 8 additions & 2 deletions core/src/event-utils/validateEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,15 @@ export function validateEvents(events: DomainEvent[]) {
activityRegisteredEvents.map((e) => e.activityName),
);

const pushedEvents = filterEvents(events, "Pushed");
// Both Pushed and Replaced materialize an activity by name, so both must
// name a registered activity — checking only Pushed left Replaced an
// asymmetric gap.
const materializingEvents = [
...filterEvents(events, "Pushed"),
...filterEvents(events, "Replaced"),
];

if (pushedEvents.some((e) => !registeredActivityNames.has(e.activityName))) {
if (materializingEvents.some((e) => !registeredActivityNames.has(e.activityName))) {
throw new Error("the corresponding activity does not exist");
}
}
6 changes: 6 additions & 0 deletions core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,17 @@ export { DispatchEvent, makeEvent } from "./event-utils";
export * from "./interfaces";
export * from "./makeCoreStore";
export { produceEffects } from "./produceEffects";
export { SnapshotLoadError, SnapshotLoadErrorCause } from "./SnapshotLoadError";
export {
Activity,
ActivityStep,
ActivityTransitionState,
RegisteredActivity,
Stack,
} from "./Stack";
export {
NavigationEvent,
SnapshotEvent,
StackSnapshot,
} from "./StackSnapshot";
export { id } from "./utils";
7 changes: 7 additions & 0 deletions core/src/interfaces/StackflowActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,20 @@ import type {
import type { BaseDomainEvent } from "../event-types/_base";
import type { DispatchEvent } from "../event-utils";
import type { Stack } from "../Stack";
import type { StackSnapshot } from "../StackSnapshot";

export type StackflowActions = {
/**
* Get current stack state
*/
getStack: () => Stack;

/**
* Capture the current navigation history as a snapshot. Callable from any
* hook, at any time; normalizes the event log into navigation events.
*/
captureSnapshot: () => StackSnapshot;

/**
* Dispatch new event to the core without pre-effect hooks
*/
Expand Down
58 changes: 53 additions & 5 deletions core/src/interfaces/StackflowPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@ import type {
StepReplacedEvent,
} from "../event-types";
import type { BaseDomainEvent } from "../event-types/_base";
import type { SnapshotLoadError } from "../SnapshotLoadError";
import type { SnapshotEvent, StackSnapshot } from "../StackSnapshot";
import type {
StackflowPluginHook,
StackflowPluginInitHook,
StackflowPluginPostEffectHook,
StackflowPluginPreEffectHook,
StackInitInfo,
} from "./StackflowPluginHook";

export type StackflowPlugin = () => {
Expand All @@ -24,7 +27,7 @@ export type StackflowPlugin = () => {
/**
* Called when the <Stack /> component is initialized for the first time
*/
onInit?: StackflowPluginHook;
onInit?: StackflowPluginInitHook;

/**
* Called before the `push()` function of `useActions()` is called and the corresponding signal is delivered to the core
Expand Down Expand Up @@ -128,10 +131,55 @@ export type StackflowPlugin = () => {
onChanged?: StackflowPluginPostEffectHook<"%SOMETHING_CHANGED%">;

/**
* Specifies the first `PushedEvent`, `StepPushedEvent` (Overrides the `initialActivity` option specified in the `stackflow()` function)
* Intercept the event sequence a stack is built from. Chained across
* plugins in array order — each plugin receives the previous one's
* return. `initInfo` says which path is running, in the same record shape
* `onInit` receives:
* - `{ kind: "create" }`: `initialEvents` holds the initial entry events
* (`PushedEvent`/`StepPushedEvent`, from the `initialActivity` option or
* earlier plugins). The return decides the initial entries.
* - `{ kind: "load" }`: `initialEvents` holds the provided snapshot's full
* replay sequence (structure-validated, original field values) —
* `Paused`/`Resumed` included when the snapshot recorded them. The
* return is adopted as the replay sequence with its event dates
* preserved: core never re-dates it, so replay order follows the
* recorded dates and a guarantee like "every restored activity is
* settled" is this hook's to provide, by re-dating the events itself.
* The return then runs through the same load validation as the snapshot
* itself (activity registration, replay, at least one enter-state
* activity), so a failing return surfaces as a `SnapshotLoadError` to
* the snapshot provider. Reshaping the sequence reshapes the
* reconstructed navigation history — a plugin with no load policy must
* return `initialEvents` unchanged.
*/
overrideInitialEvents?: (args: {
initialEvents: (PushedEvent | StepPushedEvent)[];
initialEvents: SnapshotEvent[];
initialContext: any;
}) => (PushedEvent | StepPushedEvent)[];
initInfo: StackInitInfo;
}) => SnapshotEvent[];

/**
* Called synchronously at stack creation time to provide a snapshot to load
* from. Returning `null` means "nothing to provide" and the create path
* continues. If more than one plugin returns a non-null snapshot, core
* throws a creation error naming the conflicting keys — it does not
* arbitrate (R9).
*/
provideSnapshot?: (args: { initialContext: any }) => StackSnapshot | null;

/**
* Called — only on the plugin that provided the failing snapshot (R5) — when
* that snapshot fails to load. Returning `{ policy: "recover" }` resumes the
* create path without re-polling; returning `{ policy: "propagate" }` (or
* having no handler) throws the `SnapshotLoadError` out of `makeCoreStore`
* (R4). Both outcomes share the `policy` discriminant so a handler chooses
* recover vs propagate explicitly, rather than propagating by falling off
* the end. `"recover"` currently resumes the sole create path; a future
* recovery target would extend this branch (e.g. an added field) rather
* than the discriminant.
*/
onLoadError?: (args: {
error: SnapshotLoadError;
initialContext: any;
}) => { policy: "recover" } | { policy: "propagate" };
};
14 changes: 13 additions & 1 deletion core/src/interfaces/StackflowPluginHook.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
import type { Effect } from "../Effect";
import type { StackflowActions } from "./StackflowActions";

export type StackflowPluginHook = (args: { actions: StackflowActions }) => void;
/**
* Which path created this stack — `{ kind: "create" }` (fresh) or
* `{ kind: "load" }` (restored from a snapshot). A one-shot signal that
* leaves no trace on the stack. A record rather than a bare string so
* per-path fields can be added later without breaking hook signatures.
* `onInit` and `overrideInitialEvents` receive the signal in this same shape.
*/
export type StackInitInfo = { kind: "create" | "load" };

export type StackflowPluginInitHook = (args: {
actions: StackflowActions;
initInfo: StackInitInfo;
}) => void;

export type StackflowPluginPreEffectHook<T> = (args: {
actionParams: T;
Expand Down
Loading
Loading