Open History to see the last commit
1// Grades a workflow file the way the server would use it: loaded by the real loader, registered
2// in the real engine on a throwaway database, and driven with a stand-in for agents.
3import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Result from "effect/Result";
12import * as Stream from "effect/Stream";
13
14import WorkflowsMigration from "../../apps/server/src/persistence/Migrations/110_Workflows.ts";
15import type { WorkflowDefinition } from "../../apps/server/src/workflows/workflow.ts";
16import {
17 type AgentResult,
18 WorkflowAgents,
19} from "../../apps/server/src/workflows/WorkflowAgents.ts";
20import * as WorkflowEngine from "../../apps/server/src/workflows/WorkflowEngine.ts";
21import { loadDefinitions } from "../../apps/server/src/workflows/WorkflowRuntime.ts";
22import * as Workflows from "../../apps/server/src/workflows/Workflows.ts";
23import type { WorkflowRun } from "../../apps/server/src/workflows/WorkflowStore.ts";
24
25export type AgentTurnInput = Parameters<WorkflowAgents["Service"]["start"]>[0];
26
27/**
28 * One server holding the file's workflows. Each `server` call is one lifetime of it: the file
29 * loaded afresh and a new engine on the same database, as after a restart.
30 */
31export interface World {
32 readonly definitions: ReadonlyArray<WorkflowDefinition>;
33 /** Every agent turn the workflows asked for, in order. */
34 readonly turns: ReadonlyArray<AgentTurnInput>;
35 readonly server: <A>(
36 use: (workflows: Workflows.Workflows["Service"]) => Effect.Effect<A, Workflows.WorkflowError>,
37 ) => Effect.Effect<A, Workflows.WorkflowError>;
38 /** The run once it is in one of these states, or nothing after ten seconds. */
39 readonly reaches: (
40 workflows: Workflows.Workflows["Service"],
41 runId: string,
42 ...statuses: ReadonlyArray<WorkflowRun["status"]>
43 ) => Effect.Effect<Option.Option<WorkflowRun>>;
44 /** The name of the question the run asks a person, or nothing after ten seconds. */
45 readonly asks: (
46 workflows: Workflows.Workflows["Service"],
47 runId: string,
48 ) => Effect.Effect<Option.Option<string>>;
49}
50
51export interface Case {
52 readonly id: string;
53 readonly source: string;
54 /** What the model is asked to write. */
55 readonly task: string;
56 /** What a fake agent answers. Each scenario of the case sets its own. */
57 readonly scenarios: ReadonlyArray<{
58 readonly name: string;
59 readonly agent: (turn: AgentTurnInput) => Partial<AgentResult>;
60 /** The problems found. None is a pass. */
61 readonly check: (world: World) => Effect.Effect<ReadonlyArray<string>, Workflows.WorkflowError>;
62 }>;
63}
64
65// Across every grade in the process: a load under an address used before would get that module.
66let lifetimes = 0;
67
68const world = Effect.fn("gradeWorkflow.world")(function* (
69 file: string,
70 definitions: ReadonlyArray<WorkflowDefinition>,
71 agent: (turn: AgentTurnInput) => Partial<AgentResult>,
72) {
73 const fileSystem = yield* FileSystem.FileSystem;
74 const path = yield* Path.Path;
75 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflow-eval-" });
76 const database = NodeSqliteClient.layer({ filename: path.join(directory, "state.sqlite") });
77 yield* Effect.provide(WorkflowsMigration, database);
78 const turns: Array<AgentTurnInput> = [];
79 const asked = new Map<string, AgentTurnInput>();
80 const agents = WorkflowAgents.of({
81 start: Effect.fn("gradeWorkflow.agents.start")(function* (input) {
82 if (!asked.has(input.key)) {
83 asked.set(input.key, input);
84 turns.push(input);
85 }
86 return yield* Effect.succeed({
87 threadId: input.thread ?? `thread-${input.key}`,
88 turnId: input.key,
89 });
90 }),
91 result: Effect.fn("gradeWorkflow.agents.result")(function* (turn) {
92 return yield* Effect.succeed({
93 ending: "completed" as const,
94 detail: "",
95 reply: "",
96 ...agent(asked.get(turn.turnId)!),
97 });
98 }),
99 // Every turn here has already completed, so there is nothing to stop.
100 interrupt: Effect.fn("gradeWorkflow.agents.interrupt")(function* () {
101 return yield* Effect.succeed("ended" as const);
102 }),
103 });
104 const engine = (loaded: ReadonlyArray<WorkflowDefinition>) =>
105 WorkflowEngine.layer(loaded).pipe(
106 Layer.provide(Layer.succeed(WorkflowAgents, agents)),
107 Layer.provide(database),
108 Layer.provide(NodeCrypto.layer),
109 Layer.orDie,
110 );
111 return {
112 definitions,
113 turns,
114 server: (use) =>
115 loadDefinitions(file, ++lifetimes).pipe(
116 Effect.orDie,
117 Effect.provideService(Path.Path, path),
118 Effect.flatMap((loaded) =>
119 Effect.scoped(Effect.provide(Effect.flatMap(Workflows.Workflows, use), engine(loaded))),
120 ),
121 ),
122 reaches: (workflows, runId, ...statuses) =>
123 workflows
124 .waitFor(runId, (run) => statuses.includes(run.status))
125 .pipe(Effect.timeoutOption("10 seconds")),
126 asks: (workflows, runId) =>
127 workflows.watch.pipe(
128 Stream.filterMap((snapshot) => {
129 const question = snapshot.questions.find((asked) => asked.runId === runId);
130 return question === undefined ? Result.failVoid : Result.succeed(question.name);
131 }),
132 Stream.runHead,
133 Effect.timeoutOption("10 seconds"),
134 Effect.map(Option.flatten),
135 ),
136 } satisfies World;
137});
138
139const problemsWith = Effect.fn("gradeWorkflow.problemsWith")(function* (file: string, entry: Case) {
140 const loaded = yield* Effect.result(loadDefinitions(file));
141 if (loaded._tag === "Failure") {
142 return [`The file does not load: ${String(loaded.failure.cause)}`];
143 }
144 const problems: Array<string> = [];
145 for (const scenario of entry.scenarios) {
146 const found = yield* world(file, loaded.success, scenario.agent).pipe(
147 Effect.flatMap(scenario.check),
148 Effect.scoped,
149 Effect.catch((error) => Effect.succeed([error.message])),
150 Effect.catchDefect((defect) => Effect.succeed([`It crashed: ${String(defect)}`])),
151 );
152 problems.push(...found.map((problem) => `${scenario.name}: ${problem}`));
153 }
154 return problems;
155});
156
157/** The problems with the workflow file at `file` as an answer to `entry`. None is a pass. */
158export const grade = (file: string, entry: Case): Promise<ReadonlyArray<string>> =>
159 Effect.runPromise(Effect.provide(problemsWith(file, entry), NodeServices.layer));