Skip to content

Track onboard FSM migration stack and resume compatibility #4533

Closed

Description

@cv

Summary

This issue tracks the stacked onboarding finite-state-machine (FSM) migration work and explains the current intended end-state for reviewers and maintainers.

The stack moves onboarding from a large manual sequence in src/lib/onboard.ts toward explicit FSM state results, a strict runtime/runner, and phase slices. Fresh onboarding is now being migrated onto FSM slices. Resume/ahead-state flows intentionally remain compatibility-driven for now so historical repair and backstop checks still execute even when the saved machine state is already ahead.

Stack overview

1. FSM target, metadata, and mappings

2. Runtime lifecycle/events/result primitives

3. Existing handlers return FSM results

4. Runner, record-only steps, and compatibility bridge

5. Ordered results and sequence adapter

6. Flow context, phase adapters, and slice helpers

7. Live fresh-flow migration and boundary tests

Current behavior after the stack

Fresh onboarding is migrated to FSM slices:

  1. Initial slice: preflight/gateway → stops at provider_selection
  2. Core slice: provider/inference + sandbox → stops at openclaw or agent_setup
  3. Final slice: branch setup + policies + finalization → completion

Step helpers can now record status without mutating the durable machine state. Fresh flows use record-only step mutation so OnboardRuntime owns machine transitions.

Resume compatibility is intentional

Resume/ahead-state flows still use the compatibility execution path. This is intentional because many historical fixes are repair/backstop checks inside phase bodies. Those checks must still run even if a saved session has already advanced beyond the phase's nominal FSM state.

Examples of this pattern include preflight/gateway backstops, provider repair, sandbox reuse/repair decisions, policy reconciliation, and final verification/recovery checks.

A future project can model resume repairs as first-class FSM behavior, but this stack keeps resume conservative to avoid regressions.

