NemoClaw icon indicating copy to clipboard operation
NemoClaw copied to clipboard

Track onboard FSM migration stack and resume compatibility

Open cv opened this issue 6 months ago • 5 comments

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

  • #4361 — docs(onboard): document FSM migration target
  • #4362 — refactor(onboard): centralize machine state metadata
  • #4363 — refactor(onboard): derive session step mapping from FSM metadata
  • #4364 — refactor(onboard): derive progress labels from FSM metadata

2. Runtime lifecycle/events/result primitives

  • #4373 — fix(onboard): emit lifecycle events for onboarding start
  • #4374 — fix(onboard): emit machine events for resume conflicts
  • #4375 — refactor(onboard): introduce explicit state result types
  • #4376 — refactor(onboard): apply explicit state results through runtime

3. Existing handlers return FSM results

  • #4443 — refactor(onboard): make finalization return FSM result
  • #4444 — refactor(onboard): make agent setup return FSM result
  • #4445 — refactor(onboard): make policy setup return FSM result
  • #4446 — refactor(onboard): make preflight and gateway return FSM results
  • #4447 — refactor(onboard): make sandbox return branch FSM result
  • #4452 — refactor(onboard): return FSM results from provider inference

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

  • #4453 — refactor(onboard): add FSM runner shell
  • #4454 — refactor(onboard): consume handler FSM results compatibly
  • #4457 — refactor(onboard): allow step recording without machine transitions
  • #4458 — refactor(onboard): plumb step mutation options through runtime
  • #4461 — refactor(onboard): add record-only FSM runner adapter

5. Ordered results and sequence adapter

  • #4471 — refactor(onboard): return ordered provider FSM results
  • #4472 — refactor(onboard): run live sequence with record-only steps
  • #4473 — refactor(onboard): let FSM handlers return result sequences
  • #4475 — refactor(onboard): add sequence runner adapter

6. Flow context, phase adapters, and slice helpers

  • #4480 — refactor(onboard): support FSM runner stop states
  • #4481 — refactor(onboard): define FSM flow context
  • #4482 — refactor(onboard): extract preflight and gateway FSM phases
  • #4483 — refactor(onboard): extract provider and sandbox FSM phases
  • #4484 — refactor(onboard): extract agent policy finalization FSM phases
  • #4485 — refactor(onboard): assemble FSM phase sequence
  • #4486 — refactor(onboard): add initial FSM flow slice
  • #4487 — refactor(onboard): add core FSM flow slice
  • #4488 — refactor(onboard): add final FSM flow slice

7. Live fresh-flow migration and boundary tests

  • #4499 — refactor(onboard): run initial phases through FSM slice
  • #4500 — refactor(onboard): run core phases through FSM slice
  • #4507 — refactor(onboard): run final phases through FSM slice
  • #4530 — refactor(onboard): extract live FSM slice runner helper
  • #4531 — test(onboard): cover live FSM slice boundaries

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 (#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 (#4499, #4500, #4507, #4530, #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.

cv avatar May 29 '26 16:05 cv

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);
  }

Iamkewl avatar May 29 '26 17:05 Iamkewl

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:

  • npx prek run --all-files
  • npm test
  • targeted E2E advisor run: https://github.com/NVIDIA/NemoClaw/actions/runs/27117026620
    • onboard-resume-e2e passed
    • onboard-repair-e2e passed
    • messaging-providers-e2e passed
  • targeted rebuild retry: https://github.com/NVIDIA/NemoClaw/actions/runs/27117531320
    • rebuild-openclaw-e2e passed

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.

cv avatar Jun 08 '26 05:06 cv

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:

  • #4480 — refactor(onboard): support FSM runner stop states
  • #4481 — refactor(onboard): define FSM flow context
  • #4482 — refactor(onboard): extract preflight and gateway FSM phases
  • #4483 — refactor(onboard): extract provider and sandbox FSM phases
  • #4484 — refactor(onboard): extract agent policy finalization FSM phases
  • #4485 — refactor(onboard): assemble FSM phase sequence
  • #4486 — refactor(onboard): add initial FSM flow slice
  • #4487 — refactor(onboard): add core FSM flow slice
  • #4488 — refactor(onboard): add final FSM flow slice

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.

cv avatar Jun 09 '26 23:06 cv

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.

cv avatar Jun 10 '26 05:06 cv