Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 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
9e80959
test(core): add FEP-2548 create/load distinction test suites
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
33 changes: 33 additions & 0 deletions .changeset/fep-2548-create-load-distinction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
---
"@stackflow/core": major
---

Distinguish how a stack is created — freshly (`create`) or restored from a snapshot (`load`) — and add the surface a snapshot round-trip (capture → persist → load) needs, through additive plugin contracts. The addition is runtime-additive — a store with no snapshot provider behaves exactly as before — but at the type level, hand-written `StackflowActions` mocks and code that constructs `onInit` hook arguments (wrap-and-forward plugins) must add the new required members (`captureSnapshot`, `initInfo`), and `overrideInitialEvents` implementations that explicitly annotate their parameter with the previous `(PushedEvent | StepPushedEvent)[]` shape must widen it to `SnapshotEvent[]` (implementations with inferred parameters are unaffected). One more type-level break versus the last release: the exported hook type `StackflowPluginHook` is renamed to `StackflowPluginInitHook` (the `onInit` hook type). The `provideSnapshot` and `onLoadError` hooks below are new additive surface — they land in their final shape (`StackSnapshot | null` and `{ policy: "recover" } | { policy: "propagate" }`), not a change to any published type. Hence a major release.

- `StackSnapshot` (and the `SnapshotEvent` union) — a plain-data value, owned by core, that carries every event the stack recorded at runtime — the six navigation events plus `Paused`/`Resumed` — excluding only the static events (`Initialized`, `ActivityRegistered`), which are config-grade information the current config re-derives at load time. Encoding to a persistence medium (codec) is the consumer's responsibility.
- `actions.captureSnapshot()` — export the recorded event log as-is (statics excluded); callable from any hook, at any time. Core holds no opinion about when a snapshot is meaningful: capturing a paused stack yields a snapshot that restores a paused stack, and whether to capture at such a moment is the caller's timing choice.
- `provideSnapshot?({ initialContext })` plugin hook — called synchronously at creation time to supply a snapshot to load from. Returning `null` keeps the create path. If more than one plugin supplies a snapshot, core throws a creation error naming the conflicting keys rather than arbitrating.
- `onLoadError?({ error, initialContext })` plugin hook + `SnapshotLoadError` (with a `cause.kind` of `"unrecognized-snapshot"`, `"incompatible-events"`, or `"empty-stack"`) — a failed load is routed only to the plugin that provided the snapshot. Returning `{ policy: "recover" }` resumes the create path; returning `{ policy: "propagate" }` (or having no handler) throws the error out of `makeCoreStore`.
- `onInit` now receives `initInfo: { kind: "create" | "load" }` — a one-shot signal that leaves no trace on the stack state or event log. It is a record rather than a bare string so per-path fields can be added later without breaking the hook signature.
- `overrideInitialEvents` now runs on the load path too, and its signature widens to `SnapshotEvent[]` in and out, with a new `initInfo` argument (the same record `onInit` receives). On create it keeps deciding the initial entries, as before. On load it receives the provided snapshot's full replay sequence (`Paused`/`Resumed` included when the snapshot recorded them), and its return is adopted as the replay sequence with its event dates preserved — core never re-dates it, so 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, so a failing return surfaces as a `SnapshotLoadError` to the provider. Reshaping the sequence reshapes the reconstructed navigation history: a plugin with no load policy must return `initialEvents` unchanged, and plugins written before this signal that fabricate initial events (e.g. from a URL) should early-return on `initInfo.kind === "load"`.

```ts
const persisterPlugin = ({ storage, codec }) => () => ({
key: "persister",
onChanged({ actions }) {
storage.write(codec.encode(actions.captureSnapshot()));
},
provideSnapshot() {
const raw = storage.read();
return raw ? codec.decode(raw) : null;
},
onLoadError({ error }) {
storage.remove();
return { policy: "recover" };
},
});
```

A load reconstructs the stack by replaying the snapshot's events — as passed through the plugins' `overrideInitialEvents` chain — through the existing aggregate machinery, preserving them byte-for-byte, `eventDate` included: the recorded dates are the replay truth, so a stack captured mid-transition restores mid-transition and a paused stack restores paused, and capture∘load is an identity on the snapshot events. Static information (transition duration, the registered-activity set) is re-derived from the current config, and only those static events are re-dated — to just before the earliest replayed event, so registration and transition duration are in place before any snapshot event applies. Core imposes no settling or date normalization on the replay; a supplier or plugin that wants a fully-settled restore (or protection from a capture clock that ran ahead) re-dates the sequence in `overrideInitialEvents`. No new domain events or stack state properties are introduced.

The snapshot load's registration check is unified into `validateEvents` (run by `aggregate` on every path), which now rejects a `Replaced` that materializes an unregistered activity, matching its long-standing check for `Pushed`. In config-first usage a replace only targets registered activities, so this added check does not fire on the live path.
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 }
| { 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[];
};
Loading
Loading