Repository navigation
Model lifecycles as explicit state machines: packages/machine and its checks - #110
Merged
Merged
Conversation
… checks @githubnext/projections-machine is a small, dependency-free state machine core for the hosts' and integrations' lifecycles: - defineMachine: states keyed by `kind`, events by `type`; every state lists a handler or `ignore` for every event, so an unconsidered case, a missing or extra state, or a transition without its state's data is a compile error. Handlers are pure and return the next state or emit(state, ...effects). - createActor: framework-agnostic. Effects and activities are data run by a runner per type, each in a generation that ends when superseded (an effect's `key`), when its state stops listing it, or when the actor stops; its signal aborts and its later events are dropped. after() is a timer activity. - useMachine (./react): one actor per component, started in a layout effect so changes made there render before paint. - explore (./testing): breadth-first walk of reachable states, with state and step invariants, the shortest path to a violation, and `complete` to fail on handlers never taken. npm run check:machines (a `tools check --fast` gate, and in CI) runs the machines/lifecycle ESLint rule (boolean refs, timers started in effects, setters called from timer or promise callbacks) against a committed baseline that may only shrink, and requires an explore test for every machine. docs/guides/state-machines.md explains when and how; AGENTS.md and CONTRIBUTING.md point to it. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
… alone With two or more effect types, inferring from the options too made each runner's effect never. The options now take NoInfer of the whole type, and the compile-time tests cover a machine with two effects. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This was referenced Nov 20, 2026
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical defects permit stale event delivery, resource leaks, incorrect subscriber ordering, and uncommitted React runner updates, while exploration and lifecycle checks can produce misleading results.
10 open issues
Discard queued events from invalidated generations · New Retain cleanup functions for all unkeyed effects · New Notify all subscribers before draining listener-enqueued events · New Publish runner options only after commit · New Track timer state across exploration paths · New Prevent baseline updates from increasing allowances · New Verify each machine is passed to an explore call · New Resolve the current error handler when reporting · New Treat unmatched machine-definition counts as zero · New Resolve deferred setters by scope binding · New
What changed in this PR
Introduces a shared state-machine foundation for host and integration lifecycles, preparing for the toolbar fit-plan migration described in #106 and #109.
Changes:
- Adds typed machine definitions, an actor runtime, a React adapter, and state-exploration utilities.
- Adds lifecycle linting and machine-test checks to local tooling and CI.
- Documents lifecycle modelling and registers the package in workspace and dependency-boundary configuration.
| File | Description |
|---|---|
tools/scripts/check-machines/lifecycle-rule.mjs |
Detects implicit lifecycle patterns. |
tools/scripts/check-machines/baseline.json |
Records existing lifecycle warnings. |
tools/scripts/check-machines.test.mjs |
Tests the lifecycle lint rule. |
tools/scripts/check-machines.mjs |
Checks warning counts and exploration-test presence. |
tools/scripts/check-boundaries/layers.mjs |
Registers machine dependencies in package layers. |
tools/scripts/check-boundaries.mjs |
Applies browser-portability checks to the package. |
tools/cli/src/lib/gates.ts |
Adds the fast machine-check gate. |
packages/machine/tsconfig.test.json |
Configures compile-time tests. |
packages/machine/tsconfig.json |
Configures package compilation. |
packages/machine/test/types.ts |
Tests definition and runner type constraints. |
packages/machine/test/testing.test.mjs |
Tests exploration and invariant reporting. |
packages/machine/test/actor.test.mjs |
Tests transitions and actor lifecycles. |
packages/machine/src/testing.ts |
Implements breadth-first state exploration. |
packages/machine/src/react.ts |
Adds the layout-timed React hook. |
packages/machine/src/machine.ts |
Defines typed machines, effects, and timers. |
packages/machine/src/index.ts |
Exports the core public API. |
packages/machine/src/actor.ts |
Implements event processing and generation management. |
packages/machine/README.md |
Summarizes the package API. |
packages/machine/package.json |
Declares exports, scripts, and optional React peer. |
packages/machine/LICENSE |
Adds the package’s MIT license. |
package.json |
Registers the workspace and check command. |
package-lock.json |
Records workspace and dependency metadata. |
eslint.config.js |
Enables package linting and lifecycle warnings. |
docs/README.md |
Links the state-machine guide. |
docs/guides/state-machines.md |
Explains modelling, execution, testing, and checks. |
CONTRIBUTING.md |
Documents the package and lifecycle invariant. |
AGENTS.md |
Adds lifecycle-modelling guidance. |
.github/workflows/ci.yml |
Runs machine checks in CI. |
Review effort: Balanced
…h; tighter checks From the code review on #110: - An event a generation sent waits in the queue with that generation, and is dropped if the generation ended before it was taken (two keyed effects' synchronous results, an activity removed meanwhile). - Every cleanup an unkeyed effect returns runs when the actor stops; they shared one slot. - Listeners hear a batch before the events they send are taken, so each hears every state in order. - useMachine publishes its runners and error handler in the commit phase, never a render React may discard, and always delegates errors to the current handler or the default reporter. - explore fires a timer once while states keep listing its key, as an actor does. - check-machines: `--update` never raises the baseline; a machine counts as explored only when passed to `explore(`; a module that only imports `defineMachine` passes; the lifecycle rule resolves a setter call to the `useState` binding instead of comparing names. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This was referenced Nov 20, 2026
…pend on it Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
agorischek
added a commit
that referenced
this pull request
Nov 21, 2026
…der and echoes by page (#118) * Model lifecycles as explicit state machines: packages/machine and its checks @githubnext/projections-machine is a small, dependency-free state machine core for the hosts' and integrations' lifecycles: - defineMachine: states keyed by `kind`, events by `type`; every state lists a handler or `ignore` for every event, so an unconsidered case, a missing or extra state, or a transition without its state's data is a compile error. Handlers are pure and return the next state or emit(state, ...effects). - createActor: framework-agnostic. Effects and activities are data run by a runner per type, each in a generation that ends when superseded (an effect's `key`), when its state stops listing it, or when the actor stops; its signal aborts and its later events are dropped. after() is a timer activity. - useMachine (./react): one actor per component, started in a layout effect so changes made there render before paint. - explore (./testing): breadth-first walk of reachable states, with state and step invariants, the shortest path to a violation, and `complete` to fail on handlers never taken. npm run check:machines (a `tools check --fast` gate, and in CI) runs the machines/lifecycle ESLint rule (boolean refs, timers started in effects, setters called from timer or promise callbacks) against a committed baseline that may only shrink, and requires an explore test for every machine. docs/guides/state-machines.md explains when and how; AGENTS.md and CONTRIBUTING.md point to it. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Machine: infer an actor's and an exploration's types from the machine alone With two or more effect types, inferring from the options too made each runner's effect never. The options now take NoInfer of the whole type, and the compile-time tests cover a machine with two effects. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Machine: drop stale queued events, run every cleanup, notify per batch; tighter checks From the code review on #110: - An event a generation sent waits in the queue with that generation, and is dropped if the generation ended before it was taken (two keyed effects' synchronous results, an activity removed meanwhile). - Every cleanup an unkeyed effect returns runs when the actor stops; they shared one slot. - Listeners hear a batch before the events they send are taken, so each hears every state in order. - useMachine publishes its runners and error handler in the commit phase, never a render React may discard, and always delegates errors to the current handler or the default reporter. - explore fires a timer once while states keep listing its key, as an actor does. - check-machines: `--update` never raises the baseline; a machine counts as explored only when passed to `explore(`; a module that only imports `defineMachine` passes; the lifecycle rule resolves a setter call to the `useState` binding instead of comparing names. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Agent viewer: the page's connection as a state machine; reports in order and echoes by page The viewer page kept its connection in a closure loop: a long poll, a `stopped` flag in the store, a two-second sleep that outlived unmounting, an `instance` check, and reports posted every 400 ms without waiting. That let an older report arrive after a newer one, which the server keeps as the newest. The page also took the generation after its own report for that report's echo. With two pages reporting at once, one page took the other's change for its own echo and skipped it. - `viewerConnection` (viewer/lifecycle.ts, on @githubnext/projections-machine): `live` (waiting past a generation), `stopped` (asking again every 2 s), `replaced` by another server, `ended`. The long poll and its retry delay are an activity per ask, so unmounting aborts both. The first state that shows a projection mounts the Inspector, once. - Reports go one at a time: the latest waits for the one in flight, and a resumed page reports again. - The server names the page whose report made a generation (`reportedBy`). A page takes only that for its echo (`echoes`), and every other page applies it. Tests cover each transition and the echo, and explore every connection state: one report in flight at most, the Inspector mounted once, and replaced and ended are final. The Rust state test covers `reportedBy`. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Agent viewer: the report in flight is an activity of `live`, abandoned when the page stops From the code review on #118: a report still in flight when the long poll failed kept `sending` set across the reconnection, so every later report waited behind it. A report waiting behind it went out while the page was stopped, before the reconnection had checked the server. The report in flight is now a `post` activity of `live`, keyed by its sequence number. When the page stops, the activity ends: its request is aborted and its completion is dropped. The outbox is cleared, and the page reports afresh once it resumes. A stopped page takes no reports and no completions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Installed proof: pack the machine package with the workspaces that depend on it Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
agorischek
added a commit
that referenced
this pull request
Nov 21, 2026
… waits forever (#111) * Model lifecycles as explicit state machines: packages/machine and its checks @githubnext/projections-machine is a small, dependency-free state machine core for the hosts' and integrations' lifecycles: - defineMachine: states keyed by `kind`, events by `type`; every state lists a handler or `ignore` for every event, so an unconsidered case, a missing or extra state, or a transition without its state's data is a compile error. Handlers are pure and return the next state or emit(state, ...effects). - createActor: framework-agnostic. Effects and activities are data run by a runner per type, each in a generation that ends when superseded (an effect's `key`), when its state stops listing it, or when the actor stops; its signal aborts and its later events are dropped. after() is a timer activity. - useMachine (./react): one actor per component, started in a layout effect so changes made there render before paint. - explore (./testing): breadth-first walk of reachable states, with state and step invariants, the shortest path to a violation, and `complete` to fail on handlers never taken. npm run check:machines (a `tools check --fast` gate, and in CI) runs the machines/lifecycle ESLint rule (boolean refs, timers started in effects, setters called from timer or promise callbacks) against a committed baseline that may only shrink, and requires an explore test for every machine. docs/guides/state-machines.md explains when and how; AGENTS.md and CONTRIBUTING.md point to it. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Machine: infer an actor's and an exploration's types from the machine alone With two or more effect types, inferring from the options too made each runner's effect never. The options now take NoInfer of the whole type, and the compile-time tests cover a machine with two effects. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Machine: drop stale queued events, run every cleanup, notify per batch; tighter checks From the code review on #110: - An event a generation sent waits in the queue with that generation, and is dropped if the generation ended before it was taken (two keyed effects' synchronous results, an activity removed meanwhile). - Every cleanup an unkeyed effect returns runs when the actor stops; they shared one slot. - Listeners hear a batch before the events they send are taken, so each hears every state in order. - useMachine publishes its runners and error handler in the commit phase, never a render React may discard, and always delegates errors to the current handler or the default reporter. - explore fires a timer once while states keep listing its key, as an actor does. - check-machines: `--update` never raises the baseline; a machine counts as explored only when passed to `explore(`; a module that only imports `defineMachine` passes; the lifecycle rule resolves a setter call to the `useState` binding instead of comparing names. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * VS Code: a webview page's lifecycle as a state machine, so no command waits forever InspectorWebview kept the page's readiness as a promise it replaced on every load. A command (`control`) that awaited the promise of a load the extension then replaced (a backend replacement reloads the page) waited forever: its 30 s timeout was armed only after the await, and closing the panel never settled it either. The page's lifecycle is now `pageLifecycle` (page-lifecycle.ts, on @githubnext/projections-machine): loading, ready or closed, with the commands waiting on the page in its state. - A command asked for while the page loads waits for the page across reloads, and is posted when it is ready. - Its time counts from the call, as an `after` timer per command, so a page that never gets ready fails it. - A command posted to a page that then reloads (the extension's load, or VS Code's reload of a hidden tab) fails at once instead of after 30 s. - Closing fails every waiting command, and any asked for after. - The page says which load it is in its `ready`, so a late ready from a replaced page isn't taken for the new one. The tests cover each case and explore every state: every command is posted once, when the page is ready for it, and settled once, whatever the page does. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * VS Code: a command asked for after the panel closed fails at once; tests stop their actors From the code review on #111: the page's lifecycle keeps running once closed, so a later control() is rejected rather than queued on a stopped actor, and the tests stop their actors so no 30 s timer keeps the process alive. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Installed proof: pack the machine package with the workspaces that depend on it Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Projections' hosts and integrations have dozens of lifecycles written as booleans, refs, effects and timers. Their bugs are events arriving in states the code didn't expect: a cancel before the job is named, a result after the person moved on, a reload while a command waits. This adds a small state machine core and checks that make explicit modelling the default. It is the first step of converting them; the toolbar fit plan (#106/#109) is the first user, in a follow-up.
@githubnext/projections-machine(packages/machine)The package has no dependencies; React is an optional peer of
./react. It is a new bottom-layer workspace, so host core, the VS Code UI, the Inspector and the VS Code extension host can all use it without depending on each other. Renderers can use it later, since it is tree-shakable and contains noeval.defineMachine<State, Event, Effect, Activity>()({states}). States are a union keyed bykindand events a union keyed bytype. Every state must list a handler orignorefor every event type. That makes all of these compile errors (test/types.ts):Handlers are pure: they return the next state, or
emit(state, ...effects).createActor. It is framework-agnostic, for the extension host and headless UIs. Effects and activities are data, carried out by a runner per type. Each runs in a generation that ends when it is superseded (an effect with the samekey), when its state stops listing it, or when the actor stops. When a generation ends, its signal aborts, its cleanup runs and the events it sends are dropped. Stale results can't reach the machine, without hand-written epochs or run tokens.after(key, ms, event)is a timer activity.useMachine(./react). It runs one actor per component and starts it in a layout effect, so a change an event makes there renders before paint, as a layout loop needs. I used a layout-effect subscription rather thanuseSyncExternalStore, which subscribes only after paint on first mount.explore(./testing). It walks reachable states breadth first, firingaftertimers too, and checks named state and step invariants. It reports the shortest path to a violation, for exampleidle --start--> starting --named--> polling. Withcomplete, it fails on handlers never taken.Checks
npm run check:machinesis atools check --fastgate, also in CI andnpm run check.machines/lifecycleESLint rule. It covers the hosts and the VS Code extension, and flags booleanuseRefs, timers started in effects, anduseStatesetters called from timer or promise callbacks. It is a warning in editors. The check counts findings per file againsttools/scripts/check-machines/baseline.json: 62 today, in 27 files. It fails when a file gains one, or when it has fewer than its baseline (lower it with--update), so the baseline only shrinks as code is converted.defineMachinemust be an exported const with anexploretest in its workspace'stest/.Docs
docs/guides/state-machines.mdcovers when and how, testing, the checks, and why no library. XState v5 was weighed: about 13 KB gzipped, context shared across states, and an awkward fit for layout-timed and controlled machines.Verification
tools check --fastpasses: boundaries, considered, machines, lint, format, typecheck including the compile-time tests, versions and readmes.check:tsdocpasses.