Repository navigation
refactor(onboard): consume handler FSM results compatibly #4454
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 24 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
6b753bf
docs(onboard): document FSM migration target
cv fb1b32d
refactor(onboard): centralize machine state metadata
cv c3e4ad6
refactor(onboard): derive session step mapping from FSM metadata
cv 603832c
refactor(onboard): derive progress labels from FSM metadata
cv 4fad8e7
fix(onboard): emit lifecycle events for onboarding start
cv f99e9cb
fix(onboard): emit machine events for resume conflicts
cv 2b60df4
refactor(onboard): introduce explicit state result types
cv 30341b0
refactor(onboard): apply explicit state results through runtime
cv d4ad2d9
refactor(onboard): make finalization return FSM result
cv 356c947
refactor(onboard): make agent setup return FSM result
cv 2296519
refactor(onboard): make policy setup return FSM result
cv 67a9a1e
refactor(onboard): make preflight and gateway return FSM results
cv 46f4a49
refactor(onboard): make sandbox return branch FSM result
cv 9cc15f5
refactor(onboard): return FSM results from provider inference
cv dbbb273
refactor(onboard): add FSM runner shell
cv 6b27a0b
refactor(onboard): consume handler FSM results compatibly
cv 748bda6
merge(onboard): sync stack base
cv 796ed7b
refactor(onboard): address FSM runner review feedback
cv c782eac
merge(onboard): sync stack base
cv a5e53d9
refactor(onboard): address FSM result compatibility feedback
cv cc637fd
refactor(onboard): keep result recording entrypoint neutral
cv 3e4fcf7
merge(onboard): sync stack base
cv a373ddd
merge(onboard): sync stack base
cv c5d3d1c
test(onboard): cover FSM compatibility bridge
cv ed9a739
Merge branch 'main' into stack/onboard-fsm-consume-results-compat
cv 9372e41
fix(onboard): address FSM review followups
cv File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,219 @@ | ||
| // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import { describe, expect, it, vi } from "vitest"; | ||
|
|
||
| import { | ||
| MACHINE_SNAPSHOT_VERSION, | ||
| createSession, | ||
| filterSafeUpdates, | ||
| normalizeSession, | ||
| sanitizeFailure, | ||
| type Session, | ||
| type SessionUpdates, | ||
| } from "../../state/onboard-session"; | ||
| import { advanceTo, branchTo, completeOnboardMachine, failOnboardMachine, retryTo } from "./result"; | ||
| import { OnboardRuntime, type OnboardRuntimeDeps } from "./runtime"; | ||
| import { | ||
| MissingOnboardStateHandlerError, | ||
| OnboardMachineTransitionLimitError, | ||
| runOnboardMachine, | ||
| type OnboardStateHandlers, | ||
| } from "./runner"; | ||
|
|
||
| interface RunnerContext { | ||
| attempts: number; | ||
| visited: string[]; | ||
| } | ||
|
|
||
| function cloneSession(session: Session): Session { | ||
| return normalizeSession(JSON.parse(JSON.stringify(session))) ?? session; | ||
| } | ||
|
|
||
| function createRuntime(initialSession: Session = createSession()) { | ||
| let session = cloneSession(initialSession); | ||
| const updateSession = (mutator: (value: Session) => Session | void): Session => { | ||
| const next = mutator(cloneSession(session)) ?? session; | ||
| session = cloneSession(next); | ||
| return cloneSession(session); | ||
| }; | ||
| const deps: OnboardRuntimeDeps = { | ||
| loadSession: () => cloneSession(session), | ||
| createSession, | ||
| saveSession: (next) => { | ||
| session = cloneSession(next); | ||
| return cloneSession(session); | ||
| }, | ||
| updateSession, | ||
| markStepStarted: () => cloneSession(session), | ||
| markStepComplete: (_stepName, updates: SessionUpdates = {}) => | ||
| updateSession((current) => { | ||
| Object.assign(current, filterSafeUpdates(updates)); | ||
| return current; | ||
| }), | ||
| markStepSkipped: () => cloneSession(session), | ||
| markStepFailed: (_stepName, message) => | ||
| updateSession((current) => { | ||
| current.status = "failed"; | ||
| current.failure = sanitizeFailure({ step: _stepName, message, recordedAt: "now" }); | ||
| return current; | ||
| }), | ||
| completeSession: (updates: SessionUpdates = {}) => | ||
| updateSession((current) => { | ||
| Object.assign(current, filterSafeUpdates(updates)); | ||
| current.status = "complete"; | ||
| current.resumable = false; | ||
| return current; | ||
| }), | ||
| filterSafeUpdates, | ||
| emitEvent: () => undefined, | ||
| now: () => "2026-05-28T00:00:00.000Z", | ||
| }; | ||
| return new OnboardRuntime(deps); | ||
| } | ||
|
|
||
| describe("runOnboardMachine", () => { | ||
| it("runs handlers until completion while applying retry and branch transitions", async () => { | ||
| const runtime = createRuntime(); | ||
| const calls: string[] = []; | ||
| const handlers: OnboardStateHandlers<RunnerContext> = { | ||
| init: () => advanceTo("preflight"), | ||
| preflight: () => advanceTo("gateway"), | ||
| gateway: () => advanceTo("provider_selection"), | ||
| provider_selection: () => advanceTo("inference"), | ||
| inference: (context) => { | ||
| calls.push(`inference:${context.attempts}`); | ||
| return context.attempts === 0 ? retryTo("provider_selection") : advanceTo("sandbox"); | ||
| }, | ||
| sandbox: () => branchTo("openclaw"), | ||
| openclaw: () => advanceTo("policies"), | ||
| policies: () => advanceTo("finalizing"), | ||
| finalizing: () => advanceTo("post_verify"), | ||
| post_verify: () => completeOnboardMachine({ sandboxName: "my-assistant" }), | ||
| }; | ||
|
|
||
| const result = await runOnboardMachine({ | ||
| context: { attempts: 0, visited: [] } as RunnerContext, | ||
| runtime, | ||
| handlers, | ||
| updateContext: ({ context, state }) => ({ | ||
| attempts: state === "inference" ? context.attempts + 1 : context.attempts, | ||
| visited: [...context.visited, state], | ||
| }), | ||
| }); | ||
|
|
||
| expect(result.session).toMatchObject({ | ||
| status: "complete", | ||
| sandboxName: "my-assistant", | ||
| machine: { state: "complete" }, | ||
| }); | ||
| expect(calls).toEqual(["inference:0", "inference:1"]); | ||
| expect(result.context.visited).toEqual([ | ||
| "init", | ||
| "preflight", | ||
| "gateway", | ||
| "provider_selection", | ||
| "inference", | ||
| "provider_selection", | ||
| "inference", | ||
| "sandbox", | ||
| "openclaw", | ||
| "policies", | ||
| "finalizing", | ||
| "post_verify", | ||
| ]); | ||
| }); | ||
|
|
||
| it("stops on failed terminal results", async () => { | ||
| const runtime = createRuntime(); | ||
| const policies = vi.fn(() => advanceTo("finalizing")); | ||
|
|
||
| const result = await runOnboardMachine({ | ||
| context: { attempts: 0, visited: [] } as RunnerContext, | ||
| runtime, | ||
| handlers: { | ||
| init: () => advanceTo("preflight"), | ||
| preflight: () => failOnboardMachine("preflight failed", { step: "preflight" }), | ||
| policies, | ||
| }, | ||
| }); | ||
|
|
||
| expect(result.session).toMatchObject({ | ||
| status: "failed", | ||
| failure: { step: "preflight", message: "preflight failed" }, | ||
| machine: { state: "failed" }, | ||
| }); | ||
| expect(policies).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns immediately for terminal sessions", async () => { | ||
| const startedAt = "2026-05-28T00:00:00.000Z"; | ||
| const completeSession = createSession({ | ||
| resumable: false, | ||
| machine: { | ||
| version: MACHINE_SNAPSHOT_VERSION, | ||
| state: "complete", | ||
| stateEnteredAt: startedAt, | ||
| revision: 1, | ||
| }, | ||
| }); | ||
| completeSession.status = "complete"; | ||
| const runtime = createRuntime(completeSession); | ||
| const init = vi.fn(() => advanceTo("preflight")); | ||
|
|
||
| const result = await runOnboardMachine({ | ||
| context: { attempts: 0, visited: [] } as RunnerContext, | ||
| runtime, | ||
| handlers: { init }, | ||
| }); | ||
|
|
||
| expect(result.session).toMatchObject({ status: "complete", machine: { state: "complete" } }); | ||
| expect(init).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("propagates runtime transition errors without updating context", async () => { | ||
| const runtime = createRuntime(); | ||
| const updateContext = vi.fn(({ context }) => context); | ||
|
|
||
| await expect( | ||
| runOnboardMachine({ | ||
| context: { attempts: 0, visited: [] } as RunnerContext, | ||
| runtime, | ||
| handlers: { init: () => advanceTo("sandbox") }, | ||
| updateContext, | ||
| }), | ||
| ).rejects.toThrow("Invalid onboarding machine transition"); | ||
| expect(updateContext).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("throws when a non-terminal state has no handler", async () => { | ||
| const runtime = createRuntime(); | ||
|
|
||
| await expect( | ||
| runOnboardMachine({ | ||
| context: { attempts: 0, visited: [] } as RunnerContext, | ||
| runtime, | ||
| handlers: {}, | ||
| }), | ||
| ).rejects.toThrow(MissingOnboardStateHandlerError); | ||
| }); | ||
|
|
||
| it("throws when retry-capable handlers exceed the transition limit", async () => { | ||
| const runtime = createRuntime(); | ||
|
|
||
| await expect( | ||
| runOnboardMachine({ | ||
| context: { attempts: 0, visited: [] } as RunnerContext, | ||
| runtime, | ||
| handlers: { | ||
| init: () => advanceTo("preflight"), | ||
| preflight: () => advanceTo("gateway"), | ||
| gateway: () => advanceTo("provider_selection"), | ||
| provider_selection: () => advanceTo("inference"), | ||
| inference: () => retryTo("provider_selection"), | ||
| }, | ||
| maxTransitions: 5, | ||
| }), | ||
| ).rejects.toThrow(OnboardMachineTransitionLimitError); | ||
| }); | ||
| }); |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import type { Session } from "../../state/onboard-session"; | ||
| import type { OnboardStateResult } from "./result"; | ||
| import { isTerminalOnboardMachineState } from "./transitions"; | ||
| import type { OnboardMachineState, OnboardNonTerminalMachineState } from "./types"; | ||
|
|
||
| export type OnboardStateHandler<Context> = ( | ||
| context: Context, | ||
| ) => Promise<OnboardStateResult> | OnboardStateResult; | ||
|
|
||
| export type OnboardStateHandlers<Context> = Partial< | ||
| Record<OnboardNonTerminalMachineState, OnboardStateHandler<Context>> | ||
| >; | ||
|
|
||
| export interface OnboardMachineRunnerRuntime { | ||
| session(): Promise<Session>; | ||
| applyResult(result: OnboardStateResult): Promise<Session>; | ||
| } | ||
|
|
||
| export interface OnboardMachineRunnerOptions<Context> { | ||
| context: Context; | ||
| runtime: OnboardMachineRunnerRuntime; | ||
| handlers: OnboardStateHandlers<Context>; | ||
| /** | ||
| * Safety valve for retry-capable handlers. Handlers should bound their own | ||
| * retry loops, but the runner refuses to apply unbounded transitions. | ||
| */ | ||
| maxTransitions?: number; | ||
| updateContext?(input: { | ||
| context: Context; | ||
| state: OnboardMachineState; | ||
| result: OnboardStateResult; | ||
| session: Session; | ||
| }): Context | Promise<Context>; | ||
| } | ||
|
|
||
| export interface OnboardMachineRunnerResult<Context> { | ||
| context: Context; | ||
| session: Session; | ||
| } | ||
|
|
||
| export class MissingOnboardStateHandlerError extends Error { | ||
| readonly state: OnboardNonTerminalMachineState; | ||
|
|
||
| constructor(state: OnboardNonTerminalMachineState) { | ||
| super(`Missing onboarding machine handler for state: ${state}`); | ||
| this.name = "MissingOnboardStateHandlerError"; | ||
| this.state = state; | ||
| } | ||
| } | ||
|
|
||
| export class OnboardMachineTransitionLimitError extends Error { | ||
| readonly maxTransitions: number; | ||
|
|
||
| constructor(maxTransitions: number) { | ||
| super(`Onboarding machine exceeded transition limit: ${maxTransitions}`); | ||
| this.name = "OnboardMachineTransitionLimitError"; | ||
| this.maxTransitions = maxTransitions; | ||
| } | ||
| } | ||
|
|
||
| const DEFAULT_MAX_TRANSITIONS = 100; | ||
|
|
||
| function normalizeMaxTransitions(value: number | undefined): number { | ||
| if (value === undefined) return DEFAULT_MAX_TRANSITIONS; | ||
| return Math.max(1, Math.trunc(value)); | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| export async function runOnboardMachine<Context>({ | ||
| context: initialContext, | ||
| runtime, | ||
| handlers, | ||
| maxTransitions, | ||
| updateContext, | ||
| }: OnboardMachineRunnerOptions<Context>): Promise<OnboardMachineRunnerResult<Context>> { | ||
| let context = initialContext; | ||
| let session = await runtime.session(); | ||
| let transitions = 0; | ||
| const transitionLimit = normalizeMaxTransitions(maxTransitions); | ||
|
|
||
| while (!isTerminalOnboardMachineState(session.machine.state)) { | ||
| if (transitions >= transitionLimit) { | ||
| throw new OnboardMachineTransitionLimitError(transitionLimit); | ||
| } | ||
| const state = session.machine.state; | ||
| const handler = handlers[state as OnboardNonTerminalMachineState]; | ||
| if (!handler) throw new MissingOnboardStateHandlerError(state as OnboardNonTerminalMachineState); | ||
|
|
||
| const result = await handler(context); | ||
| session = await runtime.applyResult(result); | ||
| transitions += 1; | ||
| context = updateContext | ||
| ? await updateContext({ context, state, result, session }) | ||
| : context; | ||
| } | ||
|
|
||
| return { context, session }; | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.