Skip to content

Model lifecycles as explicit state machines: packages/machine and its checks - #110

Merged
agorischek merged 6 commits into
mainfrom
machine-core
Nov 21, 2026
Merged

agorischek merged 6 commits into
mainfrom
machine-core

Conversation

@agorischek

Copy link
Copy Markdown
Collaborator

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 no eval.

  • defineMachine<State, Event, Effect, Activity>()({states}). States are a union keyed by kind and events a union keyed by type. Every state must list a handler or ignore for every event type. That makes all of these compile errors (test/types.ts):

    • an event a state doesn't consider;
    • a missing or extra state;
    • a transition to a state without its data;
    • a handler reading data its state lacks.

    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 same key), 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 than useSyncExternalStore, which subscribes only after paint on first mount.

  • explore (./testing). It walks reachable states breadth first, firing after timers too, and checks named state and step invariants. It reports the shortest path to a violation, for example idle --start--> starting --named--> polling. With complete, it fails on handlers never taken.

Checks

npm run check:machines is a tools check --fast gate, also in CI and npm run check.

  • The machines/lifecycle ESLint rule. It covers the hosts and the VS Code extension, and flags boolean useRefs, timers started in effects, and useState setters called from timer or promise callbacks. It is a warning in editors. The check counts findings per file against tools/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.
  • Every defineMachine must be an exported const with an explore test in its workspace's test/.

Docs

  • docs/guides/state-machines.md covers 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.
  • AGENTS.md, CONTRIBUTING.md (layout and invariants) and the docs index point to it.

Verification

  • tools check --fast passes: boundaries, considered, machines, lint, format, typecheck including the compile-time tests, versions and readmes.
  • check:tsdoc passes.
  • The package's 13 node tests and the rule's 9 RuleTester cases pass.
  • The guide's examples compile and run.

… 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>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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
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

Comment thread packages/machine/src/actor.ts Resolved
Comment thread packages/machine/src/actor.ts Resolved
Comment thread packages/machine/src/actor.ts Resolved
Comment thread packages/machine/src/react.ts Resolved
Comment thread packages/machine/src/testing.ts Resolved
Comment thread tools/scripts/check-machines.mjs Resolved
Comment thread tools/scripts/check-machines.mjs Resolved
Comment thread packages/machine/src/react.ts Resolved
Comment thread tools/scripts/check-machines.mjs Resolved
…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>
@agorischek
agorischek merged commit 9a2aeee into main Nov 21, 2026
52 checks passed
@agorischek
agorischek deleted the machine-core branch November 21, 2026 01:29
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants