Skip to content
Merged
Show file tree
Hide file tree
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 May 27, 2026
fb1b32d
refactor(onboard): centralize machine state metadata
cv May 27, 2026
c3e4ad6
refactor(onboard): derive session step mapping from FSM metadata
cv May 27, 2026
603832c
refactor(onboard): derive progress labels from FSM metadata
cv May 27, 2026
4fad8e7
fix(onboard): emit lifecycle events for onboarding start
cv May 28, 2026
f99e9cb
fix(onboard): emit machine events for resume conflicts
cv May 28, 2026
2b60df4
refactor(onboard): introduce explicit state result types
cv May 28, 2026
30341b0
refactor(onboard): apply explicit state results through runtime
cv May 28, 2026
d4ad2d9
refactor(onboard): make finalization return FSM result
cv May 28, 2026
356c947
refactor(onboard): make agent setup return FSM result
cv May 28, 2026
2296519
refactor(onboard): make policy setup return FSM result
cv May 28, 2026
67a9a1e
refactor(onboard): make preflight and gateway return FSM results
cv May 28, 2026
46f4a49
refactor(onboard): make sandbox return branch FSM result
cv May 28, 2026
9cc15f5
refactor(onboard): return FSM results from provider inference
cv May 28, 2026
dbbb273
refactor(onboard): add FSM runner shell
cv May 28, 2026
6b27a0b
refactor(onboard): consume handler FSM results compatibly
cv May 28, 2026
748bda6
merge(onboard): sync stack base
cv Jun 4, 2026
796ed7b
refactor(onboard): address FSM runner review feedback
cv Jun 4, 2026
c782eac
merge(onboard): sync stack base
cv Jun 4, 2026
a5e53d9
refactor(onboard): address FSM result compatibility feedback
cv Jun 4, 2026
cc637fd
refactor(onboard): keep result recording entrypoint neutral
cv Jun 4, 2026
3e4fcf7
merge(onboard): sync stack base
cv Jun 4, 2026
a373ddd
merge(onboard): sync stack base
cv Jun 4, 2026
c5d3d1c
test(onboard): cover FSM compatibility bridge
cv Jun 5, 2026
ed9a739
Merge branch 'main' into stack/onboard-fsm-consume-results-compat
cv Jun 5, 2026
9372e41
fix(onboard): address FSM review followups
cv Jun 5, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions src/lib/onboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6061,7 +6061,7 @@
const recordStepFailed = onboardRuntimeBoundary.recordStepFailed.bind(onboardRuntimeBoundary);
const recordStateSkipped = onboardRuntimeBoundary.recordStateSkipped.bind(onboardRuntimeBoundary);
const recordRepairEvent = onboardRuntimeBoundary.recordRepairEvent.bind(onboardRuntimeBoundary);
const recordStateResult = onboardRuntimeBoundary.recordStateResult.bind(onboardRuntimeBoundary);
const recordStateResult = onboardRuntimeBoundary.recordStateResultWithStepCompatibility.bind(onboardRuntimeBoundary);
const recordPostVerifyStarted = onboardRuntimeBoundary.recordPostVerifyStarted.bind(onboardRuntimeBoundary);

function skippedStepMessage(
Expand Down Expand Up @@ -6457,7 +6457,7 @@
},
});
if (resume && _preflightDashboardPort === null) preflightDashboardPortRangeAvailability(); // #3953 — resume must mirror preflight()'s fail-fast
session = preflightResult.session;
session = (await recordStateResult(preflightResult.stateResult), preflightResult.session);
const {
sandboxGpuConfig,
resumeHasResolvedGpuIntent,
Expand Down Expand Up @@ -6529,7 +6529,7 @@
exitProcess: (code) => process.exit(code),
},
});
session = gatewayResult.session;
session = (await recordStateResult(gatewayResult.stateResult), gatewayResult.session);

// #2753: prefer requestedSandboxName over an unconfirmed session name.
// A pre-fix session may carry sandboxName even though sandbox creation
Expand Down Expand Up @@ -6614,7 +6614,7 @@
},
},
});
session = providerInferenceResult.session;
session = (await onboardRuntimeBoundary.recordStateResultsWithStepCompatibility([...providerInferenceResult.retryStateResults, providerInferenceResult.stateResult]), providerInferenceResult.session);
sandboxName = providerInferenceResult.sandboxName;
const {
model,
Expand Down Expand Up @@ -6689,7 +6689,7 @@
exitProcess: (code) => process.exit(code),
},
});
session = sandboxStateResult.session;
session = (await recordStateResult(sandboxStateResult.stateResult), sandboxStateResult.session);
sandboxName = sandboxStateResult.sandboxName;
webSearchConfig = sandboxStateResult.webSearchConfig ?? null;
selectedMessagingChannels = sandboxStateResult.selectedMessagingChannels;
Expand Down Expand Up @@ -6731,7 +6731,7 @@
toSessionUpdates: (updates) => toSessionUpdates(updates as Parameters<typeof toSessionUpdates>[0]),
},
});
session = agentSetupResult.session;
session = (await recordStateResult(agentSetupResult.stateResult), agentSetupResult.session);
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed

const policiesResult = await handlePoliciesState({
resume,
Expand Down Expand Up @@ -6768,7 +6768,7 @@
persistAppliedPolicyPresets: policyPresetCarry.persistFinalizedPolicyPresets,
},
});
session = policiesResult.session;
session = (await recordStateResult(policiesResult.stateResult), policiesResult.session);
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
sandboxCancelRollback.disarm(); // #4614: policies confirmed, past the cancellable window

const finalizationResult = await handleFinalizationState({
Expand Down
219 changes: 219 additions & 0 deletions src/lib/onboard/machine/runner.test.ts
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);
});
});
100 changes: 100 additions & 0 deletions src/lib/onboard/machine/runner.ts
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));
}
Comment thread
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 };
}
Loading
Loading