From c4d5326c3f7158062aa5273ec90563be9928e441 Mon Sep 17 00:00:00 2001 From: qkhalk Date: Thu, 20 Aug 2026 04:45:26 +0700 Subject: [PATCH 1/2] feat(opencode): add OC Kit workflow engine (Phase 3) --- .../opencode/src/ockit/workflow/engine.ts | 83 ++++++++ packages/opencode/src/ockit/workflow/graph.ts | 73 +++++++ packages/opencode/src/ockit/workflow/index.ts | 29 +++ .../opencode/src/ockit/workflow/runner.ts | 182 ++++++++++++++++++ .../opencode/src/ockit/workflow/scheduler.ts | 31 +++ packages/opencode/src/ockit/workflow/state.ts | 146 ++++++++++++++ .../test/ockit/workflow/engine.test.ts | 162 ++++++++++++++++ .../test/ockit/workflow/graph.test.ts | 107 ++++++++++ .../test/ockit/workflow/runner.test.ts | 181 +++++++++++++++++ .../test/ockit/workflow/scheduler.test.ts | 35 ++++ .../test/ockit/workflow/state.test.ts | 101 ++++++++++ 11 files changed, 1130 insertions(+) create mode 100644 packages/opencode/src/ockit/workflow/engine.ts create mode 100644 packages/opencode/src/ockit/workflow/graph.ts create mode 100644 packages/opencode/src/ockit/workflow/index.ts create mode 100644 packages/opencode/src/ockit/workflow/runner.ts create mode 100644 packages/opencode/src/ockit/workflow/scheduler.ts create mode 100644 packages/opencode/src/ockit/workflow/state.ts create mode 100644 packages/opencode/test/ockit/workflow/engine.test.ts create mode 100644 packages/opencode/test/ockit/workflow/graph.test.ts create mode 100644 packages/opencode/test/ockit/workflow/runner.test.ts create mode 100644 packages/opencode/test/ockit/workflow/scheduler.test.ts create mode 100644 packages/opencode/test/ockit/workflow/state.test.ts diff --git a/packages/opencode/src/ockit/workflow/engine.ts b/packages/opencode/src/ockit/workflow/engine.ts new file mode 100644 index 000000000..78b4f2986 --- /dev/null +++ b/packages/opencode/src/ockit/workflow/engine.ts @@ -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 + 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" \ No newline at end of file diff --git a/packages/opencode/src/ockit/workflow/graph.ts b/packages/opencode/src/ockit/workflow/graph.ts new file mode 100644 index 000000000..529259e6b --- /dev/null +++ b/packages/opencode/src/ockit/workflow/graph.ts @@ -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()("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() + 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" \ No newline at end of file diff --git a/packages/opencode/src/ockit/workflow/index.ts b/packages/opencode/src/ockit/workflow/index.ts new file mode 100644 index 000000000..3029e3d3e --- /dev/null +++ b/packages/opencode/src/ockit/workflow/index.ts @@ -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" \ No newline at end of file diff --git a/packages/opencode/src/ockit/workflow/runner.ts b/packages/opencode/src/ockit/workflow/runner.ts new file mode 100644 index 000000000..e5f817445 --- /dev/null +++ b/packages/opencode/src/ockit/workflow/runner.ts @@ -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 +} + +type RunnerDeps = Required> + +/** + * 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, + run: RunnerDeps, + at?: string, +): { record: WorkflowRunRecord; trace: ReadonlyArray } { + 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" \ No newline at end of file diff --git a/packages/opencode/src/ockit/workflow/scheduler.ts b/packages/opencode/src/ockit/workflow/scheduler.ts new file mode 100644 index 000000000..5ee39118f --- /dev/null +++ b/packages/opencode/src/ockit/workflow/scheduler.ts @@ -0,0 +1,31 @@ +// OC Kit workflow step scheduler. Deterministic FIFO ordering of skill steps +// with an optional max-concurrency bound: steps are dispatched in declaration +// order, oldest first, `concurrency` at a time. Pure — no I/O, no clock — so it +// is trivially unit-testable. + +import type { WorkflowStep } from "../types" +import { stepKey } from "./state" + +/** The resolved key of the first step the runner should attempt. */ +export function peek(steps: ReadonlyArray): string | undefined { + const first = steps[0] + return first ? stepKey(first) : undefined +} + +/** + * Deterministic FIFO dispatch plan for `steps` under `concurrency`: returns the + * batches in release order, each holding the resolved step keys dispatched + * together. A concurrency of 1 yields one step per batch (strict sequence); + * higher values dispatch that many head-of-line steps per batch. + */ +export function planBatches(steps: ReadonlyArray, concurrency: number): ReadonlyArray> { + const limit = Math.max(1, concurrency) + const batches: ReadonlyArray> = [] + const queue = steps.map(stepKey) + while (queue.length > 0) { + batches.push(queue.splice(0, limit)) + } + return batches +} + +export * as Scheduler from "./scheduler" \ No newline at end of file diff --git a/packages/opencode/src/ockit/workflow/state.ts b/packages/opencode/src/ockit/workflow/state.ts new file mode 100644 index 000000000..36229227e --- /dev/null +++ b/packages/opencode/src/ockit/workflow/state.ts @@ -0,0 +1,146 @@ +// OC Kit workflow run state. A pure state machine over the shared `WorkflowState` +// literals: a deterministic `(state, event) -> state` transition function that +// throws a typed `IllegalTransitionError` on any transition the machine does not +// define. Also defines the run record the engine carries through a run and the +// canonical per-step key (`as ?? skill`) shared by the graph validator and runner. + +import type { WorkflowStep, WorkflowState } from "../types" + +/** Events the state machine accepts. */ +export type StateEvent = "start" | "step-ok" | "step-fail" | "retry" | "complete" | "fail" | "cancel" + +/** Typed error raised on an illegal (undefined) transition. */ +export class IllegalTransitionError extends Error { + readonly _tag = "WorkflowIllegalTransition" as const + constructor( + readonly from: WorkflowState, + readonly event: StateEvent, + ) { + super(`Illegal workflow transition: ${from} --${event}--> ?`) + } +} + +/** + * Transition table: which `(state, event)` pairs are legal, and where they lead. + * The activity phases (`PLANNING` → `VERIFYING`) are walked one `step-ok` at a + * time; once a workflow has more steps than distinct phase labels the final + * activity state (`VERIFYING`) self-loops until the run completes. The exact + * phase labels carry no execution semantics — the runner drives them purely + * from the declared steps. + */ +const NEXT: Record>> = { + CREATED: { start: "PLANNING", cancel: "CANCELLED", fail: "FAILED" }, + PLANNING: { + "step-ok": "IMPLEMENTING", + "step-fail": "BLOCKED", + retry: "PLANNING", + complete: "COMPLETED", + fail: "FAILED", + cancel: "CANCELLED", + }, + IMPLEMENTING: { + "step-ok": "TESTING", + "step-fail": "BLOCKED", + retry: "IMPLEMENTING", + complete: "COMPLETED", + fail: "FAILED", + cancel: "CANCELLED", + }, + TESTING: { + "step-ok": "REVIEWING", + "step-fail": "BLOCKED", + retry: "TESTING", + complete: "COMPLETED", + fail: "FAILED", + cancel: "CANCELLED", + }, + REVIEWING: { + "step-ok": "VERIFYING", + "step-fail": "BLOCKED", + retry: "REVIEWING", + complete: "COMPLETED", + fail: "FAILED", + cancel: "CANCELLED", + }, + // Steps beyond the distinct phase labels keep the run in `VERIFYING`; the + // engine finishes with `complete`. + VERIFYING: { + "step-ok": "VERIFYING", + "step-fail": "BLOCKED", + retry: "VERIFYING", + complete: "COMPLETED", + fail: "FAILED", + cancel: "CANCELLED", + }, + // The run is blocked waiting for recovery (onFailure) or an explicit retry. + BLOCKED: { retry: "PLANNING", complete: "COMPLETED", fail: "FAILED", cancel: "CANCELLED" }, + COMPLETED: {}, + FAILED: {}, + CANCELLED: {}, +} + +/** + * Pure reducer: `(state, event) -> next state`. Throws `IllegalTransitionError` + * when the machine defines no transition for the pair. Side-effect-free. + */ +export function transition(state: S, event: StateEvent): WorkflowState { + const next = NEXT[state][event as StateEvent] + if (next === undefined) throw new IllegalTransitionError(state, event) + return next +} + +/** The canonical key a step is traced under: its `as` alias, else its skill id. */ +export function stepKey(step: WorkflowStep): string { + return step.as ?? step.skill +} + +/** Run record carried through a workflow run (extends, rather than changes, `types.ts`). */ +export interface WorkflowRunRecord { + readonly runId: string + readonly workflowId: string + readonly sessionId: string + readonly stepIndex: number + readonly state: WorkflowState + readonly recovered: boolean + readonly startedAt: string + readonly completedAt?: string +} + +/** Create a run record in its initial `CREATED` state. */ +export function createRecord(input: { + readonly runId: string + readonly workflowId: string + readonly sessionId: string + readonly at?: string +}): WorkflowRunRecord { + return { + runId: input.runId, + workflowId: input.workflowId, + sessionId: input.sessionId, + stepIndex: 0, + state: "CREATED", + recovered: false, + startedAt: input.at ?? new Date().toISOString(), + } +} + +/** + * Apply an event to a run record: advances the state via `transition`, bumps + * `stepIndex` on `step-ok`, and stamps `completedAt` on a terminal state. + * Pure; throws `IllegalTransitionError` on illegal events. `at` is the optional + * deterministic timestamp to stamp when the run terminates (defaults to the + * wall clock so callers that never pass a clock still get an ISO timestamp). + */ +export function applyEvent(record: WorkflowRunRecord, event: StateEvent, at?: string): WorkflowRunRecord { + const state = transition(record.state, event) + const stepIndex = event === "step-ok" ? record.stepIndex + 1 : record.stepIndex + const terminal = state === "COMPLETED" || state === "FAILED" || state === "CANCELLED" + return { + ...record, + state, + stepIndex, + completedAt: terminal ? record.completedAt ?? at ?? new Date().toISOString() : record.completedAt, + } +} + +export * as State from "./state" \ No newline at end of file diff --git a/packages/opencode/test/ockit/workflow/engine.test.ts b/packages/opencode/test/ockit/workflow/engine.test.ts new file mode 100644 index 000000000..3d8898b94 --- /dev/null +++ b/packages/opencode/test/ockit/workflow/engine.test.ts @@ -0,0 +1,162 @@ +import { describe, expect } from "bun:test" +import { it } from "../../lib/effect" +import { Cause, Effect } from "effect" +import type { Kit, Workflow } from "../../../src/ockit/types" +import { runWorkflow, runIdFor, type RunSummary } from "../../../src/ockit/workflow/engine" +import { WorkflowError } from "../../../src/ockit/workflow/graph" +import type { StepExecutor } from "../../../src/ockit/workflow/runner" + +const KIT: Kit = { + id: "engineer", + name: "OC Engineer Kit", + version: "1.0.0", + runtime: "opencode", + skills: [ + { id: "ask", description: "Clarify requirements" }, + { id: "plan", description: "Create a plan" }, + { id: "implement", description: "Write code" }, + { id: "test", description: "Run tests" }, + { id: "review", description: "Review changes" }, + { id: "verify", description: "Verify the outcome" }, + { id: "reproduce", description: "Reproduce a bug" }, + { id: "diagnose", description: "Diagnose a bug" }, + { id: "root-cause", description: "Root-cause analysis" }, + { id: "patch", description: "Patch the defect" }, + { id: "regression-check", description: "Check for regressions" }, + { id: "fix", description: "Apply a fix" }, + ], + workflows: [], +} + +const FEATURE: Workflow = { + id: "feature-development", + steps: [ + { skill: "ask" }, + { skill: "plan" }, + { skill: "implement" }, + { skill: "test" }, + { skill: "review" }, + { skill: "verify" }, + ], +} + +const BUGFIX: Workflow = { + id: "bug-fix", + steps: [ + { skill: "reproduce" }, + { skill: "diagnose" }, + { skill: "root-cause" }, + { skill: "patch" }, + { skill: "test" }, + { skill: "regression-check" }, + { skill: "review" }, + ], +} + +/** Executor that fails `skill` a fixed number of times then succeeds. */ +function failTimes(skill: string, times: number): StepExecutor { + let failures = times + return (input) => { + if (input.step.skill === skill && failures > 0) { + failures -= 1 + return { ok: false, reason: `simulated failure of ${skill}` } + } + return { ok: true } + } +} + +describe("ockit workflow engine", () => { + it.effect("returns a deterministic RunSummary for feature-development", () => + Effect.gen(function* () { + const at = "2026-08-20T00:00:00.000Z" + const summary = yield* runWorkflow({ + kit: KIT, + workflow: FEATURE, + sessionId: "s1", + runId: "custom-run", + at, + }) + expect(summary).toMatchObject({ + workflowId: "feature-development", + runId: "custom-run", + state: "COMPLETED", + recovered: false, + startedAt: at, + completedAt: at, + }) + expect(summary).toHaveProperty("steps") + expect(summary.steps.map((o) => o.skill)).toEqual( + FEATURE.steps.map((s) => s.skill), + ) + })) + + it.effect("runs bug-fix end-to-end to COMPLETED", () => + Effect.gen(function* () { + const summary = yield* runWorkflow({ kit: KIT, workflow: BUGFIX, sessionId: "s1" }) + expect(summary.state).toBe("COMPLETED") + expect(summary.recovered).toBe(false) + expect(summary.steps).toHaveLength(7) + expect(summary.steps[0]?.skill).toBe("reproduce") + expect(summary.steps[6]?.skill).toBe("review") + })) + + it.effect("recovers via onFailure and completes with recovered: true", () => + Effect.gen(function* () { + const withRecovery = { ...FEATURE, onFailure: ["fix"] } + const summary = yield* runWorkflow({ + kit: KIT, + workflow: withRecovery, + maxRetries: 1, + executor: failTimes("test", 2), // exhausts the budget once + }) + expect(summary.state).toBe("COMPLETED") + expect(summary.recovered).toBe(true) + const fix = summary.steps.find((o) => o.skill === "fix") + expect(fix?.status).toBe("recovered") + })) + + it.effect("ends FAILED when onFailure also fails", () => + Effect.gen(function* () { + const withRecovery = { ...FEATURE, onFailure: ["fix"] } + const alwaysFail: StepExecutor = (input) => ({ + ok: false, + reason: `simulated failure of ${input.step.skill}`, + }) + const summary = yield* runWorkflow({ + kit: KIT, + workflow: withRecovery, + maxRetries: 1, + executor: alwaysFail, + }) + expect(summary.state).toBe("FAILED") + expect(summary.recovered).toBe(false) + })) + + it.effect("fails with a typed WorkflowError on an unknown step", () => + Effect.gen(function* () { + const broken: Workflow = { id: "broken", steps: [{ skill: "ghost-skill" }] } + const exit = yield* runWorkflow({ kit: KIT, workflow: broken, sessionId: "s1" }).pipe(Effect.exit) + expect(exit._tag).toBe("Failure") + if (exit._tag === "Failure") { + const error = Cause.squash(exit.cause) + expect(error).toBeInstanceOf(WorkflowError) + expect((error as WorkflowError).kind).toBe("unknown-step") + expect((error as WorkflowError).workflowId).toBe("broken") + } + })) + + it.effect("derives a deterministic run id from the workflow", () => + Effect.sync(() => { + expect(runIdFor(FEATURE)).toBe("feature-development-6") + expect(runIdFor(BUGFIX)).toBe("bug-fix-7") + })) + + it.effect("summary fields are stable across runs (deterministic)", () => + Effect.gen(function* () { + const at = "2026-08-20T00:00:00.000Z" + const a = yield* runWorkflow({ kit: KIT, workflow: FEATURE, sessionId: "s", runId: "r", at }) + const b = yield* runWorkflow({ kit: KIT, workflow: FEATURE, sessionId: "s", runId: "r", at }) + expect(a).toEqual(b) + const _unused: RunSummary = a + })) +}) \ No newline at end of file diff --git a/packages/opencode/test/ockit/workflow/graph.test.ts b/packages/opencode/test/ockit/workflow/graph.test.ts new file mode 100644 index 000000000..93d4a5f98 --- /dev/null +++ b/packages/opencode/test/ockit/workflow/graph.test.ts @@ -0,0 +1,107 @@ +import { describe, expect } from "bun:test" +import { it } from "../../lib/effect" +import { Cause, Effect } from "effect" +import type { Kit, Workflow } from "../../../src/ockit/types" +import { indexKit } from "../../../src/ockit/resolver" +import { validateGraph, WorkflowError } from "../../../src/ockit/workflow/graph" + +const KIT: Kit = { + id: "engineer", + name: "OC Engineer Kit", + version: "1.0.0", + runtime: "opencode", + skills: [ + { id: "ask", description: "Clarify requirements" }, + { id: "plan", description: "Create a plan" }, + { id: "implement", description: "Write code" }, + { id: "test", description: "Run tests" }, + { id: "review", description: "Review changes" }, + { id: "verify", description: "Verify the outcome" }, + { id: "reproduce", description: "Reproduce a bug" }, + { id: "fix", description: "Fix the defect" }, + ], + workflows: [], +} + +/** Validate a workflow against the fixture index, returning its Exit. */ +function validateExit(workflow: Workflow) { + return validateGraph(workflow, indexKit(KIT)).pipe(Effect.exit) +} + +describe("ockit workflow graph", () => { + it.effect("accepts a workflow whose steps all resolve", () => + Effect.gen(function* () { + const exit = yield* validateExit({ id: "feature-development", steps: KIT.skills.map((s) => ({ skill: s.id })) }) + expect(exit._tag).toBe("Success") + })) + + it.effect("rejects a step that references an undeclared skill", () => + Effect.gen(function* () { + const exit = yield* validateExit({ id: "ship", steps: [{ skill: "plan" }, { skill: "ghost-skill" }] }) + expect(exit._tag).toBe("Failure") + if (exit._tag === "Failure") { + const error = Cause.squash(exit.cause) + expect(error).toBeInstanceOf(WorkflowError) + expect((error as WorkflowError).kind).toBe("unknown-step") + expect((error as WorkflowError).workflowId).toBe("ship") + expect((error as WorkflowError).step).toBe("ghost-skill") + } + })) + + it.effect("rejects an onFailure id that resolves to no declared skill", () => + Effect.gen(function* () { + const exit = yield* validateExit({ + id: "ship", + steps: [{ skill: "plan" }], + onFailure: ["fix", "missing-handler"], + }) + expect(exit._tag).toBe("Failure") + if (exit._tag === "Failure") { + const error = Cause.squash(exit.cause) + expect(error).toBeInstanceOf(WorkflowError) + expect((error as WorkflowError).kind).toBe("unknown-onfailure") + expect((error as WorkflowError).step).toBe("missing-handler") + } + })) + + it.effect("rejects duplicate as aliases within one workflow", () => + Effect.gen(function* () { + const exit = yield* validateExit({ + id: "ship", + steps: [ + { skill: "plan", as: "step-one" }, + { skill: "implement", as: "step-one" }, + ], + }) + expect(exit._tag).toBe("Failure") + if (exit._tag === "Failure") { + const error = Cause.squash(exit.cause) + expect(error).toBeInstanceOf(WorkflowError) + expect((error as WorkflowError).kind).toBe("duplicate-alias") + expect((error as WorkflowError).step).toBe("step-one") + } + })) + + it.effect("rejects a step that would re-enter the workflow itself", () => + Effect.gen(function* () { + const exit = yield* validateExit({ id: "ship", steps: [{ skill: "plan", as: "ship" }] }) + expect(exit._tag).toBe("Failure") + if (exit._tag === "Failure") { + const error = Cause.squash(exit.cause) + expect(error).toBeInstanceOf(WorkflowError) + expect((error as WorkflowError).kind).toBe("cycle") + } + })) + + it.effect("same skill used twice with distinct aliases is allowed", () => + Effect.gen(function* () { + const exit = yield* validateExit({ + id: "double", + steps: [ + { skill: "test", as: "unit" }, + { skill: "test", as: "integration" }, + ], + }) + expect(exit._tag).toBe("Success") + })) +}) \ No newline at end of file diff --git a/packages/opencode/test/ockit/workflow/runner.test.ts b/packages/opencode/test/ockit/workflow/runner.test.ts new file mode 100644 index 000000000..32a2a9af5 --- /dev/null +++ b/packages/opencode/test/ockit/workflow/runner.test.ts @@ -0,0 +1,181 @@ +import { describe, expect } from "bun:test" +import { it } from "../../lib/effect" +import { Effect } from "effect" +import type { Kit, Workflow } from "../../../src/ockit/types" +import { createRecord } from "../../../src/ockit/workflow/state" +import { runSteps, defaultExecutor, type StepExecutor } from "../../../src/ockit/workflow/runner" +import { indexKit } from "../../../src/ockit/resolver" +import { validateGraph } from "../../../src/ockit/workflow/graph" + +const KIT: Kit = { + id: "engineer", + name: "OC Engineer Kit", + version: "1.0.0", + runtime: "opencode", + skills: [ + { id: "ask", description: "Clarify requirements" }, + { id: "plan", description: "Create a plan" }, + { id: "implement", description: "Write code" }, + { id: "test", description: "Run tests" }, + { id: "review", description: "Review changes" }, + { id: "verify", description: "Verify the outcome" }, + { id: "reproduce", description: "Reproduce a bug" }, + { id: "diagnose", description: "Diagnose a bug" }, + { id: "root-cause", description: "Root-cause analysis" }, + { id: "patch", description: "Patch the defect" }, + { id: "regression-check", description: "Check for regressions" }, + { id: "fix", description: "Apply a fix" }, + ], + workflows: [], +} + +const FEATURE: Workflow = { + id: "feature-development", + steps: [ + { skill: "ask" }, + { skill: "plan" }, + { skill: "implement" }, + { skill: "test" }, + { skill: "review" }, + { skill: "verify" }, + ], +} + +const BUGFIX: Workflow = { + id: "bug-fix", + steps: [ + { skill: "reproduce" }, + { skill: "diagnose" }, + { skill: "root-cause" }, + { skill: "patch" }, + { skill: "test" }, + { skill: "regression-check" }, + { skill: "review" }, + ], +} + +function record(workflow: Workflow) { + return createRecord({ runId: "r", workflowId: workflow.id, sessionId: "s", at: "2026-08-20T00:00:00.000Z" }) +} + +/** Executor that fails `skill` the first `times` attempts, then succeeds. */ +function failing(skill: string, times: number): StepExecutor { + let failures = times + return (input) => { + if (input.step.skill === skill && failures > 0) { + failures -= 1 + return { ok: false, reason: `simulated failure of ${skill}` } + } + return { ok: true } + } +} + +/** Executor that always fails the named skill; others succeed. */ +function neverSucceeds(skill: string): StepExecutor { + return (input) => + input.step.skill === skill + ? { ok: false, reason: `simulated failure of ${skill}` } + : { ok: true } +} + +describe("ockit workflow runner", () => { + it.effect("runs feature-development to COMPLETED with a per-step trace", () => + Effect.gen(function* () { + const result = yield* runSteps(record(FEATURE), { workflow: FEATURE }) + expect(result.record.state).toBe("COMPLETED") + expect(result.record.recovered).toBe(false) + expect(result.trace.map((o) => o.skill)).toEqual(["ask", "plan", "implement", "test", "review", "verify"]) + for (const outcome of result.trace) { + expect(outcome.status).toBe("ok") + expect(outcome.attempts).toBe(1) + } + })) + + it.effect("runs bug-fix to COMPLETED with a per-step trace", () => + Effect.gen(function* () { + const result = yield* runSteps(record(BUGFIX), { workflow: BUGFIX }) + expect(result.record.state).toBe("COMPLETED") + expect(result.trace.map((o) => o.skill)).toEqual([ + "reproduce", + "diagnose", + "root-cause", + "patch", + "test", + "regression-check", + "review", + ]) + expect(result.trace.every((o) => o.status === "ok")).toBe(true) + })) + + it.effect("retries a step within its budget and records attempts", () => + Effect.gen(function* () { + // The executor fails "plan" exactly once (attempt 0), then succeeds. + const result = yield* runSteps(record(FEATURE), { + workflow: FEATURE, + maxRetries: 2, + executor: failing("plan", 1), + }) + expect(result.record.state).toBe("COMPLETED") + const plan = result.trace.find((o) => o.skill === "plan") + expect(plan?.status).toBe("ok") + expect(plan?.attempts).toBe(2) + })) + + it.effect("fails the run without an onFailure handler", () => + Effect.gen(function* () { + const result = yield* runSteps(record(FEATURE), { + workflow: FEATURE, + maxRetries: 1, + executor: neverSucceeds("implement"), + }) + expect(result.record.state).toBe("FAILED") + const implement = result.trace.find((o) => o.skill === "implement") + expect(implement?.status).toBe("failed") + expect(implement?.attempts).toBe(2) // original attempt + one retry + })) + + it.effect("routes to onFailure and recovers when the handler succeeds", () => + Effect.gen(function* () { + const withRecovery = { ...FEATURE, onFailure: ["fix"] } + // `validateGraph` is the caller's job; the runner trusts its input. + yield* validateGraph(withRecovery, indexKit(KIT)) + const result = yield* runSteps(record(withRecovery), { + workflow: withRecovery, + maxRetries: 1, + executor: failing("implement", 99), + }) + expect(result.record.state).toBe("COMPLETED") + expect(result.record.recovered).toBe(true) + const fix = result.trace.find((o) => o.skill === "fix") + expect(fix?.status).toBe("recovered") + })) + + it.effect("ends FAILED when onFailure also fails", () => + Effect.gen(function* () { + const withRecovery = { ...FEATURE, onFailure: ["fix"] } + yield* validateGraph(withRecovery, indexKit(KIT)) + const alwaysFail: StepExecutor = () => ({ ok: false, reason: "always fails" }) + const result = yield* runSteps(record(withRecovery), { + workflow: withRecovery, + maxRetries: 1, + executor: alwaysFail, + }) + expect(result.record.state).toBe("FAILED") + expect(result.record.recovered).toBe(false) + const last = result.trace[result.trace.length - 1] + expect(last?.status).toBe("failed") + })) + + it.effect("runs steps with the default executor (all succeed)", () => + Effect.gen(function* () { + expect(defaultExecutor({ step: { skill: "anything" }, attempt: 0 })).toEqual({ ok: true }) + const result = yield* runSteps(record(FEATURE), { workflow: FEATURE }) + expect(result.record.state).toBe("COMPLETED") + })) + + it.effect("preserves deterministic FIFO order under concurrency > 1", () => + Effect.gen(function* () { + const result = yield* runSteps(record(FEATURE), { workflow: FEATURE, concurrency: 3 }) + expect(result.trace.map((o) => o.skill)).toEqual(["ask", "plan", "implement", "test", "review", "verify"]) + })) +}) \ No newline at end of file diff --git a/packages/opencode/test/ockit/workflow/scheduler.test.ts b/packages/opencode/test/ockit/workflow/scheduler.test.ts new file mode 100644 index 000000000..a453271af --- /dev/null +++ b/packages/opencode/test/ockit/workflow/scheduler.test.ts @@ -0,0 +1,35 @@ +import { describe, expect } from "bun:test" +import type { WorkflowStep } from "../../../src/ockit/types" +import { planBatches, peek } from "../../../src/ockit/workflow/scheduler" + +const steps: ReadonlyArray = [ + { skill: "a" }, + { skill: "b", as: "bee" }, + { skill: "c" }, +] + +describe("ockit workflow scheduler", () => { + it("plans strict FIFO (one step per batch) at concurrency 1", () => { + expect(planBatches(steps, 1)).toEqual([["a"], ["bee"], ["c"]]) + }) + + it("groups head-of-line steps under higher concurrency", () => { + expect(planBatches(steps, 2)).toEqual([["a", "bee"], ["c"]]) + expect(planBatches(steps, 10)).toEqual([["a", "bee", "c"]]) + }) + + it("clamps concurrency to at least 1", () => { + expect(planBatches(steps, 0)).toEqual(planBatches(steps, 1)) + }) + + it("preserves declaration order regardless of batch width", () => { + for (const concurrency of [1, 2, 3, 10]) { + expect(planBatches(steps, concurrency).flat()).toEqual(["a", "bee", "c"]) + } + }) + + it("peeks the first step key", () => { + expect(peek(steps)).toBe("a") + expect(peek([])).toBeUndefined() + }) +}) \ No newline at end of file diff --git a/packages/opencode/test/ockit/workflow/state.test.ts b/packages/opencode/test/ockit/workflow/state.test.ts new file mode 100644 index 000000000..e14838745 --- /dev/null +++ b/packages/opencode/test/ockit/workflow/state.test.ts @@ -0,0 +1,101 @@ +import { describe, expect } from "bun:test" +import { it } from "../../lib/effect" +import { Effect } from "effect" +import type { WorkflowStep } from "../../../src/ockit/types" +import { + transition, + applyEvent, + createRecord, + stepKey, + IllegalTransitionError, +} from "../../../src/ockit/workflow/state" + +describe("ockit workflow state", () => { + describe("transition", () => { + it.effect("starts CREATED -> PLANNING", () => + Effect.sync(() => { + expect(transition("CREATED", "start")).toBe("PLANNING") + })) + + it.effect("advances the activity phases on step-ok", () => + Effect.sync(() => { + let state = transition("CREATED", "start") + expect(state).toBe("PLANNING") + state = transition(state, "step-ok") + expect(state).toBe("IMPLEMENTING") + state = transition(state, "step-ok") + expect(state).toBe("TESTING") + state = transition(state, "step-ok") + expect(state).toBe("REVIEWING") + state = transition(state, "step-ok") + expect(state).toBe("VERIFYING") + // Beyond the distinct phase labels, VERIFYING self-loops. + state = transition(state, "step-ok") + expect(state).toBe("VERIFYING") + })) + + it.effect("blocks on step-fail and retries in place", () => + Effect.sync(() => { + expect(transition("PLANNING", "step-fail")).toBe("BLOCKED") + expect(transition("BLOCKED", "retry")).toBe("PLANNING") + expect(transition("IMPLEMENTING", "step-fail")).toBe("BLOCKED") + expect(transition("IMPLEMENTING", "retry")).toBe("IMPLEMENTING") + })) + + it.effect("closes terminal states", () => + Effect.sync(() => { + expect(transition("VERIFYING", "complete")).toBe("COMPLETED") + expect(transition("BLOCKED", "complete")).toBe("COMPLETED") + expect(transition("BLOCKED", "fail")).toBe("FAILED") + expect(transition("PLANNING", "fail")).toBe("FAILED") + expect(transition("CREATED", "cancel")).toBe("CANCELLED") + })) + + it.effect("throws a typed error on an illegal transition", () => + Effect.sync(() => { + expect(() => transition("CREATED", "step-ok")).toThrow(IllegalTransitionError) + expect(() => transition("COMPLETED", "start")).toThrow("Illegal workflow transition") + expect(() => transition("FAILED", "retry")).toThrow(IllegalTransitionError) + })) + }) + + describe("applyEvent / createRecord", () => { + it.effect("creates a record in CREATED with the given ids", () => + Effect.sync(() => { + const record = createRecord({ runId: "wf-1", workflowId: "feature-development", sessionId: "s1", at: "2026-08-20T00:00:00.000Z" }) + expect(record.state).toBe("CREATED") + expect(record.stepIndex).toBe(0) + expect(record.recovered).toBe(false) + expect(record.startedAt).toBe("2026-08-20T00:00:00.000Z") + })) + + it.effect("bumps stepIndex only on step-ok", () => + Effect.sync(() => { + let record = applyEvent(createRecord({ runId: "r", workflowId: "w", sessionId: "s", at: "t" }), "start") + record = applyEvent(record, "step-ok") + expect(record.stepIndex).toBe(1) + record = applyEvent(record, "step-fail") + expect(record.stepIndex).toBe(1) // failure does not advance + record = applyEvent(record, "retry") + expect(record.stepIndex).toBe(1) + })) + + it.effect("stamps completedAt on terminal completion", () => + Effect.sync(() => { + let record = applyEvent(createRecord({ runId: "r", workflowId: "w", sessionId: "s", at: "t0" }), "start") + record = applyEvent(record, "complete") + expect(record.state).toBe("COMPLETED") + expect(record.completedAt).toBeDefined() + })) + }) + + describe("stepKey", () => { + it.effect("uses the as alias when present, else the skill", () => + Effect.sync(() => { + const aliased: WorkflowStep = { skill: "plan", as: "planner" } + const plain: WorkflowStep = { skill: "test" } + expect(stepKey(aliased)).toBe("planner") + expect(stepKey(plain)).toBe("test") + })) + }) +}) \ No newline at end of file From 34dcf43c8b72bf41123a876ad6cb227d8371f9c5 Mon Sep 17 00:00:00 2001 From: qkhalk Date: Thu, 20 Aug 2026 04:49:25 +0700 Subject: [PATCH 2/2] fix(opencode): satisfy typecheck errors in ockit workflow modules --- packages/opencode/src/ockit/workflow/scheduler.ts | 2 +- packages/opencode/test/ockit/workflow/graph.test.ts | 2 +- packages/opencode/test/ockit/workflow/scheduler.test.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/opencode/src/ockit/workflow/scheduler.ts b/packages/opencode/src/ockit/workflow/scheduler.ts index 5ee39118f..60dd72a05 100644 --- a/packages/opencode/src/ockit/workflow/scheduler.ts +++ b/packages/opencode/src/ockit/workflow/scheduler.ts @@ -20,7 +20,7 @@ export function peek(steps: ReadonlyArray): string | undefined { */ export function planBatches(steps: ReadonlyArray, concurrency: number): ReadonlyArray> { const limit = Math.max(1, concurrency) - const batches: ReadonlyArray> = [] + const batches: string[][] = [] const queue = steps.map(stepKey) while (queue.length > 0) { batches.push(queue.splice(0, limit)) diff --git a/packages/opencode/test/ockit/workflow/graph.test.ts b/packages/opencode/test/ockit/workflow/graph.test.ts index 93d4a5f98..65f17e29e 100644 --- a/packages/opencode/test/ockit/workflow/graph.test.ts +++ b/packages/opencode/test/ockit/workflow/graph.test.ts @@ -31,7 +31,7 @@ function validateExit(workflow: Workflow) { describe("ockit workflow graph", () => { it.effect("accepts a workflow whose steps all resolve", () => Effect.gen(function* () { - const exit = yield* validateExit({ id: "feature-development", steps: KIT.skills.map((s) => ({ skill: s.id })) }) + const exit = yield* validateExit({ id: "feature-development", steps: (KIT.skills ?? []).map((s) => ({ skill: s.id })) }) expect(exit._tag).toBe("Success") })) diff --git a/packages/opencode/test/ockit/workflow/scheduler.test.ts b/packages/opencode/test/ockit/workflow/scheduler.test.ts index a453271af..e3dcfb94f 100644 --- a/packages/opencode/test/ockit/workflow/scheduler.test.ts +++ b/packages/opencode/test/ockit/workflow/scheduler.test.ts @@ -1,4 +1,4 @@ -import { describe, expect } from "bun:test" +import { describe, expect, it } from "bun:test" import type { WorkflowStep } from "../../../src/ockit/types" import { planBatches, peek } from "../../../src/ockit/workflow/scheduler"