Suggested review order

  1. Review and merge the foundation PRs first (docs(onboard): document FSM migration target #4361 onward).
  2. Keep later PRs draft until their bases are merged/restacked.
  3. Review handler-result PRs independently; most are small behavior-preserving changes.
  4. Review live-slice PRs (refactor(onboard): run initial phases through FSM slice #4499, refactor(onboard): run core phases through FSM slice #4500, refactor(onboard): run final phases through FSM slice #4507, refactor(onboard): extract live FSM slice runner helper #4530, test(onboard): cover live FSM slice boundaries #4531) more carefully because they affect the live onboard.ts execution path for fresh runs.

Follow-up work after this stack

  • Move large inline live phase wiring out of src/lib/onboard.ts into a dedicated module.
  • Clarify/rename the resume compatibility result application helper.
  • Audit high-level smoke coverage for fresh, retry, branch, and resume paths after the stack lands.
  • Decide later whether resume repair/backstop behavior should become explicit FSM policy.

Activity

  1. self-assigned this
    on May 29, 2026
  2. Iamkewl commented on May 29, 2026

    @Iamkewl
    Contributor

    Might be outside the scope of this, wondering if I should open a seperate issue with the same, found post revieiwng the PRs:

    Summary

    OnboardRuntimeBoundary.recordStateResultWithStepCompatibility (runtime-boundary.ts:95–107) silently discards transition results in two cases:

    1. Idempotency guard (line 100) — machine is already at the target state → return current
    2. Provenance guard (line 104) — result's source state doesn't match current machine state → return current

    Neither case emits an event, log, or trace. When debugging resume flows, there's no way to tell if a result was applied, discarded by idempotency, or discarded by provenance mismatch without stepping through with a debugger.

    Proposal

    Introduce a new type-safe event "state.result.skipped" to the FSM runtime and emit it when a result is skipped during transition recording.

    1. Add "state.result.skipped" to ONBOARD_MACHINE_EVENT_TYPES in src/lib/onboard/machine/types.ts:

    export const ONBOARD_MACHINE_EVENT_TYPES = [
      ...
      "state.repair.started",
      "state.repair.completed",
      "state.repair.failed",
      "state.result.skipped", // Add here
      "context.updated",
      ...
    ] as const;

    2. Define emitResultSkipped on OnboardRuntime in src/lib/onboard/machine/runtime.ts:

      async emitResultSkipped(options: {
        reason: "already_at_target" | "source_state_mismatch";
        currentState: OnboardMachineState;
        targetState: OnboardMachineState;
        metadata?: Record<string, unknown> | null;
      }): Promise<Session> {
        const session = this.ensureSession();
        this.emit("state.result.skipped", session, {
          state: session.machine.state,
          metadata: {
            ...eventMetadata(options.metadata),
            reason: options.reason,
            currentState: options.currentState,
            targetState: options.targetState,
          },
        });
        return session;
      }

    3. Update recordStateResultWithStepCompatibility in src/lib/onboard/runtime-boundary.ts to emit the events:

      async recordStateResultWithStepCompatibility(result: OnboardStateResult): Promise<Session> {
        const runtime = this.getRuntime();
        const current = await runtime.session();
        if (result.type !== "transition") return runtime.applyResult(result);
    
        if (current.machine.state === result.next) {
          await runtime.emitResultSkipped({
            reason: "already_at_target",
            currentState: current.machine.state,
            targetState: result.next,
          });
          return current;
        }
    
        const sourceState =
          result.metadata && typeof result.metadata.state === "string" ? result.metadata.state : null;
        if (sourceState && current.machine.state !== sourceState) {
          await runtime.emitResultSkipped({
            reason: "source_state_mismatch",
            currentState: current.machine.state,
            targetState: result.next,
            metadata: { sourceState },
          });
          return current;
        }
    
        return runtime.applyResult(result);
      }
  3. added
    area: install
    area: onboarding
    and removed on May 29, 2026
  4. cv commented on Jun 8, 2026

    @cv
    CollaboratorAuthor

    Post-mortem: rebuild/resume E2E regression after #4472

    After #4472 merged, the rebuild/resume path exposed a regression that should have been caught before that PR landed.

    What failed

    The affected path was rebuild-driven resume: rebuildSandbox() reopens the persisted onboarding session and calls onboard({ resume: true, recreateSandbox: true }) so the sandbox can be recreated with the prior configuration.

    In the broken case, the persisted session had already reached a terminal machine snapshot:

    • session.machine.state === "complete"
    • session.status was reset to "in_progress" by rebuild
    • session.resumable was reset to true
    • legacy step fields still indicated the last completed phase

    #4472 intentionally moved the live sequence to record-only step helpers so the FSM runtime owns durable machine transitions. That part was directionally correct for #4533. The gap was that resume compatibility still relies on legacy step fields and repair/backstop phase bodies. When rebuild reopened a session whose machine snapshot was still terminal complete, the compatibility recorder treated subsequent nonterminal results as stale/already-ahead and skipped them. Finalization then tried to complete from an already-complete machine state, hitting the invalid complete -> complete transition assertion instead of replaying the compatibility phases.

    Root cause

    #4472 repaired terminal failed snapshots before resume, but did not repair terminal complete snapshots that had been reopened for resume/rebuild. That left the durable machine state ahead of the compatibility execution path.

    The important distinction is:

    • a genuinely completed, non-resumable session should remain complete
    • a completed snapshot that rebuild has deliberately reopened (status !== "complete" or resumable !== false) must be normalized back to the next resumable state derived from the legacy step record

    #4938 fixed this by extending repairResumeMachineSnapshot() to repair reopened/resumable complete snapshots while leaving non-resumable completed sessions untouched.

    Why #4472 missed it

    The review and tests covered the new record-only behavior and failed-session resume repair, but did not cover the rebuild-specific reopened-terminal shape. That shape is subtle because it is not a normal resume interruption; it is created by rebuildSandbox() after a previously successful onboard, when rebuild temporarily turns a completed session back into an in-progress resumable one.

    This is exactly the kind of boundary #4533 called out as risky: fresh onboarding can move to FSM-owned transitions, but resume/ahead-state flows must keep compatibility repairs and backstops alive until resume behavior is modeled as first-class FSM policy.

    Fix and verification

    Fixed by #4938:

    • repaired reopened/resumable complete machine snapshots from legacy step state
    • added unit coverage for reopened complete snapshots after gateway and policies
    • kept non-resumable completed sessions unchanged
    • fixed a separate messaging verification warning found during the same investigation: provider checks now use sandbox-scoped bridge provider names and skip tokenless WhatsApp provider checks

    Verification after #4938:

    Prevention

    For future PRs in this stack, we should treat changes to the live sequence, runtime boundary, resume repair, record-only runner, or rebuild/session reopening as requiring targeted runtime coverage before merge:

    • onboard-resume-e2e
    • onboard-repair-e2e
    • rebuild-openclaw-e2e

    We should also consider adding a dedicated E2E scenario that explicitly creates the reopened-complete snapshot shape (machine.state: "complete", status: "in_progress", resumable: true, lastCompletedStep set) and verifies onboard --resume repairs the snapshot before record-only replay. The unit coverage now pins this, but the original failure lived at the rebuild/runtime boundary, so a small targeted E2E would have caught #4472 before merge.

  5. added and removed on Jun 8, 2026
  6. cv commented on Jun 9, 2026

    @cv
    CollaboratorAuthor

    Status refresh (June 9, 2026)

    Refreshed live GitHub state for the section 6 PRs and the follow-on live-slice stack.

    Section 6

    PRs #4480-#4488 are merged. They all carry v0.0.62; their CI/check surfaces were green at merge time, and none have pending/failing checks now.

    Merged section 6 PRs:

    Open follow-on stack

    PR Current status
    #4499 Draft. CI is green. Old CodeQL threads are resolved/outdated. GPU formatter feedback is resolved. Latest advisor still has one worth-checking item: add/prove/document the resume/ahead-state compatibility path for initial-flow resume backstops.
    #4500 Draft. Checks green, but merge state is DIRTY; needs conflict/rebase work.
    #4507 Draft. Checks green, merge state CLEAN.
    #4530 Draft. Checks green, merge state CLEAN.
    #4531 Draft. Checks green, merge state CLEAN.

    Next maintainer move

    For #4499, add the targeted resume/ahead-state compatibility coverage requested by the advisor, plus a clear comment documenting the removal condition for the compatibility path. Then rerun/push, wait for checks/advisor, and mark #4499 ready for review if clean.

  7. cv commented on Jun 10, 2026

    @cv
    CollaboratorAuthor

    Closeout

    This tracker is complete.

    All PRs listed in the stack have merged, including the section 6 phase/slice helpers (#4480-#4488), the live fresh-flow migration (#4499, #4500, #4507), the live slice runner extraction (#4530), and the boundary coverage PR (#4531). The rebuild/resume regression follow-up (#4938) also merged, and the compatibility skip visibility feedback from this issue is now represented by state.result.skipped plus runtime-boundary coverage.

    Final state for this tracker:

    • Fresh onboarding now runs through FSM slices: initial -> core -> final.
    • Resume/ahead-state flows intentionally remain compatibility-driven so historical repair/backstop checks still execute.
    • Live slice boundary tests cover fresh progression plus resume/ahead compatibility bypass behavior.
    • CodeRabbit, PR Advisor, and CI were green on the final PR before merge.

    Closing this as completed. Broader cleanup and future policy work, such as continuing to slim src/lib/onboard.ts, making resume repair/backstop behavior first-class FSM policy, or expanding the E2E scenario catalog, should stay under the umbrella issue #3802 or be split into dedicated follow-up issues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area: installarea: onboarding

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions