run.ts
This file
Path
packages/drafting/src/run.ts
327 lines · 10.1 KiB · TypeScript
Last changed by
Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328/** * Each step's value is recorded, so a replay never asks the model again. * * A step whose retries are spent is kept failed by the engine and thrown * again, unrun, in every replay, where its typed failure is gone: so what * the program makes of it is recorded as a value in a step of its own * (`<step>:gave-up`), which every replay reads back. */import { RepoHost, Revision } from "@repo/artifacts/repo-host";import { DraftResult, DRAFT_ROUNDS, Rehearsal } from "@repo/project/draft-runs";import type { DraftParams } from "@repo/project/draft-runs";import { Projects } from "@repo/project/projects";import { keyOf, RepoName, RepoPath } from "@repo/protocol/ids";import type { Refusal } from "@repo/protocol/refusal";import { IncompleteBrief, VerifierBlocked } from "@repo/protocol/refusal";import { Cause, Context, Effect, Option, Record, Schema } from "effect";
import { askTestFolderOf, pickFiles } from "./context.ts";import { DraftContext, DraftedAsk, DraftFailed } from "./drafted.ts";import type { DraftInput } from "./drafted.ts";import { Drafter } from "./drafter.ts";import { feedbackText, policyDigest } from "./prompt.ts";import { draftedFiles } from "./render.ts";
export interface StepRetry { readonly limit: number; readonly delayMs: number; readonly backoff: "constant" | "linear" | "exponential";}
export interface DraftSteps { readonly step: <A, I, E, R>( name: string, schema: Schema.Codec<A, I>, effect: Effect.Effect<A, E, R>, retry?: StepRetry ) => Effect.Effect<A, E, R>;}
export const DraftModel = Context.Reference<string>("drafting/DraftModel", { defaultValue: () => "memory",});
export const rateLimitedRetry: StepRetry = { backoff: "exponential", delayMs: 15_000, limit: 4,};
export const blockedRetry: StepRetry = { backoff: "exponential", delayMs: 60_000, limit: 3,};
const Prepared = Schema.TaggedUnion({ Gone: {}, NoFix: {}, Ready: { context: DraftContext, territory: Schema.optionalKey(Schema.NonEmptyString), want: Schema.NonEmptyString, },});
type Prepared = typeof Prepared.Type;
const Attempted = Schema.TaggedUnion({ Drafted: { drafted: DraftedAsk }, Spent: { reason: DraftFailed.fields.reason },});
type Attempted = typeof Attempted.Type;
const draftedKind = "fix";
const territoryPaths = (territory: string | undefined) => (territory ?? "") .split(/[\s,]+/u) .map((path) => path.replace(/(?:\/\*\*)?\/*$/u, "")) .filter((path) => path !== "" && path !== ".") .map((path) => RepoPath.make(path));
const decoder = new TextDecoder();
const field = <K extends string, A>( key: K, value: Option.Option<A>): Partial<Record<K, A>> => Option.match(value, { onNone: () => ({}), onSome: (present) => Record.singleton(key, present), });
const spentText = (reason: string) => `Your reply gave no draft (${reason}): answer with one JSON object that matches the schema, and nothing else.`;
const noDraft = (reason: string): Refusal => new IncompleteBrief({ missing: [`a draft (${reason})`] });
export const runDraft = ( params: DraftParams, steps: DraftSteps): Effect.Effect<void, never, Projects | Drafter | RepoHost> => Effect.gen(function* () { const { step } = steps; const projects = yield* Projects; const drafter = yield* Drafter; const host = yield* RepoHost; const model = yield* DraftModel; const project = projects.get(params.project);
const prepare = Effect.gen(function* () { const api = yield* project; const data = yield* api.draftContext(params.proposal, params.round);
if (!data.policy.kinds.some(({ name }) => name === draftedKind)) { return Prepared.cases.NoFix.make({}); }
const repo = RepoName.make(keyOf(data.project));
const read = (path: RepoPath) => host.readFile(repo, Revision.Commit({ sha: data.at }), path).pipe( Effect.map( Option.match({ onNone: () => "", onSome: (bytes) => decoder.decode(bytes), }) ), Effect.catchTag("RepoNotFound", () => Effect.succeed("")) );
const files = yield* pickFiles( data.paths, { territory: territoryPaths(data.territory), want: data.want }, read );
return Prepared.cases.Ready.make({ context: { at: data.at, files, policy: policyDigest(data.policy, askTestFolderOf(files)), project: data.project, }, ...field("territory", Option.fromUndefinedOr(data.territory)), want: data.want, }); }).pipe( Effect.catchTags({ ProposalClosed: () => Effect.succeed(Prepared.cases.Gone.make({})), UnknownProject: () => Effect.succeed(Prepared.cases.Gone.make({})), UnknownProposal: () => Effect.succeed(Prepared.cases.Gone.make({})), }) );
const prepared: Prepared = yield* step("context", Prepared, prepare);
const settle = (result: DraftResult) => step( "settle", Schema.Boolean, project.pipe( Effect.flatMap((api) => api.draftSettled(params.proposal, params.round, result) ), Effect.as(true), Effect.catchTag("UnknownProject", () => Effect.succeed(false)) ) );
const attempts = ( ready: Extract<Prepared, { readonly _tag: "Ready" }> ): Effect.Effect<DraftResult> => Effect.gen(function* () { let feedback = Option.none<string>(); let last: Refusal = noDraft("none given");
for (let attempt = 1; attempt <= DRAFT_ROUNDS; attempt += 1) { const input: DraftInput = { attempt, context: ready.context, ...field("feedback", feedback), ...field("note", Option.fromUndefinedOr(params.note)), ...field("territory", Option.fromUndefinedOr(ready.territory)), want: ready.want, };
const tried: Attempted = yield* step( `draft-${attempt}`, Attempted, drafter.draft(input).pipe( Effect.map((drafted) => Attempted.cases.Drafted.make({ drafted }) ), Effect.catchTag("DraftFailed", (failed) => failed.reason === "rate-limited" ? Effect.fail(failed) : Effect.succeed( Attempted.cases.Spent.make({ reason: failed.reason }) ) ) ), rateLimitedRetry ).pipe( // A model still rate-limited once the retries are spent, or a // drafter that died: either way a spent attempt, said as it was. Effect.catchCause((cause) => step( `draft-${attempt}:gave-up`, Attempted, Effect.succeed( Attempted.cases.Spent.make({ reason: Option.match(Cause.findErrorOption(cause), { onNone: () => "model-error" as const, onSome: ({ reason }) => reason, }), }) ) ) ) );
if (Attempted.guards.Spent(tried)) { feedback = Option.some(spentText(tried.reason)); last = noDraft(tried.reason);
continue; }
const { drafted } = tried; const files = draftedFiles(drafted);
// A Checker still blocked (or a main still moving) once the // retries are spent ends the round: another draft would not help. const gaveUp = (cause: Cause.Cause<Refusal>) => step( `rehearse-${attempt}:gave-up`, Rehearsal, Effect.succeed( Rehearsal.cases.Refused.make({ diagnosis: "Blocked", excerpt: "", refusal: Option.getOrElse( Cause.findErrorOption(cause), (): Refusal => new VerifierBlocked({}) ), }) ) ).pipe(Effect.map((rehearsal) => ({ blocked: true, rehearsal })));
const rehearsed = yield* step( `rehearse-${attempt}`, Rehearsal, Effect.flatMap(project, (api) => api.rehearseOpen(files)).pipe( Effect.catchTag("UnknownProject", () => Effect.fail(new VerifierBlocked({})) ) ), blockedRetry ).pipe( Effect.map((rehearsal) => ({ blocked: false, rehearsal })), Effect.catchCause(gaveUp) );
if (Rehearsal.guards.Red(rehearsed.rehearsal)) { return DraftResult.cases.Red.make({ attempts: attempt, files, lane: rehearsed.rehearsal.lane, model, rationale: drafted.rationale, signature: rehearsed.rehearsal.signature, }); }
const refused = rehearsed.rehearsal;
last = refused.refusal;
if (rehearsed.blocked) { return DraftResult.cases.Failed.make({ attempts: attempt, model, refusal: last, }); }
feedback = Option.some( feedbackText({ diagnosis: refused.diagnosis, excerpt: refused.excerpt, refusal: refused.refusal, }) ); }
return DraftResult.cases.Failed.make({ attempts: DRAFT_ROUNDS, model, refusal: last, }); });
const result: Option.Option<DraftResult> = yield* Prepared.match(prepared, { Gone: () => Effect.succeedNone, NoFix: () => Effect.succeedSome( DraftResult.cases.Failed.make({ attempts: 1, model, refusal: new IncompleteBrief({ missing: ["kinds.fix"] }), }) ), Ready: (ready) => Effect.asSome(attempts(ready)), });
if (Option.isSome(result)) { yield* settle(result.value); } }).pipe( Effect.annotateLogs({ proposal: params.proposal, round: String(params.round), }) );