draft.test.ts
This file
Path
apps/platform/test/workflows/draft.test.ts
661 lines · 19.8 KiB · TypeScript
Last changed by
Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
History of this fileTake it
Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f
lines 1–23why, one step back1import { describe, expect, expectTypeOf, it } from "@effect/vitest";2import type { RepoHost } from "@repo/artifacts/repo-host";3import { CheckAt } from "@repo/checks/check-runner";4import { DraftFailed } from "@repo/drafting/drafted";5import type { DraftedAsk } from "@repo/drafting/drafted";6import type { Drafter } from "@repo/drafting/drafter";7import type { AiLike } from "@repo/drafting/drafter/binding";8import { DrafterMemory, DraftsAsked } from "@repo/drafting/drafter/memory";9import { draftedFiles } from "@repo/drafting/render";10import { DraftModel } from "@repo/drafting/run";11import { DraftRuns } from "@repo/project/draft-runs";12import { Lander } from "@repo/project/lander";13import type { ProjectApi } from "@repo/project/project";14import { Projects } from "@repo/project/projects";15import { DecisionSubject } from "@repo/protocol/domain/decision";16import { DraftState } from "@repo/protocol/domain/proposal";17import {18 AskId,19 LandedSha,20 LaneName,21 ProjectName,22 ProposalId,23 RepoName,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 24why, one step back24 keyOf,Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f
lines 25–54why, one step back25 RepoPath,26} from "@repo/protocol/ids";27import { Anonymous, Person } from "@repo/protocol/principal";28import { CapReached } from "@repo/protocol/refusal";29import { advanceTo } from "@repo/testkit/clock";30import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";31import { Array, Context, Effect, Layer, Option, Ref, Schema } from "effect";3233import { DraftRunsWorkflow } from "../../src/adapters/draft-runs-workflow.ts";34import type { DraftWorkflow } from "../../src/adapters/draft-runs-workflow.ts";35import { DraftParams, draftId } from "../../src/answer-runs.ts";36import { Handlers } from "../../src/handlers.ts";37import type { PlatformConfig } from "../../src/platform.ts";38import { runDraftWorkflow } from "../../src/workflows/answer.ts";39import type { EngineSteps } from "../../src/workflows/draft-steps.ts";40import { draftSteps } from "../../src/workflows/draft-steps.ts";41import { memoSteps, StepRunner } from "../../src/workflows/step.ts";42import type { StepRetry } from "../../src/workflows/step.ts";43import { as, seeded, worldOf } from "../handlers.fixtures.ts";44import { Checker, Pusher, worldWith } from "./answer.fixtures.ts";4546type EngineConfig = Parameters<EngineSteps["do"]>[1];4748const scenario = aProject({ people: ["carol"] }).pipe(49 withVouches(["carol"]),50 withAsk({ id: "parse-week", territory: "." })51);5253const { policy, project } = scenario;54Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 55why, one step back55const repo = RepoName.make(keyOf(project));Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f
lines 56–73why, one step back5657const alice = Person.make({ handle: scenario.initializer });5859const carol = Person.make({60 handle: scenario.people.get("carol") ?? scenario.initializer,61});6263const redThenGreen = LaneName.make("redThenGreen");6465const model = "@cf/moonshotai/kimi-k2.7-code";6667const want = "Parse an ISO week date such as 2026-W41";6869const proposal = ProposalId.make("prop-000001");7071const params = DraftParams.make({ project, proposal, round: 1 });7273const start = [Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 74why, one step back74 ["package.json", '{ "name": "alice/datekit", "type": "module" }\n'],Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f
lines 75–479why, one step back75 ["src/parse.ts", "export const parse = (s) => ({});\n"],76] as const;7778const draftOf = (assertion: string, id = "parse-week"): DraftedAsk => ({79 id: AskId.make(id),80 kind: "fix",81 rationale: `${id}: parseWeek is missing, so its test fails by an assertion`,82 territory: [RepoPath.make("src/parse.ts")],83 test: {84 path: RepoPath.make(`test/${id}.test.ts`),85 source: [86 'import { expect, it } from "bun:test";',87 'import { parse } from "../src/parse.ts";',88 "",89 `it("${id}", () => {`,90 ` ${assertion}`,91 "});",92 "",93 ].join("\n"),94 },95 want,96});9798const passing = draftOf("expect(parse('2026-W41')).toStrictEqual({});");99100const passingToo = draftOf("expect(parse('2026-W42')).toStrictEqual({});");101102const red = draftOf("expect(parse('2026-W41').week).toBe(41);");103104const unstated = draftOf(105 "expect(parse('2026-W41').week).toBe(41);",106 "parse-month"107);108109const proposed = Effect.gen(function* () {110 yield* advanceTo("2026-10-08T12:00:00Z");111112 const api = yield* Projects.use((each) => each.create(project)).pipe(113 Effect.orDie114 );115116 yield* api.initProject(alice, {}).pipe(Effect.orDie);117118 const first = yield* Pusher.use((each) =>119 each.push(repo, Option.none(), start)120 );121122 yield* api.recordFirstPush(alice, first).pipe(Effect.orDie);123124 yield* api125 .proposeAsk(carol, { draft: true, territory: "src/parse.ts", want })126 .pipe(Effect.orDie);127128 return { api, main: LandedSha.make(first) };129});130131const scripted = (132 main: LandedSha,133 drafted: DraftedAsk,134 result: "passed" | "failed"135) =>136 Effect.gen(function* () {137 const { commit } = yield* Lander.use((lander) =>138 lander.compose({ files: draftedFiles(drafted), main, repo })139 ).pipe(Effect.orDie);140141 yield* Checker.use((script) =>142 script.script(CheckAt.cases.Commit.make({ commit }), redThenGreen, [143 result === "passed"144 ? { result }145 : { result, signature: "redThenGreen: expected 41, got undefined" },146 ])147 );148 });149150const draftOfProposal = (api: ProjectApi) =>151 Effect.map(152 Effect.orDie(api.showProposal(Anonymous.make({}), proposal)),153 ({ proposal: shown }) => shown.draft154 );155156const proposalDecisions = (api: ProjectApi) =>157 Effect.map(Effect.orDie(api.today(alice)), ({ decisions }) =>158 decisions.filter(({ subject }) =>159 DecisionSubject.guards.OpenProposal(subject)160 )161 );162163const asked = DraftsAsked.use(({ inputs }) => inputs);164165const worldDrafting = (script: Parameters<typeof DrafterMemory>[0]) =>166 Layer.mergeAll(167 worldWith(policy),168 DrafterMemory(script),169 Layer.succeed(DraftModel, model)170 );171172describe("a draft's run, over steps that replay", () => {173 it.effect(174 "feeds attempt 1's NotRedFirst into attempt 2, puts up one decision with the red-first evidence, and a replay asks the model nothing more",175 () =>176 Effect.gen(function* () {177 const { api, main } = yield* proposed;178179 yield* scripted(main, passing, "passed");180 yield* scripted(main, red, "failed");181182 const steps = yield* memoSteps();183184 yield* draftSteps(params).pipe(Effect.provide(steps));185186 const inputs = yield* asked;187 const decisions = yield* proposalDecisions(api);188189 expect({190 attempts: inputs.map(({ attempt }) => attempt),191 decisions: decisions.length,192 draft: yield* draftOfProposal(api),193 firstFeedback: inputs[0]?.feedback,194 redFirst: decisions[0]?.evidence.find(195 ({ label }) => label === "red first"196 )?.value,197 refusedWith: inputs[1]?.feedback?.split("\n")[0]?.split(":")[0],198 }).toStrictEqual({199 attempts: [1, 2],200 decisions: 1,201 draft: DraftState.cases.Ready.make({202 attempts: 2,203 model,204 red: {205 lane: redThenGreen,206 signature: "redThenGreen: expected 41, got undefined",207 },208 round: 1,209 }),210 firstFeedback: undefined,211 redFirst: `${redThenGreen}: redThenGreen: expected 41, got undefined`,212 refusedWith: "NotRedFirst",213 });214215 yield* draftSteps(params).pipe(Effect.provide(steps));216217 expect({218 asked: (yield* asked).length,219 decisions: (yield* proposalDecisions(api)).length,220 }).toStrictEqual({ asked: 2, decisions: 1 });221 }).pipe(Effect.provide(worldDrafting([passing, red])))222 );223224 it.effect(225 "settles Failed with the last refusal's tag once three attempts are refused",226 () =>227 Effect.gen(function* () {228 const { api, main } = yield* proposed;229230 yield* scripted(main, passing, "passed");231 yield* scripted(main, passingToo, "passed");232233 yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));234235 expect({236 asked: (yield* asked).length,237 decisions: (yield* proposalDecisions(api)).length,238 draft: yield* draftOfProposal(api),239 }).toStrictEqual({240 asked: 3,241 decisions: 1,242 draft: DraftState.cases.Failed.make({243 attempts: 3,244 model,245 refusal: "IncompleteBrief",246 round: 1,247 }),248 });249 }).pipe(Effect.provide(worldDrafting([passing, passingToo, unstated])))250 );251252 it.effect(253 "retries a rate-limited model as a step, without spending an attempt",254 () =>255 Effect.gen(function* () {256 const { api, main } = yield* proposed;257258 yield* scripted(main, red, "failed");259260 yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));261262 expect({263 asked: (yield* asked).map(({ attempt }) => attempt),264 draft: yield* draftOfProposal(api),265 }).toStrictEqual({266 asked: [1, 1],267 draft: DraftState.cases.Ready.make({268 attempts: 1,269 model,270 red: {271 lane: redThenGreen,272 signature: "redThenGreen: expected 41, got undefined",273 },274 round: 1,275 }),276 });277 }).pipe(278 Effect.provide(279 worldDrafting([new DraftFailed({ reason: "rate-limited" }), red])280 )281 )282 );283284 it.effect(285 "spends the attempt of a model still rate-limited once its step's retries are spent, and a replay ends the same way",286 () =>287 Effect.gen(function* () {288 const { api, main } = yield* proposed;289290 yield* scripted(main, red, "failed");291292 const steps = yield* memoSteps();293294 yield* draftSteps(params).pipe(Effect.provide(steps));295296 const settled = {297 asked: (yield* asked).map(({ attempt }) => attempt),298 draft: yield* draftOfProposal(api),299 feedback: (yield* asked)[5]?.feedback,300 };301302 yield* draftSteps(params).pipe(Effect.provide(steps));303304 expect({305 replayed: {306 asked: (yield* asked).length,307 draft: yield* draftOfProposal(api),308 },309 settled,310 }).toStrictEqual({311 replayed: { asked: 6, draft: settled.draft },312 settled: {313 asked: [1, 1, 1, 1, 1, 2],314 draft: DraftState.cases.Ready.make({315 attempts: 2,316 model,317 red: {318 lane: redThenGreen,319 signature: "redThenGreen: expected 41, got undefined",320 },321 round: 1,322 }),323 feedback:324 "Your reply gave no draft (rate-limited): answer with one JSON object that matches the schema, and nothing else.",325 },326 });327 }).pipe(328 Effect.provide(329 worldDrafting([330 ...Array.replicate(new DraftFailed({ reason: "rate-limited" }), 5),331 red,332 ])333 )334 )335 );336337 it.effect(338 "tells the next attempt the model erred, not that it was rate-limited, when the drafter dies",339 () =>340 Effect.gen(function* () {341 const { api } = yield* proposed;342343 yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));344345 const inputs = yield* asked;346347 expect({348 asked: inputs.map(({ attempt }) => attempt),349 draft: yield* draftOfProposal(api),350 feedback: inputs[1]?.feedback,351 }).toStrictEqual({352 asked: [1, 2, 3],353 draft: DraftState.cases.Failed.make({354 attempts: 3,355 model,356 refusal: "IncompleteBrief",357 round: 1,358 }),359 feedback:360 "Your reply gave no draft (model-error): answer with one JSON object that matches the schema, and nothing else.",361 });362 }).pipe(Effect.provide(worldDrafting([])))363 );364365 it.effect(366 "ends the round Failed with VerifierBlocked, asking no other draft, when the Checker stays blocked past the rehearsal's retries",367 () =>368 Effect.gen(function* () {369 const { api } = yield* proposed;370371 const steps = yield* memoSteps();372373 yield* draftSteps(params).pipe(Effect.provide(steps));374 yield* draftSteps(params).pipe(Effect.provide(steps));375376 expect({377 asked: (yield* asked).length,378 decisions: (yield* proposalDecisions(api)).length,379 draft: yield* draftOfProposal(api),380 }).toStrictEqual({381 asked: 1,382 decisions: 1,383 draft: DraftState.cases.Failed.make({384 attempts: 1,385 model,386 refusal: "VerifierBlocked",387 round: 1,388 }),389 });390 }).pipe(Effect.provide(worldDrafting([red])))391 );392393 it.effect(394 "stops after its context when the proposal is gone: no attempt, no settling",395 () =>396 Effect.gen(function* () {397 yield* proposed;398399 const names = yield* Ref.make<readonly string[]>([]);400401 const memo = Context.get(402 yield* Layer.build(yield* memoSteps()),403 StepRunner404 );405406 const logged = StepRunner.of({407 step: (name, schema, effect, retry?: StepRetry) =>408 Effect.andThen(409 Ref.update(names, (all) => [...all, name]),410 memo.step(name, schema, effect, retry)411 ),412 });413414 yield* draftSteps(415 DraftParams.make({416 project,417 proposal: ProposalId.make("prop-000009"),418 round: 1,419 })420 ).pipe(Effect.provideService(StepRunner, logged));421422 expect({423 asked: (yield* asked).length,424 names: yield* Ref.get(names),425 }).toStrictEqual({ asked: 0, names: ["context"] });426 }).pipe(Effect.provide(worldDrafting([])))427 );428});429430const fakeWorkflow = (status: InstanceStatus["status"]) => {431 const made: string[] = [];432 const restarted: string[] = [];433434 const workflow: DraftWorkflow = {435 create: ({ id }) => {436 if (made.includes(id)) {437 return Promise.reject(new Error(`instance ${id} already exists`));438 }439440 made.push(id);441442 return Promise.resolve({ id });443 },444 get: (id) =>445 Promise.resolve({446 id,447 restart: () => {448 restarted.push(id);449450 return Promise.resolve();451 },452 status: () => Promise.resolve({ status }),453 }),454 };455456 return { made, restarted, workflow };457};458459describe("the Workflow's draft runs", () => {460 it.effect(461 "starts one instance per round: a second start finds it, and a run still going is left alone",462 () =>463 Effect.gen(function* () {464 const fake = fakeWorkflow("running");465466 const starting = DraftRuns.pipe(467 Effect.flatMap((runs) =>468 runs.start({ note: "keep it small", project, proposal, round: 1 })469 ),470 Effect.provide(DraftRunsWorkflow(fake.workflow))471 );472473 yield* starting;474 yield* starting;475476 expect({477 made: fake.made,478 restarted: fake.restarted,479 }).toStrictEqual({Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 480why, one step back480 made: [`draft-${keyOf(project)}-${proposal}-r1`],Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f
lines 481–483why, one step back481 restarted: [],482 });483Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 484why, one step back484 expect(draftId(params)).toBe(`draft-${keyOf(project)}-${proposal}-r1`);Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f
lines 485–488why, one step back485 })486 );487488 it("keeps every round of a long-named project's proposals its own instance, within the engine's 100 characters", () => {Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 489–494why, one step back489 const long = ProjectName.make(`alice/${"a-long-project-name".repeat(6)}x`);490491 const longToo = ProjectName.make(492 `alice/${"a-long-project-name".repeat(6)}y`493 );494Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f
lines 495–542why, one step back495 const other = ProposalId.make("prop-000002");496497 const rounds = [498 { project: long, proposal, round: 1 },499 { project: long, proposal, round: 2 },500 { project: long, proposal: other, round: 1 },501 { project: longToo, proposal, round: 1 },502 ];503504 const ids = rounds.map(draftId);505506 expect({507 distinct: new Set(ids).size,508 fit: ids.every(509 (id) => id.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/u.test(id)510 ),511 named: rounds.every((round, at) =>512 (ids[at] ?? "").endsWith(`-${round.proposal}-r${round.round}`)513 ),514 }).toStrictEqual({ distinct: 4, fit: true, named: true });515 });516517 it.effect(518 "starts an errored round's instance again, and never a complete one, which would ask the model again",519 () =>520 Effect.gen(function* () {521 const errored = fakeWorkflow("errored");522 const complete = fakeWorkflow("complete");523524 const twice = (workflow: DraftWorkflow) =>525 DraftRuns.pipe(526 Effect.flatMap((runs) =>527 Effect.andThen(528 runs.start({ project, proposal, round: 1 }),529 runs.start({ project, proposal, round: 1 })530 )531 ),532 Effect.provide(DraftRunsWorkflow(workflow))533 );534535 yield* twice(errored.workflow);536 yield* twice(complete.workflow);537538 expect({539 complete: complete.restarted,540 errored: errored.restarted,541 }).toStrictEqual({542 complete: [],Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 543why, one step back543 errored: [`draft-${keyOf(project)}-${proposal}-r1`],Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f
lines 544–645why, one step back544 });545 })546 );547548 it.effect(549 "gives the engine a 10-minute timeout on each step, and the rate-limit retries on the model's",550 () =>551 Effect.gen(function* () {552 const { main } = yield* proposed;553554 yield* scripted(main, red, "failed");555556 const configs: (readonly [string, EngineConfig])[] = [];557 const kept = new Map<string, Schema.Json>();558559 const engine: EngineSteps = {560 do: (name, config, body) => {561 configs.push([name, config]);562563 const found = kept.get(name);564565 return found === undefined566 ? body().then((value) => {567 kept.set(name, value);568569 return value;570 })571 : Promise.resolve(found);572 },573 };574575 const ports = yield* Effect.context<Projects | Drafter | RepoHost>();576577 const payload = yield* Schema.encodeEffect(DraftParams)(params);578579 yield* Effect.promise(() =>580 runDraftWorkflow(Layer.succeedContext(ports), payload, engine)581 );582583 expect(configs.map(([name]) => name)).toStrictEqual([584 "context",585 "draft-1",586 "rehearse-1",587 "settle",588 ]);589590 expect({591 draft: new Map(configs).get("draft-1"),592 rehearse: new Map(configs).get("rehearse-1"),593 }).toStrictEqual({594 draft: {595 retries: { backoff: "exponential", delay: 15_000, limit: 4 },596 timeout: "10 minutes",597 },598 rehearse: {599 retries: { backoff: "exponential", delay: 60_000, limit: 3 },600 timeout: "10 minutes",601 },602 });603604 expect(605 configs.filter(([, config]) => config.timeout !== "10 minutes")606 ).toStrictEqual([]);607 }).pipe(Effect.provide(worldDrafting([red])))608 );609610 it("takes the Worker's bindings as the generated Env types them", () => {611 expectTypeOf<Env["ANSWER"]>().toExtend<612 Parameters<typeof DraftRunsWorkflow>[0]613 >();614 expectTypeOf<PlatformConfig["AI"]>().toExtend<AiLike>();615 });616});617618describe("proposing with a draft", () => {619 it.effect(620 "spends the person's draft limit first: past it, CapReached, while a proposal without a draft still goes through",621 () =>622 Effect.gen(function* () {623 yield* advanceTo("2026-10-08T12:00:00Z");624 yield* seeded(scenario);625626 const asCarol = yield* as("carol");627628 const drafted = yield* asCarol.proposeAsk({629 draft: true,630 project,631 want,632 });633634 const past = yield* Effect.flip(635 asCarol.proposeAsk({ draft: true, project, want })636 );637638 const plain = yield* asCarol.proposeAsk({ project, want });639640 expect({641 drafted: drafted.proposal.draft?._tag,642 past,643 plain: plain.proposal.draft,644 }).toStrictEqual({645 drafted: "Drafting",Say which limit a CapReached reached and when to try again, and that a fork takes branches onlyoscabrielbefore adoption42ea9b7
line 646why, one step back646 past: new CapReached({ cap: 1, limit: "drafts", retryAfter: 60 }),Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f
lines 647–661why, one step back647 plain: undefined,648 });649 }).pipe(650 Effect.provide(651 Handlers.pipe(652 Layer.provideMerge(653 worldOf([scenario], {654 limits: { claim: 5, draft: 1, proposal: 5 },655 })656 )657 )658 )659 )660 );661});