Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
83 changes: 83 additions & 0 deletions packages/opencode/src/ockit/workflow/engine.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// OC Kit workflow engine. Entry point that orchestrates the workflow pipeline:
// validate the graph against the kit index, create the run record, run the
// steps (state machine + runner + scheduler), and fold everything into a
// deterministic `RunSummary`. Pure Effect — no network, no disk I/O.

import { Effect } from "effect"
import type { Kit, Workflow, WorkflowState } from "../types"
import { indexKit } from "../resolver"
import { validateGraph, WorkflowError } from "./graph"
import { createRecord, type WorkflowRunRecord } from "./state"
import { runSteps, type StepOutcome, type StepExecutor } from "./runner"

/** Deterministic summary returned by `runWorkflow`. */
export interface RunSummary {
readonly workflowId: string
readonly runId: string
readonly state: WorkflowState
readonly steps: ReadonlyArray<StepOutcome>
readonly recovered: boolean
readonly startedAt: string
readonly completedAt: string
}

export interface EngineRunOptions {
readonly kit: Kit
readonly workflow: Workflow
readonly sessionId?: string
readonly runId?: string
readonly maxRetries?: number
readonly concurrency?: number
readonly executor?: StepExecutor
readonly at?: string
}

/** Derive a deterministic run id from the workflow + step count. */
export function runIdFor(workflow: Workflow): string {
return `${workflow.id}-${workflow.steps.length}`
}

/**
* Run a workflow. Validates the graph first (a malformed workflow fails with a
* typed `WorkflowError` before anything executes), then drives the state
* machine over the declared steps. The result is deterministic and carries the
* per-step trace, final state, and recovery flag.
*/
export const runWorkflow = Effect.fn("OCKit.workflow.runWorkflow")(function* (options: EngineRunOptions) {
const at = options.at ?? new Date().toISOString()
const runId = options.runId ?? runIdFor(options.workflow)
const sessionId = options.sessionId ?? "session"

const index = indexKit(options.kit)
yield* validateGraph(options.workflow, index)

const record: WorkflowRunRecord = createRecord({
runId,
workflowId: options.workflow.id,
sessionId,
at,
})

const result = yield* runSteps(record, {
workflow: options.workflow,
maxRetries: options.maxRetries,
concurrency: options.concurrency,
executor: options.executor,
at,
})

const { record: final, trace } = result
return {
workflowId: final.workflowId,
runId: final.runId,
state: final.state,
steps: trace,
recovered: final.recovered,
startedAt: final.startedAt,
completedAt: final.completedAt ?? at,
} satisfies RunSummary
})

export type { WorkflowError }

export * as WorkflowEngine from "./engine"
73 changes: 73 additions & 0 deletions packages/opencode/src/ockit/workflow/graph.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// OC Kit workflow graph validation. A workflow's ordered `steps` must each
// resolve to a skill declared by the kit (via the resolver index), must use
// unique `as` aliases, must not form a cycle, and its `onFailure` identifiers
// must also resolve to declared skills. Pure — operates on the decoded `Workflow`
// and `KitIndex`, no I/O — so it is trivially unit-testable and is invoked before
// any run.

import { Effect, Schema } from "effect"
import type { Workflow } from "../types"
import type { KitIndex } from "../resolver"
import { stepKey } from "./state"

export class WorkflowError extends Schema.TaggedErrorClass<WorkflowError>()("OCKit.WorkflowError", {
kind: Schema.Literals(["unknown-step", "unknown-onfailure", "duplicate-alias", "cycle"]),
workflowId: Schema.String,
step: Schema.optional(Schema.String),
message: Schema.optional(Schema.String),
}) {
override get message(): string {
return `OC Kit workflow: ${this.workflowId}${this.step ? ` step "${this.step}"` : ""}${this.message ? ` — ${this.message}` : ""}`
}
}

/**
* Validate a workflow graph against a kit's resolved index.
*
* Checks:
* - every `steps[].skill` resolves to a declared skill
* - every `onFailure` identifier resolves to a declared skill
* - `as` aliases are unique within the workflow (a duplicate alias would make
* the run trace ambiguous)
* - no step key equals the workflow's own id (that would re-enter the
* workflow itself — the only cycle the linear step model can express)
*/
export const validateGraph = Effect.fn("OCKit.workflow.validate")(function* (workflow: Workflow, index: KitIndex) {
for (const step of workflow.steps) {
if (!index.skills.has(step.skill)) {
return yield* new WorkflowError({ kind: "unknown-step", workflowId: workflow.id, step: stepKey(step) })
}
}

for (const id of workflow.onFailure ?? []) {
if (!index.skills.has(id)) {
return yield* new WorkflowError({ kind: "unknown-onfailure", workflowId: workflow.id, step: id })
}
}

const seen = new Set<string>()
for (const step of workflow.steps) {
const key = stepKey(step)
if (seen.has(key)) {
return yield* new WorkflowError({
kind: "duplicate-alias",
workflowId: workflow.id,
step: key,
message: `duplicate alias "${key}"`,
})
}
// A step keyed by the workflow's own id would re-enter the workflow itself —
// the only cycle the linear step model can express. (`as ?? skill` equals
// the workflow id, e.g. `{ skill: "plan", as: "ship" }` in workflow "ship".)
if (key === workflow.id) {
return yield* new WorkflowError({ kind: "cycle", workflowId: workflow.id, step: key })
}
seen.add(key)
}

return { ok: true }
})

export type GraphValidation = { readonly ok: true }

export * as Graph from "./graph"
29 changes: 29 additions & 0 deletions packages/opencode/src/ockit/workflow/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// OC Kit workflow engine — module entry. Self-exports so consumers can
// `import * as Workflow from "./workflow"` (or re-export it from src/ockit/index).
// Contains no other logic: the engine, state machine, runner, scheduler, and
// graph validator each live in their own kebab-case module.

export * as Graph from "./graph"
export * as State from "./state"
export * as Runner from "./runner"
export * as Scheduler from "./scheduler"
export { WorkflowEngine, runWorkflow, runIdFor, type RunSummary } from "./engine"
export { WorkflowError, validateGraph, type GraphValidation } from "./graph"
export {
createRecord,
applyEvent,
stepKey,
transition,
IllegalTransitionError,
type StateEvent,
type WorkflowRunRecord,
} from "./state"
export {
runSteps,
defaultExecutor,
type StepOutcome,
type StepExecutor,
type StepExecResult,
type RunOptions,
type RunResult,
} from "./runner"
182 changes: 182 additions & 0 deletions packages/opencode/src/ockit/workflow/runner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
// OC Kit workflow step runner. Executes a workflow's steps — simulated/scheduled,
// since live agent execution lands in a later phase — by driving the state
// machine in `state.ts`: each successful step advances one activity phase, a
// failed step within its retry budget is retried in place, and a step failing
// past its budget routes to the workflow's `onFailure` handlers. Records a
// deterministic per-step trace (`StepOutcome`) and returns the final run record.

import { Effect } from "effect"
import type { Workflow, WorkflowStep } from "../types"
import { applyEvent, stepKey, type WorkflowRunRecord } from "./state"
import { planBatches } from "./scheduler"

/** Per-step run outcome recorded in the run trace. */
export interface StepOutcome {
readonly key: string
readonly skill: string
readonly status: "ok" | "recovered" | "failed"
readonly attempts: number
}

/** Deterministic simulated result of executing one skill step. */
export interface StepExecResult {
readonly ok: boolean
readonly reason?: string
}

/** Executes one skill step (simulated; a later phase wires live execution). */
export type StepExecutor = (input: { readonly step: WorkflowStep; readonly attempt: number }) => StepExecResult

/** Default simulated executor: every step succeeds on its first attempt. */
export const defaultExecutor: StepExecutor = () => ({ ok: true })

export interface RunOptions {
readonly workflow: Workflow
readonly maxRetries?: number
readonly concurrency?: number
readonly executor?: StepExecutor
/** Deterministic timestamp stamped when the run terminates. */
readonly at?: string
}

export interface RunResult {
readonly record: WorkflowRunRecord
readonly trace: ReadonlyArray<StepOutcome>
}

type RunnerDeps = Required<Pick<RunOptions, "maxRetries" | "executor">>

