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
Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f
line 1why, one step back1/**Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
line 2why, one step back2 * Each step's value is recorded, so a replay never asks the model again.Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f
lines 3–12why, one step back3 *4 * A step whose retries are spent is kept failed by the engine and thrown5 * again, unrun, in every replay, where its typed failure is gone: so what6 * the program makes of it is recorded as a value in a step of its own7 * (`<step>:gave-up`), which every replay reads back.8 */9import { RepoHost, Revision } from "@repo/artifacts/repo-host";10import { DraftResult, DRAFT_ROUNDS, Rehearsal } from "@repo/project/draft-runs";11import type { DraftParams } from "@repo/project/draft-runs";12import { Projects } from "@repo/project/projects";Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 13why, one step back13import { keyOf, RepoName, RepoPath } from "@repo/protocol/ids";Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f
lines 14–120why, one step back14import type { Refusal } from "@repo/protocol/refusal";15import { IncompleteBrief, VerifierBlocked } from "@repo/protocol/refusal";16import { Cause, Context, Effect, Option, Record, Schema } from "effect";1718import { askTestFolderOf, pickFiles } from "./context.ts";19import { DraftContext, DraftedAsk, DraftFailed } from "./drafted.ts";20import type { DraftInput } from "./drafted.ts";21import { Drafter } from "./drafter.ts";22import { feedbackText, policyDigest } from "./prompt.ts";23import { draftedFiles } from "./render.ts";2425export interface StepRetry {26 readonly limit: number;27 readonly delayMs: number;28 readonly backoff: "constant" | "linear" | "exponential";29}3031export interface DraftSteps {32 readonly step: <A, I, E, R>(33 name: string,34 schema: Schema.Codec<A, I>,35 effect: Effect.Effect<A, E, R>,36 retry?: StepRetry37 ) => Effect.Effect<A, E, R>;38}3940export const DraftModel = Context.Reference<string>("drafting/DraftModel", {41 defaultValue: () => "memory",42});4344export const rateLimitedRetry: StepRetry = {45 backoff: "exponential",46 delayMs: 15_000,47 limit: 4,48};4950export const blockedRetry: StepRetry = {51 backoff: "exponential",52 delayMs: 60_000,53 limit: 3,54};5556const Prepared = Schema.TaggedUnion({57 Gone: {},58 NoFix: {},59 Ready: {60 context: DraftContext,61 territory: Schema.optionalKey(Schema.NonEmptyString),62 want: Schema.NonEmptyString,63 },64});6566type Prepared = typeof Prepared.Type;6768const Attempted = Schema.TaggedUnion({69 Drafted: { drafted: DraftedAsk },70 Spent: { reason: DraftFailed.fields.reason },71});7273type Attempted = typeof Attempted.Type;7475const draftedKind = "fix";7677const territoryPaths = (territory: string | undefined) =>78 (territory ?? "")79 .split(/[\s,]+/u)80 .map((path) => path.replace(/(?:\/\*\*)?\/*$/u, ""))81 .filter((path) => path !== "" && path !== ".")82 .map((path) => RepoPath.make(path));8384const decoder = new TextDecoder();8586const field = <K extends string, A>(87 key: K,88 value: Option.Option<A>89): Partial<Record<K, A>> =>90 Option.match(value, {91 onNone: () => ({}),92 onSome: (present) => Record.singleton(key, present),93 });9495const spentText = (reason: string) =>96 `Your reply gave no draft (${reason}): answer with one JSON object that matches the schema, and nothing else.`;9798const noDraft = (reason: string): Refusal =>99 new IncompleteBrief({ missing: [`a draft (${reason})`] });100101export const runDraft = (102 params: DraftParams,103 steps: DraftSteps104): Effect.Effect<void, never, Projects | Drafter | RepoHost> =>105 Effect.gen(function* () {106 const { step } = steps;107 const projects = yield* Projects;108 const drafter = yield* Drafter;109 const host = yield* RepoHost;110 const model = yield* DraftModel;111 const project = projects.get(params.project);112113 const prepare = Effect.gen(function* () {114 const api = yield* project;115 const data = yield* api.draftContext(params.proposal, params.round);116117 if (!data.policy.kinds.some(({ name }) => name === draftedKind)) {118 return Prepared.cases.NoFix.make({});119 }120Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 121why, one step back121 const repo = RepoName.make(keyOf(data.project));Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f
lines 122–327why, one step back122123 const read = (path: RepoPath) =>124 host.readFile(repo, Revision.Commit({ sha: data.at }), path).pipe(125 Effect.map(126 Option.match({127 onNone: () => "",128 onSome: (bytes) => decoder.decode(bytes),129 })130 ),131 Effect.catchTag("RepoNotFound", () => Effect.succeed(""))132 );133134 const files = yield* pickFiles(135 data.paths,136 { territory: territoryPaths(data.territory), want: data.want },137 read138 );139140 return Prepared.cases.Ready.make({141 context: {142 at: data.at,143 files,144 policy: policyDigest(data.policy, askTestFolderOf(files)),145 project: data.project,146 },147 ...field("territory", Option.fromUndefinedOr(data.territory)),148 want: data.want,149 });150 }).pipe(151 Effect.catchTags({152 ProposalClosed: () => Effect.succeed(Prepared.cases.Gone.make({})),153 UnknownProject: () => Effect.succeed(Prepared.cases.Gone.make({})),154 UnknownProposal: () => Effect.succeed(Prepared.cases.Gone.make({})),155 })156 );157158 const prepared: Prepared = yield* step("context", Prepared, prepare);159160 const settle = (result: DraftResult) =>161 step(162 "settle",163 Schema.Boolean,164 project.pipe(165 Effect.flatMap((api) =>166 api.draftSettled(params.proposal, params.round, result)167 ),168 Effect.as(true),169 Effect.catchTag("UnknownProject", () => Effect.succeed(false))170 )171 );172173 const attempts = (174 ready: Extract<Prepared, { readonly _tag: "Ready" }>175 ): Effect.Effect<DraftResult> =>176 Effect.gen(function* () {177 let feedback = Option.none<string>();178 let last: Refusal = noDraft("none given");179180 for (let attempt = 1; attempt <= DRAFT_ROUNDS; attempt += 1) {181 const input: DraftInput = {182 attempt,183 context: ready.context,184 ...field("feedback", feedback),185 ...field("note", Option.fromUndefinedOr(params.note)),186 ...field("territory", Option.fromUndefinedOr(ready.territory)),187 want: ready.want,188 };189190 const tried: Attempted = yield* step(191 `draft-${attempt}`,192 Attempted,193 drafter.draft(input).pipe(194 Effect.map((drafted) =>195 Attempted.cases.Drafted.make({ drafted })196 ),197 Effect.catchTag("DraftFailed", (failed) =>198 failed.reason === "rate-limited"199 ? Effect.fail(failed)200 : Effect.succeed(201 Attempted.cases.Spent.make({ reason: failed.reason })202 )203 )204 ),205 rateLimitedRetry206 ).pipe(207 // A model still rate-limited once the retries are spent, or a208 // drafter that died: either way a spent attempt, said as it was.209 Effect.catchCause((cause) =>210 step(211 `draft-${attempt}:gave-up`,212 Attempted,213 Effect.succeed(214 Attempted.cases.Spent.make({215 reason: Option.match(Cause.findErrorOption(cause), {216 onNone: () => "model-error" as const,217 onSome: ({ reason }) => reason,218 }),219 })220 )221 )222 )223 );224225 if (Attempted.guards.Spent(tried)) {226 feedback = Option.some(spentText(tried.reason));227 last = noDraft(tried.reason);228229 continue;230 }231232 const { drafted } = tried;233 const files = draftedFiles(drafted);234235 // A Checker still blocked (or a main still moving) once the236 // retries are spent ends the round: another draft would not help.237 const gaveUp = (cause: Cause.Cause<Refusal>) =>238 step(239 `rehearse-${attempt}:gave-up`,240 Rehearsal,241 Effect.succeed(242 Rehearsal.cases.Refused.make({243 diagnosis: "Blocked",244 excerpt: "",245 refusal: Option.getOrElse(246 Cause.findErrorOption(cause),247 (): Refusal => new VerifierBlocked({})248 ),249 })250 )251 ).pipe(Effect.map((rehearsal) => ({ blocked: true, rehearsal })));252253 const rehearsed = yield* step(254 `rehearse-${attempt}`,255 Rehearsal,256 Effect.flatMap(project, (api) => api.rehearseOpen(files)).pipe(257 Effect.catchTag("UnknownProject", () =>258 Effect.fail(new VerifierBlocked({}))259 )260 ),261 blockedRetry262 ).pipe(263 Effect.map((rehearsal) => ({ blocked: false, rehearsal })),264 Effect.catchCause(gaveUp)265 );266267 if (Rehearsal.guards.Red(rehearsed.rehearsal)) {268 return DraftResult.cases.Red.make({269 attempts: attempt,270 files,271 lane: rehearsed.rehearsal.lane,272 model,273 rationale: drafted.rationale,274 signature: rehearsed.rehearsal.signature,275 });276 }277278 const refused = rehearsed.rehearsal;279280 last = refused.refusal;281282 if (rehearsed.blocked) {283 return DraftResult.cases.Failed.make({284 attempts: attempt,285 model,286 refusal: last,287 });288 }289290 feedback = Option.some(291 feedbackText({292 diagnosis: refused.diagnosis,293 excerpt: refused.excerpt,294 refusal: refused.refusal,295 })296 );297 }298299 return DraftResult.cases.Failed.make({300 attempts: DRAFT_ROUNDS,301 model,302 refusal: last,303 });304 });305306 const result: Option.Option<DraftResult> = yield* Prepared.match(prepared, {307 Gone: () => Effect.succeedNone,308 NoFix: () =>309 Effect.succeedSome(310 DraftResult.cases.Failed.make({311 attempts: 1,312 model,313 refusal: new IncompleteBrief({ missing: ["kinds.fix"] }),314 })315 ),316 Ready: (ready) => Effect.asSome(attempts(ready)),317 });318319 if (Option.isSome(result)) {320 yield* settle(result.value);321 }322 }).pipe(323 Effect.annotateLogs({324 proposal: params.proposal,325 round: String(params.round),326 })327 );