/**
* Run one workflow step (record is in an activity phase) with its retry budget.
* A step that succeeds within budget moves the run one activity phase forward
* (`step-ok`); a failure within budget is retried in place (`retry` keeps the
* phase); a step failing past its budget leaves the run in `BLOCKED`.
*/
function runStep(
record: WorkflowRunRecord,
step: WorkflowStep,
run: RunnerDeps,
): { record: WorkflowRunRecord; outcome: StepOutcome } {
let current = record
let attempt = 0
while (true) {
const result = run.executor({ step, attempt })
if (result.ok) {
// Retries never advanced the phase (each was a `retry` event); a step
// that eventually succeeds moves the run exactly one phase forward.
return {
record: applyEvent(current, "step-ok"),
outcome: { key: stepKey(step), skill: step.skill, status: "ok", attempts: attempt + 1 },
}
}
if (attempt < run.maxRetries) {
current = applyEvent(current, "retry") // stays in the same activity phase
attempt += 1
continue
}
return {
record: applyEvent(current, "step-fail"),
outcome: { key: stepKey(step), skill: step.skill, status: "failed", attempts: attempt + 1 },
}
}
}

/**
* Attempt one `onFailure` handler (`record` is BLOCKED). Unlike a normal step,
* recovery attempts do not move the phase — the run stays BLOCKED while the
* handler is retried so a later handler can still recover it.
*/
function runRecoveryStep(
record: WorkflowRunRecord,
skill: string,
run: RunnerDeps,
): { record: WorkflowRunRecord; ok: boolean; outcome: StepOutcome } {
let attempt = 0
while (true) {
const result = run.executor({ step: { skill }, attempt })
if (result.ok) {
return { record, ok: true, outcome: { key: skill, skill, status: "recovered", attempts: attempt + 1 } }
}
if (attempt < run.maxRetries) {
attempt += 1
continue
}
return { record, ok: false, outcome: { key: skill, skill, status: "failed", attempts: attempt + 1 } }
}
}

/**
* Run the `onFailure` handlers in order until one succeeds. A succeeded handler
* completes the blocked run with `recovered: true`; if every handler fails the
* run ends `FAILED`. Each handler executed earns one trace entry.
*/
function runRecovery(
record: WorkflowRunRecord,
onFailure: ReadonlyArray<string>,
run: RunnerDeps,
at?: string,
): { record: WorkflowRunRecord; trace: ReadonlyArray<StepOutcome> } {
const trace: StepOutcome[] = []
let current = record // BLOCKED
for (const skill of onFailure) {
const handled = runRecoveryStep(current, skill, run)
trace.push(handled.outcome)
if (handled.ok) {
current = applyEvent(current, "complete", at) // BLOCKED -> COMPLETED
return { record: { ...current, recovered: true }, trace }
}
// Handler failed; try the next. The state stays BLOCKED between handlers.
}
current = applyEvent(current, "fail", at) // BLOCKED -> FAILED
return { record: current, trace }
}

/**
* Run a workflow end-to-end over its declared steps in FIFO order (a scheduler
* plan with `concurrency` bounds the dispatch shape). Each successful step
* advances one activity phase; on a step failing past its retries the run
* routes to `onFailure`. Returns the final run record plus the per-step trace.
*/
export const runSteps = Effect.fn("OCKit.workflow.run")(function* (record: WorkflowRunRecord, options: RunOptions) {
const run: RunnerDeps = {
maxRetries: options.maxRetries ?? 1,
executor: options.executor ?? defaultExecutor,
}
const trace: StepOutcome[] = []
let current = applyEvent(record, "start") // CREATED -> PLANNING

// FIFO dispatch: the scheduler plan orders step keys by release batch (one
// step per batch at concurrency 1). The simulated core executes batches in
// order, members sequentially; a live executor could dispatch a batch
// concurrently while keeping the trace order deterministic.
const ordered = planBatches(options.workflow.steps, options.concurrency ?? 1).flat()
const byKey = new Map(options.workflow.steps.map((step) => [stepKey(step), step] as const))
const orderedSteps = ordered.map((key) => byKey.get(key)).filter((step): step is WorkflowStep => step !== undefined)

const at = options.at
for (const step of orderedSteps) {
const attempt = runStep(current, step, run)
trace.push(attempt.outcome)
current = attempt.record
if (attempt.outcome.status === "failed") {
const onFailure = options.workflow.onFailure ?? []
if (onFailure.length === 0) {
current = applyEvent(current, "fail", at) // BLOCKED -> FAILED
break
}
const recovery = runRecovery(current, onFailure, run, at)
trace.push(...recovery.trace)
current = recovery.record
break
}
}

// All steps succeeded but no `complete` event fired yet (the last `step-ok`
// leaves the run in the final activity phase) — close it out.
if (current.state !== "COMPLETED" && current.state !== "FAILED") {
current = applyEvent(current, "complete", at)
}
return { record: current, trace }
})

export * as Runner from "./runner"
Loading
Loading