Merge branch 'build/910-draft-workflow'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents bbe1442, d40eb00 · Browse files · 20 files·+2273 added−35 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
20 files+2273 added−35 removed
- tests:+1128 added−3 removed
- other:+1145 added−32 removed
Provenance
- Commit
a0c8f4f- Tree
52db455- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
bbe1442- Parent 2
d40eb00
20 files changed+2273 added−35 removed
added:apps/platform/src/adapters/draft-runs-workflow.ts+75 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475/** * The project service's `DraftRuns` port over the `Answer` Workflow: a * draft's round runs as the instance `draftId` names (one per project, * proposal and round), with the round as params tagged `Draft`. The * instance asks the project's DO for what it needs, so the port carries * only the round. * * Starting twice is starting once (principle 8), as `answer-runs-workflow.ts` * does it: `create` refuses an id that exists, and the adapter takes the * instance it finds. Unlike an answer's, a round's run never waits to go on, * so a `complete` instance is left alone (a fresh run would ask the model * again for a round already settled); an `errored` or `terminated` one is * restarted from its first step. Any other failure is a defect: the outbox * row that asked for the start stays, and the project's next alarm runs it * again. */import { DraftRuns } from "@repo/project/draft-runs";import { Effect, Layer, Schema } from "effect";
import { DraftParams, draftId } from "../answer-runs.ts";
/** The part of a Workflow instance the adapter uses. */export interface DraftInstance { readonly id: string; readonly restart: () => Promise<void>; readonly status: () => Promise<{ readonly status: InstanceStatus["status"] }>;}
/** The part of the `Answer` Workflow binding the adapter uses. */export interface DraftWorkflow { readonly create: (options: { readonly id: string; readonly params: typeof DraftParams.Encoded; }) => Promise<{ readonly id: string }>; readonly get: (id: string) => Promise<DraftInstance>;}
const encodeParams = Schema.encodeEffect(DraftParams);
/** The states a round's run must run again from: it failed, or a person stopped it. */const failed: ReadonlySet<InstanceStatus["status"]> = new Set([ "errored", "terminated",]);
/** Restarts the instance when its run failed; a running or complete one is left alone. */const runAgain = (instance: DraftInstance) => Effect.gen(function* () { const { status } = yield* Effect.tryPromise(() => instance.status());
if (failed.has(status)) { yield* Effect.tryPromise(() => instance.restart()); } });
export const DraftRunsWorkflow = ( workflow: DraftWorkflow): Layer.Layer<never> => Layer.succeed(DraftRuns, { start: (round) => Effect.gen(function* () { const params = yield* encodeParams(DraftParams.make(round)); const id = draftId(round);
yield* Effect.tryPromise(() => workflow.create({ id, params })).pipe( // The id is taken: the round was started before. Effect.catch((error) => Effect.tryPromise(() => workflow.get(id)).pipe( Effect.mapError(() => error), Effect.flatMap(runAgain) ) ) ); }).pipe(Effect.orDie), });modified:apps/platform/src/workflows/answer.ts+53 added-5 removed
11 unmodified lines12131415161718192021222324252627282930233132253334353637383940414241 unmodified lines8485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811987120121122123911241259312612712812913013113213313413513613713813914014114214314414514614714811 unmodified lines * * The same Workflow admits a layer push's sealed checks: params * tagged `Admission` run `admissionSteps`, so typed visibility adds no * Workflow binding. An admission's output is `null`. * * So does a round of a proposal's draft: params tagged `Draft` run * `draftSteps` (W9-D14), over the Worker's ports and the drafter * (`draftPorts`), with each step's timeout handed to the engine. A draft's * output is `null` too. */import type { RepoHost } from "@repo/artifacts/repo-host";import type { Drafter } from "@repo/drafting/drafter";import type { Projects } from "@repo/project/projects";import { Outcome } from "@repo/protocol/domain/outcome";import { WorkflowEntrypoint } from "cloudflare:workers";import type { WorkflowEvent } from "cloudflare:workers";import { Effect, Layer, Schema } from "effect";
import type { WorkflowParams } from "../answer-runs.ts";import { AdmissionParams, AnswerParams } from "../answer-runs.ts";import { AdmissionParams, AnswerParams, DraftParams } from "../answer-runs.ts";import { decodeEnv } from "../platform.ts";import { workerPorts } from "../ports.ts";import { draftPorts, workerPorts } from "../ports.ts";import { admissionSteps } from "./admission-steps.ts";import { runAnswer } from "./answer/program.ts";import type { AnswerPorts } from "./answer/program.ts";import { draftSteps, timedSteps } from "./draft-steps.ts";import type { EngineSteps } from "./draft-steps.ts";import { workflowSteps } from "./step.ts";import type { StepRunner, WorkflowSteps } from "./step.ts";
/** An answer's outcome as the engine keeps it: JSON. */41 unmodified lines Effect.orDie ) );
/** * One draft round's run of the Workflow over `ports`, its params decoded * first, each step handed its timeout. */export const runDraftWorkflow = <E>( ports: Layer.Layer<Projects | Drafter | RepoHost, E>, payload: typeof DraftParams.Encoded, steps: EngineSteps): Promise<null> => Effect.runPromise( Effect.gen(function* () { yield* draftSteps(yield* Schema.decodeEffect(DraftParams)(payload));
return null; }).pipe( Effect.provide(Layer.merge(ports, workflowSteps(timedSteps(steps)))), Effect.orDie ) );
/** Whether the engine's params start an admission rather than an answer. */const admits = Schema.is(Schema.toEncoded(AdmissionParams));
/** Whether the engine's params start a draft's round. */const drafts = Schema.is(Schema.toEncoded(DraftParams));
export class Answer extends WorkflowEntrypoint< Env, typeof WorkflowParams.Encoded> { /** * `step` is the engine's `WorkflowStep`; the run uses only its `do` * (`WorkflowSteps`), so a test can hand it a fake engine. * (`EngineSteps`), so a test can hand it a fake engine. */ override run( event: Readonly<WorkflowEvent<typeof WorkflowParams.Encoded>>, step: WorkflowSteps step: EngineSteps ): Promise<OutcomeEncoded | null> { const ports = Layer.unwrap(Effect.map(decodeEnv(this.env), workerPorts)); const config = decodeEnv(this.env); const { payload } = event;
if (drafts(payload)) { // The env decoded once: the Worker's ports and the drafter from it. return runDraftWorkflow( Layer.unwrap( Effect.map(config, (decoded) => Layer.merge(workerPorts(decoded), draftPorts(decoded)) ) ), payload, step ); }
const ports = Layer.unwrap(Effect.map(config, workerPorts));
return admits(payload) ? runAdmission(ports, payload, step) : runWorkflow(ports, payload, step); }}added:apps/platform/src/workflows/draft-steps.ts+53 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253/** * One round of a proposal's draft, as steps of the `Answer` Workflow * (W9-D14): the program is `@repo/drafting/run`'s `runDraft`, shared with * the in-process run, over the Workflow's `StepRunner`. Its steps are * `context`, then `draft-<n>` and `rehearse-<n>` per attempt, then * `settle`, inside the instance `draft-<project>-<proposal>-r<round>`. * * The engine is handed a timeout with each of the run's steps * (`timedSteps`): a model call or a rehearsal on a cold Checker takes * minutes, and the other two steps are one Durable Object call each, well * inside the same bound. */import type { RepoHost } from "@repo/artifacts/repo-host";import type { Drafter } from "@repo/drafting/drafter";import { runDraft } from "@repo/drafting/run";import type { Projects } from "@repo/project/projects";import type { WorkflowTimeoutDuration } from "cloudflare:workers";import type { Effect, Schema } from "effect";
import type { DraftParams } from "../answer-runs.ts";import { StepRunner } from "./step.ts";import type { WorkflowStepRetries, WorkflowSteps } from "./step.ts";
/** How long one step of a draft's run may take before the engine fails it. */export const DRAFT_STEP_TIMEOUT = "10 minutes";
/** * The part of a Workflow's `WorkflowStep` a draft's run uses: `do`, with * retries and a timeout. A `WorkflowStep` is one, and so is anything that * takes `WorkflowSteps`' narrower config. */export interface EngineSteps { readonly do: ( name: string, config: { readonly retries?: WorkflowStepRetries; readonly timeout?: WorkflowTimeoutDuration; }, body: () => Promise<Schema.Json> ) => Promise<Schema.Json>;}
/** The engine's steps, each handed the draft step timeout. */export const timedSteps = (engine: EngineSteps): WorkflowSteps => ({ do: (name, config, body) => engine.do(name, { ...config, timeout: DRAFT_STEP_TIMEOUT }, body),});
/** One round of a draft, carried from its context to its settling. */export const draftSteps = ( params: DraftParams): Effect.Effect<void, never, StepRunner | Projects | Drafter | RepoHost> => StepRunner.use((runner) => runDraft(params, { step: runner.step }));modified:apps/platform/src/answer-runs.ts+55 added-2 removed
7 unmodified lines8 * For the admission of a layer push's sealed checks:9 * admission runs as steps of the same Workflow under its own tagged10 * params, so typed visibility adds no Workflow binding. Its instance id is11 * `admissionId`, so a push admitted twice runs once.12+ *13+ * For one round of a proposal's draft: the run (`@repo/drafting/run`) is14+ * steps of the same Workflow under params tagged `Draft`, so drafting adds15+ * no Workflow binding (W9-D14). Its instance id is `draftId`, one per16+ * project, proposal and round, so a round started twice runs once.17 */18+import { DraftParams as DraftRun } from "@repo/project/draft-runs";19 import {20 CommitSha,21 LayerName,22 ProjectName,16 unmodified lines39 });40 41 export type AdmissionParams = typeof AdmissionParams.Type;42 37-/** Every run the `Answer` Workflow takes: an admission's, or an answer's. */38-export const WorkflowParams = Schema.Union([AdmissionParams, AnswerParams]);43+/**44+ * One round of a proposal's draft: its project, proposal and round, and the45+ * note the round was asked with, which travels with the run.46+ */47+export const DraftParams = Schema.TaggedStruct("Draft", DraftRun.fields);48 49+export type DraftParams = typeof DraftParams.Type;50+51+/** Every run the `Answer` Workflow takes: an admission's, a draft's, or an answer's. */52+export const WorkflowParams = Schema.Union([53+ AdmissionParams,54+ DraftParams,55+ AnswerParams,56+]);57+58 export type WorkflowParams = typeof WorkflowParams.Type;59 60 /** How long a Workflow instance id may be. */61 const ID_LENGTH = 100;62 63 /** The instance an admission runs as: one per project, layer and pushed head. */64 export const admissionId = (params: AdmissionParams) =>65 `admit-${params.project}-${params.layer}-${params.head}`.slice(0, ID_LENGTH);66+67+/** A modulus for `tagOf`: the Mersenne prime 2^31 - 1, so every step stays a safe integer. */68+const TAG_MODULUS = 2_147_483_647;69+70+/** A polynomial hash of `text`'s code points, in base 36: a short, stable tag for a name cut short. */71+const tagOf = (text: string) => {72+ let hash = 0;73+74+ for (const unit of text) {75+ hash = (hash * 31 + (unit.codePointAt(0) ?? 0)) % TAG_MODULUS;76+ }77+78+ return hash.toString(36);79+};80+81+/**82+ * The instance a draft's round runs as: one per project, proposal and83+ * round. The proposal and round are kept whole: a project name too long for84+ * the engine's id is cut, and tagged with a hash of the whole name, so no85+ * two rounds share an instance (a complete one is never run again).86+ */87+export const draftId = (88+ params: Pick<DraftParams, "project" | "proposal" | "round">89+) => {90+ const suffix = `-${params.proposal}-r${params.round}`;91+ const whole = `draft-${params.project}${suffix}`;92+93+ if (whole.length <= ID_LENGTH) {94+ return whole;95+ }96+97+ const tag = `-${tagOf(params.project)}`;98+99+ return `${whole.slice(0, ID_LENGTH - tag.length - suffix.length)}${tag}${suffix}`;100+};modified:apps/platform/src/handlers.ts+8 added-1 removed
4 unmodified lines5 * the caller `Authenticated` named; the cross-project reads (`listProjects`,6 * `frontPage`, `credits`) come from the front-page projection; `status` and7 * `today` without a project ask every project the projection lists and8 * merge what each says. `claim`, `proposeAsk` and `flagAsk` spend the9- * caller's rate limit first, so a call past it reaches no project.9+ * caller's rate limit first, so a call past it reaches no project; a10+ * proposal with a draft, and `draftAsk`, spend the draft limit too.11 * `evidence` asks the project who may read a lane's log, which it reads12 * from the stage's `EvidenceStore`. The code reads (`listRefs`, `readTree`,13 * `listPaths`, `readFile`, `log`, `showCommit`, `why`) run here, over the14 * Worker's `RepoHost` and the project's canonical repo (`@repo/project/code`),335 unmodified lines350 proposeAsk: ({ project, ...input }) =>351 Effect.gen(function* () {352 const who = yield* person;353 354+ // A draft spends the draft limit (model calls and Checker runs)355+ // first, then the proposal limit, as any proposal does.356+ if (input.draft === true) {357+ yield* rateLimits.check("draft", who.handle);358+ }359+360 yield* rateLimits.check("proposal", who.handle);361 362 return yield* on(project, (api) => api.proposeAsk(who, input));363 }),84 unmodified linesmodified:apps/platform/src/ports.ts+22 added-3 removed
24 unmodified lines25 import { RepoHostBinding } from "@repo/artifacts/repo-host/binding";26 import type { CheckRunner } from "@repo/checks/check-runner";27 import type { EvidenceStore } from "@repo/checks/evidence-store";28 import { EvidenceStoreR2 } from "@repo/checks/evidence-store/r2";29+import type { Drafter } from "@repo/drafting/drafter";30+import { DrafterWorkersAi } from "@repo/drafting/drafter/binding";31+import { DraftModel } from "@repo/drafting/run";32 import type { Upstream } from "@repo/git/upstream";33 import { UpstreamRepoHost } from "@repo/git/upstream/repo-host";34 import { CodeCacheLive } from "@repo/project/code/cache";35 import type { FrontPage } from "@repo/project/front-page";11 unmodified lines47 import { Layer, Option } from "effect";48 49 import { CheckRunnerSandbox } from "./adapters/check-runner-sandbox.ts";50 import { DoProjects } from "./adapters/do-projects.ts";51+import { DraftRunsWorkflow } from "./adapters/draft-runs-workflow.ts";52 import { WorkerFetch } from "./adapters/fetch.ts";53 import { LanderSandbox } from "./adapters/lander-sandbox.ts";54 import { WorkerRateLimits } from "./adapters/rate-limits.ts";55 import * as cartridges from "./cartridges.ts";55 unmodified lines111 * its binding, git's upstream and every repo read over it, each project's112 * Durable Object, the sandbox's Checker, the Lander `LANDER_ADAPTER` names,113 * config folders evaluated in the Worker Loader, the front114 * page in D1, the rate limits, lane logs in the `EVIDENCE` bucket,111- * and the `PROJECT` namespace again for `watch`'s relay of each project's112- * socket.115+ * the `PROJECT` namespace again for `watch`'s relay of each project's116+ * socket, and each proposal's draft rounds as runs of the `Answer`117+ * Workflow.118 */119 const corePorts = (config: PlatformConfig): Layer.Layer<WorkerPorts> =>120 Layer.mergeAll(121 memoryFrontPage,23 unmodified lines145 }),146 EvidenceStoreR2(config.EVIDENCE),147 // The code reads' cache, one per isolate: a `Context.Reference`, so148 // without this entry every read goes to Artifacts.144- CodeCacheLive(CODE_READS_KEPT.light, CODE_READS_KEPT.heavy)149+ CodeCacheLive(CODE_READS_KEPT.light, CODE_READS_KEPT.heavy),150+ // A `Context.Reference`: without this entry a draft proposal starts no151+ // run, and stays drafting.152+ DraftRunsWorkflow(config.ANSWER)153 ).pipe(154 Layer.provideMerge(RepoHostBinding.layer(config.ARTIFACTS)),155 Layer.provideMerge(WorkerFetch)156 );157 158 /** The ports for one stage's env, with every cartridge the platform plugs in. */159 export const workerPorts = (config: PlatformConfig): Layer.Layer<WorkerPorts> =>160 plugIn(config, corePorts(config), Object.values(cartridges));161+162+/**163+ * What a draft's run needs beside the Worker's ports: the drafter over164+ * Workers AI, asking `DRAFT_MODEL`, which a settled round names. Only the165+ * `Answer` Workflow's draft rounds take it.166+ */167+export const draftPorts = (config: PlatformConfig): Layer.Layer<Drafter> =>168+ Layer.merge(169+ DrafterWorkersAi(config.AI, config.DRAFT_MODEL),170+ Layer.succeed(DraftModel, config.DRAFT_MODEL)171+ );added:apps/platform/test/workflows/draft.test.ts+682 added
1+/**2+ * A draft's run as the `Answer` Workflow takes it (W9-D14): the program's3+ * steps over memory steps that record and replay as the engine does4+ * (`memoSteps`), the memory drafter scripted per attempt, and a project in5+ * memory whose rehearsals run on the scripted Checker. The Workflow's own6+ * start (`DraftRunsWorkflow`) is held to create-or-restart over a fake7+ * binding, and the engine is handed each draft step's timeout.8+ */9+import { describe, expect, expectTypeOf, it } from "@effect/vitest";10+import type { RepoHost } from "@repo/artifacts/repo-host";11+import { CheckAt } from "@repo/checks/check-runner";12+import { DraftFailed } from "@repo/drafting/drafted";13+import type { DraftedAsk } from "@repo/drafting/drafted";14+import type { Drafter } from "@repo/drafting/drafter";15+import type { AiLike } from "@repo/drafting/drafter/binding";16+import { DrafterMemory, DraftsAsked } from "@repo/drafting/drafter/memory";17+import { draftedFiles } from "@repo/drafting/render";18+import { DraftModel } from "@repo/drafting/run";19+import { DraftRuns } from "@repo/project/draft-runs";20+import { Lander } from "@repo/project/lander";21+import type { ProjectApi } from "@repo/project/project";22+import { Projects } from "@repo/project/projects";23+import { DecisionSubject } from "@repo/protocol/domain/decision";24+import { DraftState } from "@repo/protocol/domain/proposal";25+import {26+ AskId,27+ LandedSha,28+ LaneName,29+ ProjectName,30+ ProposalId,31+ RepoName,32+ RepoPath,33+} from "@repo/protocol/ids";34+import { Anonymous, Person } from "@repo/protocol/principal";35+import { CapReached } from "@repo/protocol/refusal";36+import { advanceTo } from "@repo/testkit/clock";37+import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";38+import { Array, Context, Effect, Layer, Option, Ref, Schema } from "effect";39+40+import { DraftRunsWorkflow } from "../../src/adapters/draft-runs-workflow.ts";41+import type { DraftWorkflow } from "../../src/adapters/draft-runs-workflow.ts";42+import { DraftParams, draftId } from "../../src/answer-runs.ts";43+import { Handlers } from "../../src/handlers.ts";44+import type { PlatformConfig } from "../../src/platform.ts";45+import { runDraftWorkflow } from "../../src/workflows/answer.ts";46+import type { EngineSteps } from "../../src/workflows/draft-steps.ts";47+import { draftSteps } from "../../src/workflows/draft-steps.ts";48+import { memoSteps, StepRunner } from "../../src/workflows/step.ts";49+import type { StepRetry } from "../../src/workflows/step.ts";50+import { as, seeded, worldOf } from "../handlers.fixtures.ts";51+import { Checker, Pusher, worldWith } from "./answer.fixtures.ts";52+53+/** What the engine is handed with each step. */54+type EngineConfig = Parameters<EngineSteps["do"]>[1];55+56+/** datekit, decided by alice, with carol vouched and one `fix` ask she may want drafted. */57+const scenario = aProject({ people: ["carol"] }).pipe(58+ withVouches(["carol"]),59+ withAsk({ id: "parse-week", territory: "." })60+);61+62+const { policy, project } = scenario;63+64+const repo = RepoName.make(project);65+66+const alice = Person.make({ handle: scenario.initializer });67+68+const carol = Person.make({69+ handle: scenario.people.get("carol") ?? scenario.initializer,70+});71+72+const redThenGreen = LaneName.make("redThenGreen");73+74+const model = "@cf/moonshotai/kimi-k2.7-code";75+76+const want = "Parse an ISO week date such as 2026-W41";77+78+const proposal = ProposalId.make("prop-000001");79+80+const params = DraftParams.make({ project, proposal, round: 1 });81+82+const start = [83+ ["package.json", '{ "name": "datekit", "type": "module" }\n'],84+ ["src/parse.ts", "export const parse = (s) => ({});\n"],85+] as const;86+87+/** A draft of the scenario's ask whose test says `assertion`. */88+const draftOf = (assertion: string, id = "parse-week"): DraftedAsk => ({89+ id: AskId.make(id),90+ kind: "fix",91+ rationale: `${id}: parseWeek is missing, so its test fails by an assertion`,92+ territory: [RepoPath.make("src/parse.ts")],93+ test: {94+ path: RepoPath.make(`test/${id}.test.ts`),95+ source: [96+ 'import { expect, it } from "bun:test";',97+ 'import { parse } from "../src/parse.ts";',98+ "",99+ `it("${id}", () => {`,100+ ` ${assertion}`,101+ "});",102+ "",103+ ].join("\n"),104+ },105+ want,106+});107+108+/** A test that passes on main, so its draft is not red first. */109+const passing = draftOf("expect(parse('2026-W41')).toStrictEqual({});");110+111+/** A second test that passes on main. */112+const passingToo = draftOf("expect(parse('2026-W42')).toStrictEqual({});");113+114+/** A test that fails on main by its assertion. */115+const red = draftOf("expect(parse('2026-W41').week).toBe(41);");116+117+/** A draft of an ask the project's rules do not state. */118+const unstated = draftOf(119+ "expect(parse('2026-W41').week).toBe(41);",120+ "parse-month"121+);122+123+/** carol proposes the want with a draft, on datekit's first push. */124+const proposed = Effect.gen(function* () {125+ yield* advanceTo("2026-10-08T12:00:00Z");126+127+ const api = yield* Projects.use((each) => each.create(project)).pipe(128+ Effect.orDie129+ );130+131+ yield* api.initProject(alice, {}).pipe(Effect.orDie);132+133+ const first = yield* Pusher.use((each) =>134+ each.push(repo, Option.none(), start)135+ );136+137+ yield* api.recordFirstPush(alice, first).pipe(Effect.orDie);138+139+ // The project's first proposal: `proposal`.140+ yield* api141+ .proposeAsk(carol, { draft: true, territory: "src/parse.ts", want })142+ .pipe(Effect.orDie);143+144+ return { api, main: LandedSha.make(first) };145+});146+147+/** `drafted`'s files composed onto `main`, its check scripted to end `runs` there. */148+const scripted = (149+ main: LandedSha,150+ drafted: DraftedAsk,151+ result: "passed" | "failed"152+) =>153+ Effect.gen(function* () {154+ const { commit } = yield* Lander.use((lander) =>155+ lander.compose({ files: draftedFiles(drafted), main, repo })156+ ).pipe(Effect.orDie);157+158+ yield* Checker.use((script) =>159+ script.script(CheckAt.cases.Commit.make({ commit }), redThenGreen, [160+ result === "passed"161+ ? { result }162+ : { result, signature: "redThenGreen: expected 41, got undefined" },163+ ])164+ );165+ });166+167+/** The proposal's draft state, as anyone reads it. */168+const draftOfProposal = (api: ProjectApi) =>169+ Effect.map(170+ Effect.orDie(api.showProposal(Anonymous.make({}), proposal)),171+ ({ proposal: shown }) => shown.draft172+ );173+174+/** alice's open-proposal decisions on Today. */175+const proposalDecisions = (api: ProjectApi) =>176+ Effect.map(Effect.orDie(api.today(alice)), ({ decisions }) =>177+ decisions.filter(({ subject }) =>178+ DecisionSubject.guards.OpenProposal(subject)179+ )180+ );181+182+const asked = DraftsAsked.use(({ inputs }) => inputs);183+184+/** The world, the memory drafter scripted with `script`, and the platform's model. */185+const worldDrafting = (script: Parameters<typeof DrafterMemory>[0]) =>186+ Layer.mergeAll(187+ worldWith(policy),188+ DrafterMemory(script),189+ Layer.succeed(DraftModel, model)190+ );191+192+describe("a draft's run, over steps that replay", () => {193+ it.effect(194+ "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",195+ () =>196+ Effect.gen(function* () {197+ const { api, main } = yield* proposed;198+199+ yield* scripted(main, passing, "passed");200+ yield* scripted(main, red, "failed");201+202+ const steps = yield* memoSteps();203+204+ yield* draftSteps(params).pipe(Effect.provide(steps));205+206+ const inputs = yield* asked;207+ const decisions = yield* proposalDecisions(api);208+209+ expect({210+ attempts: inputs.map(({ attempt }) => attempt),211+ decisions: decisions.length,212+ draft: yield* draftOfProposal(api),213+ firstFeedback: inputs[0]?.feedback,214+ redFirst: decisions[0]?.evidence.find(215+ ({ label }) => label === "red first"216+ )?.value,217+ refusedWith: inputs[1]?.feedback?.split("\n")[0]?.split(":")[0],218+ }).toStrictEqual({219+ attempts: [1, 2],220+ decisions: 1,221+ draft: DraftState.cases.Ready.make({222+ attempts: 2,223+ model,224+ red: {225+ lane: redThenGreen,226+ signature: "redThenGreen: expected 41, got undefined",227+ },228+ round: 1,229+ }),230+ firstFeedback: undefined,231+ redFirst: `${redThenGreen}: redThenGreen: expected 41, got undefined`,232+ refusedWith: "NotRedFirst",233+ });234+235+ // The finished instance, run again: every step reads its record.236+ yield* draftSteps(params).pipe(Effect.provide(steps));237+238+ expect({239+ asked: (yield* asked).length,240+ decisions: (yield* proposalDecisions(api)).length,241+ }).toStrictEqual({ asked: 2, decisions: 1 });242+ }).pipe(Effect.provide(worldDrafting([passing, red])))243+ );244+245+ it.effect(246+ "settles Failed with the last refusal's tag once three attempts are refused",247+ () =>248+ Effect.gen(function* () {249+ const { api, main } = yield* proposed;250+251+ yield* scripted(main, passing, "passed");252+ yield* scripted(main, passingToo, "passed");253+254+ yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));255+256+ expect({257+ asked: (yield* asked).length,258+ decisions: (yield* proposalDecisions(api)).length,259+ draft: yield* draftOfProposal(api),260+ }).toStrictEqual({261+ asked: 3,262+ decisions: 1,263+ draft: DraftState.cases.Failed.make({264+ attempts: 3,265+ model,266+ refusal: "IncompleteBrief",267+ round: 1,268+ }),269+ });270+ }).pipe(Effect.provide(worldDrafting([passing, passingToo, unstated])))271+ );272+273+ it.effect(274+ "retries a rate-limited model as a step, without spending an attempt",275+ () =>276+ Effect.gen(function* () {277+ const { api, main } = yield* proposed;278+279+ yield* scripted(main, red, "failed");280+281+ yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));282+283+ expect({284+ asked: (yield* asked).map(({ attempt }) => attempt),285+ draft: yield* draftOfProposal(api),286+ }).toStrictEqual({287+ asked: [1, 1],288+ draft: DraftState.cases.Ready.make({289+ attempts: 1,290+ model,291+ red: {292+ lane: redThenGreen,293+ signature: "redThenGreen: expected 41, got undefined",294+ },295+ round: 1,296+ }),297+ });298+ }).pipe(299+ Effect.provide(300+ worldDrafting([new DraftFailed({ reason: "rate-limited" }), red])301+ )302+ )303+ );304+305+ it.effect(306+ "spends the attempt of a model still rate-limited once its step's retries are spent, and a replay ends the same way",307+ () =>308+ Effect.gen(function* () {309+ const { api, main } = yield* proposed;310+311+ yield* scripted(main, red, "failed");312+313+ const steps = yield* memoSteps();314+315+ yield* draftSteps(params).pipe(Effect.provide(steps));316+317+ const settled = {318+ asked: (yield* asked).map(({ attempt }) => attempt),319+ draft: yield* draftOfProposal(api),320+ feedback: (yield* asked)[5]?.feedback,321+ };322+323+ // The finished instance, run again: `draft-1` is thrown again,324+ // unrun, and its `gave-up` record says what the first run made of it.325+ yield* draftSteps(params).pipe(Effect.provide(steps));326+327+ expect({328+ replayed: {329+ asked: (yield* asked).length,330+ draft: yield* draftOfProposal(api),331+ },332+ settled,333+ }).toStrictEqual({334+ replayed: { asked: 6, draft: settled.draft },335+ settled: {336+ asked: [1, 1, 1, 1, 1, 2],337+ draft: DraftState.cases.Ready.make({338+ attempts: 2,339+ model,340+ red: {341+ lane: redThenGreen,342+ signature: "redThenGreen: expected 41, got undefined",343+ },344+ round: 1,345+ }),346+ feedback:347+ "Your reply gave no draft (rate-limited): answer with one JSON object that matches the schema, and nothing else.",348+ },349+ });350+ }).pipe(351+ Effect.provide(352+ worldDrafting([353+ ...Array.replicate(new DraftFailed({ reason: "rate-limited" }), 5),354+ red,355+ ])356+ )357+ )358+ );359+360+ it.effect(361+ "tells the next attempt the model erred, not that it was rate-limited, when the drafter dies",362+ () =>363+ Effect.gen(function* () {364+ const { api } = yield* proposed;365+366+ yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));367+368+ const inputs = yield* asked;369+370+ expect({371+ asked: inputs.map(({ attempt }) => attempt),372+ draft: yield* draftOfProposal(api),373+ feedback: inputs[1]?.feedback,374+ }).toStrictEqual({375+ asked: [1, 2, 3],376+ draft: DraftState.cases.Failed.make({377+ attempts: 3,378+ model,379+ refusal: "IncompleteBrief",380+ round: 1,381+ }),382+ feedback:383+ "Your reply gave no draft (model-error): answer with one JSON object that matches the schema, and nothing else.",384+ });385+ }).pipe(Effect.provide(worldDrafting([])))386+ );387+388+ it.effect(389+ "ends the round Failed with VerifierBlocked, asking no other draft, when the Checker stays blocked past the rehearsal's retries",390+ () =>391+ Effect.gen(function* () {392+ const { api } = yield* proposed;393+394+ // Nothing scripted for the draft's commit: the Checker cannot run it.395+ const steps = yield* memoSteps();396+397+ yield* draftSteps(params).pipe(Effect.provide(steps));398+ yield* draftSteps(params).pipe(Effect.provide(steps));399+400+ expect({401+ asked: (yield* asked).length,402+ decisions: (yield* proposalDecisions(api)).length,403+ draft: yield* draftOfProposal(api),404+ }).toStrictEqual({405+ asked: 1,406+ decisions: 1,407+ draft: DraftState.cases.Failed.make({408+ attempts: 1,409+ model,410+ refusal: "VerifierBlocked",411+ round: 1,412+ }),413+ });414+ }).pipe(Effect.provide(worldDrafting([red])))415+ );416+417+ it.effect(418+ "stops after its context when the proposal is gone: no attempt, no settling",419+ () =>420+ Effect.gen(function* () {421+ yield* proposed;422+423+ const names = yield* Ref.make<readonly string[]>([]);424+425+ const memo = Context.get(426+ yield* Layer.build(yield* memoSteps()),427+ StepRunner428+ );429+430+ const logged = StepRunner.of({431+ step: (name, schema, effect, retry?: StepRetry) =>432+ Effect.andThen(433+ Ref.update(names, (all) => [...all, name]),434+ memo.step(name, schema, effect, retry)435+ ),436+ });437+438+ yield* draftSteps(439+ DraftParams.make({440+ project,441+ proposal: ProposalId.make("prop-000009"),442+ round: 1,443+ })444+ ).pipe(Effect.provideService(StepRunner, logged));445+446+ expect({447+ asked: (yield* asked).length,448+ names: yield* Ref.get(names),449+ }).toStrictEqual({ asked: 0, names: ["context"] });450+ }).pipe(Effect.provide(worldDrafting([])))451+ );452+});453+454+/** A fake `ANSWER` binding: each instance made and restarted, every instance in `status`. */455+const fakeWorkflow = (status: InstanceStatus["status"]) => {456+ const made: string[] = [];457+ const restarted: string[] = [];458+459+ const workflow: DraftWorkflow = {460+ create: ({ id }) => {461+ if (made.includes(id)) {462+ return Promise.reject(new Error(`instance ${id} already exists`));463+ }464+465+ made.push(id);466+467+ return Promise.resolve({ id });468+ },469+ get: (id) =>470+ Promise.resolve({471+ id,472+ restart: () => {473+ restarted.push(id);474+475+ return Promise.resolve();476+ },477+ status: () => Promise.resolve({ status }),478+ }),479+ };480+481+ return { made, restarted, workflow };482+};483+484+describe("the Workflow's draft runs", () => {485+ it.effect(486+ "starts one instance per round: a second start finds it, and a run still going is left alone",487+ () =>488+ Effect.gen(function* () {489+ const fake = fakeWorkflow("running");490+491+ const starting = DraftRuns.pipe(492+ Effect.flatMap((runs) =>493+ runs.start({ note: "keep it small", project, proposal, round: 1 })494+ ),495+ Effect.provide(DraftRunsWorkflow(fake.workflow))496+ );497+498+ yield* starting;499+ yield* starting;500+501+ expect({502+ made: fake.made,503+ restarted: fake.restarted,504+ }).toStrictEqual({505+ made: [`draft-${project}-${proposal}-r1`],506+ restarted: [],507+ });508+509+ expect(draftId(params)).toBe(`draft-${project}-${proposal}-r1`);510+ })511+ );512+513+ it("keeps every round of a long-named project's proposals its own instance, within the engine's 100 characters", () => {514+ const long = ProjectName.make(`${"a-long-project-name".repeat(6)}x`);515+ const longToo = ProjectName.make(`${"a-long-project-name".repeat(6)}y`);516+ const other = ProposalId.make("prop-000002");517+518+ const rounds = [519+ { project: long, proposal, round: 1 },520+ { project: long, proposal, round: 2 },521+ { project: long, proposal: other, round: 1 },522+ { project: longToo, proposal, round: 1 },523+ ];524+525+ const ids = rounds.map(draftId);526+527+ expect({528+ distinct: new Set(ids).size,529+ fit: ids.every(530+ (id) => id.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/u.test(id)531+ ),532+ named: rounds.every((round, at) =>533+ (ids[at] ?? "").endsWith(`-${round.proposal}-r${round.round}`)534+ ),535+ }).toStrictEqual({ distinct: 4, fit: true, named: true });536+ });537+538+ it.effect(539+ "starts an errored round's instance again, and never a complete one, which would ask the model again",540+ () =>541+ Effect.gen(function* () {542+ const errored = fakeWorkflow("errored");543+ const complete = fakeWorkflow("complete");544+545+ const twice = (workflow: DraftWorkflow) =>546+ DraftRuns.pipe(547+ Effect.flatMap((runs) =>548+ Effect.andThen(549+ runs.start({ project, proposal, round: 1 }),550+ runs.start({ project, proposal, round: 1 })551+ )552+ ),553+ Effect.provide(DraftRunsWorkflow(workflow))554+ );555+556+ yield* twice(errored.workflow);557+ yield* twice(complete.workflow);558+559+ expect({560+ complete: complete.restarted,561+ errored: errored.restarted,562+ }).toStrictEqual({563+ complete: [],564+ errored: [`draft-${project}-${proposal}-r1`],565+ });566+ })567+ );568+569+ it.effect(570+ "gives the engine a 10-minute timeout on each step, and the rate-limit retries on the model's",571+ () =>572+ Effect.gen(function* () {573+ const { main } = yield* proposed;574+575+ yield* scripted(main, red, "failed");576+577+ const configs: (readonly [string, EngineConfig])[] = [];578+ const kept = new Map<string, Schema.Json>();579+580+ const engine: EngineSteps = {581+ do: (name, config, body) => {582+ configs.push([name, config]);583+584+ const found = kept.get(name);585+586+ return found === undefined587+ ? body().then((value) => {588+ kept.set(name, value);589+590+ return value;591+ })592+ : Promise.resolve(found);593+ },594+ };595+596+ const ports = yield* Effect.context<Projects | Drafter | RepoHost>();597+598+ const payload = yield* Schema.encodeEffect(DraftParams)(params);599+600+ yield* Effect.promise(() =>601+ runDraftWorkflow(Layer.succeedContext(ports), payload, engine)602+ );603+604+ expect(configs.map(([name]) => name)).toStrictEqual([605+ "context",606+ "draft-1",607+ "rehearse-1",608+ "settle",609+ ]);610+611+ expect({612+ draft: new Map(configs).get("draft-1"),613+ rehearse: new Map(configs).get("rehearse-1"),614+ }).toStrictEqual({615+ draft: {616+ retries: { backoff: "exponential", delay: 15_000, limit: 4 },617+ timeout: "10 minutes",618+ },619+ rehearse: {620+ retries: { backoff: "exponential", delay: 60_000, limit: 3 },621+ timeout: "10 minutes",622+ },623+ });624+625+ expect(626+ configs.filter(([, config]) => config.timeout !== "10 minutes")627+ ).toStrictEqual([]);628+ }).pipe(Effect.provide(worldDrafting([red])))629+ );630+631+ it("takes the Worker's bindings as the generated Env types them", () => {632+ expectTypeOf<Env["ANSWER"]>().toExtend<633+ Parameters<typeof DraftRunsWorkflow>[0]634+ >();635+ expectTypeOf<PlatformConfig["AI"]>().toExtend<AiLike>();636+ });637+});638+639+describe("proposing with a draft", () => {640+ it.effect(641+ "spends the person's draft limit first: past it, CapReached, while a proposal without a draft still goes through",642+ () =>643+ Effect.gen(function* () {644+ yield* advanceTo("2026-10-08T12:00:00Z");645+ yield* seeded(scenario);646+647+ const asCarol = yield* as("carol");648+649+ const drafted = yield* asCarol.proposeAsk({650+ draft: true,651+ project,652+ want,653+ });654+655+ const past = yield* Effect.flip(656+ asCarol.proposeAsk({ draft: true, project, want })657+ );658+659+ const plain = yield* asCarol.proposeAsk({ project, want });660+661+ expect({662+ drafted: drafted.proposal.draft?._tag,663+ past,664+ plain: plain.proposal.draft,665+ }).toStrictEqual({666+ drafted: "Drafting",667+ past: new CapReached({ cap: 1 }),668+ plain: undefined,669+ });670+ }).pipe(671+ Effect.provide(672+ Handlers.pipe(673+ Layer.provideMerge(674+ worldOf([scenario], {675+ limits: { claim: 5, draft: 1, proposal: 5 },676+ })677+ )678+ )679+ )680+ )681+ );682+});modified:apps/platform/test/core-loop.test.ts+145 added-1 removed
6 unmodified lines7 * that lands nothing new. Every step goes through a surface: git's output,8 * or a contract over `/rpc`.9 */10 import { describe, expect, it } from "@effect/vitest";11+import type { RepoHost } from "@repo/artifacts/repo-host";12 import { Brand } from "@repo/brand";13 import { CheckAt } from "@repo/checks/check-runner";14+import { draftRunsInline } from "@repo/drafting/draft-runs/inline";15+import type { InlinePorts } from "@repo/drafting/draft-runs/inline";16+import type { DraftedAsk } from "@repo/drafting/drafted";17+import { DrafterMemory } from "@repo/drafting/drafter/memory";18+import { draftedFiles } from "@repo/drafting/render";19+import type { Projects } from "@repo/project/projects";20+import { DecisionSubject } from "@repo/protocol/domain/decision";21 import { Outcome } from "@repo/protocol/domain/outcome";22 import {23 AskId,24 LandedSha,9 unmodified lines34 OutOfScope,35 StaleBase,36 } from "@repo/protocol/refusal";37 import { explain } from "@repo/protocol/render";30-import { Array, Effect } from "effect";38+import { Array, Context, Deferred, Effect, Layer } from "effect";39 40 import { pushRequestId } from "../src/adapters/custody.ts";41 import { coreLoopWorld } from "./world.ts";42 453 unmodified lines496 });497 }),498 60_000499 );500+501+ it.live(502+ "a want proposed with a draft runs in process, goes to the decider with its red-first evidence, and opens on accept with Assisted-by beside the people's credits",503+ () =>504+ Effect.gen(function* () {505+ const drafted: DraftedAsk = {506+ id: AskId.make("parse-day"),507+ kind: "fix",508+ rationale: "parse reads no day, so the test fails by its assertion",509+ territory: [RepoPath.make("src/parse.ts")],510+ test: {511+ path: RepoPath.make("test/parse-day.test.ts"),512+ source: [513+ 'import { expect, it } from "bun:test";',514+ 'import { parse } from "../src/parse.ts";',515+ "",516+ 'it("parse reads the day of an ISO date", () => {',517+ ' expect(Reflect.get(parse("2026-10-07"), "day")).toBe(7);',518+ "});",519+ "",520+ ].join("\n"),521+ },522+ want: "parse reads the day of an ISO date",523+ };524+525+ // The rounds the Project DOs start run in process, on the Worker's526+ // ports and the memory drafter, once the world hands them over.527+ const ready = yield* Deferred.make<Context.Context<InlinePorts>>();528+ const drafter = yield* Layer.build(DrafterMemory([drafted]));529+530+ const world = yield* coreLoopWorld({531+ plugIn: () => ({532+ project: draftRunsInline(Deferred.await(ready)),533+ worker: Layer.effectDiscard(534+ Effect.gen(function* () {535+ const ports = yield* Effect.context<Projects | RepoHost>();536+537+ yield* Deferred.succeed(ready, Context.merge(ports, drafter));538+ })539+ ),540+ }),541+ });542+543+ const dora = world.rpc("dora");544+ const alice = world.rpc("alice");545+ const doraGit = world.git("dora");546+547+ const made = yield* dora.initProject({ project });548+ const home = yield* doraGit.clone(made.remote);549+550+ yield* doraGit.commit(home, "Start datekit", start);551+ yield* doraGit.push(home);552+553+ // The drafted files fail on main twice the same way.554+ yield* world.script(555+ CheckAt.cases.Commit.make({556+ commit: yield* world.composed(project, draftedFiles(drafted)),557+ }),558+ redThenGreen,559+ ["failed", "failed"]560+ );561+562+ const proposed = yield* alice.proposeAsk({563+ draft: true,564+ project,565+ want: drafted.want,566+ });567+568+ const { decisions } = yield* dora.today({ project });569+570+ const decision = yield* Effect.fromOption(571+ Array.findFirst(572+ decisions,573+ ({ subject }) =>574+ DecisionSubject.guards.OpenProposal(subject) &&575+ subject.proposal === proposed.proposal.id576+ )577+ );578+579+ const shown = yield* alice.showProposal({580+ project,581+ proposal: proposed.proposal.id,582+ });583+584+ yield* dora.decide({585+ choice: "accept",586+ decision: decision.id,587+ project,588+ });589+590+ const { asks } = yield* alice.listAsks({ project });591+592+ yield* doraGit.ok(home, "fetch", "--quiet", "origin");593+594+ expect({595+ asks: asks.map(({ ask, claimed }) => ({ ask, claimed })),596+ draft: shown.proposal.draft?._tag,597+ files: yield* doraGit.ok(598+ home,599+ "show",600+ "--format=",601+ "--name-only",602+ "origin/main"603+ ),604+ proposed: proposed.proposal.draft?._tag,605+ redFirst: decision.evidence.some(606+ ({ label, value }) =>607+ label === "red first" && value.startsWith(`${redThenGreen}: `)608+ ),609+ trailers: (yield* doraGit.ok(610+ home,611+ "log",612+ "-1",613+ "--format=%(trailers:only)",614+ "origin/main"615+ ))616+ .split("\n")617+ // Who it credits and which agents it discloses: every `-by` trailer.618+ .filter((line) => /^[A-Za-z-]+-by: /u.test(line)),619+ }).toStrictEqual({620+ asks: [{ ask: drafted.id, claimed: false }],621+ draft: "Ready",622+ files: draftedFiles(drafted)623+ .map(({ path }) => path)624+ .join("\n"),625+ proposed: "Drafting",626+ redFirst: true,627+ trailers: [628+ `Asked-by: ${credited("alice")}`,629+ `Decided-by: ${credited("dora")}`,630+ `Assisted-by: ${Brand.cli}-drafter:memory (verified)`,631+ ],632+ });633+ }),634+ 60_000635+ );636 });modified:apps/platform/test/serve-world.ts+40 added-1 removed
22 unmodified lines23 * project that declares a layer gets its repo there, and its maintainers24 * clone and push it through the gateway. The `Answer` Workflow25 * the cartridge starts an admission on keeps the instance and runs26 * nothing: the world carries no Workflow.27+ * - A proposal made with a draft is drafted in process as it is made28+ * (`@repo/drafting`'s inline runs, over the Worker's ports), by the29+ * memory drafter scripted with the canned draft, whose test fails on any30+ * `src/parse.ts` without a `parseOrdinal`: so smoke's `--loop --draft`31+ * sees a draft go red first and open on accept with no model.32 *33 * The seed's `--world node` runs it (`scripts/lib/seed.ts`) and34 * reaches it over HTTP and git, as it reaches a stage. A process, not an35 * import: apps never import apps, and no file outside the platform imports4 unmodified lines40 import type { RepoHost } from "@repo/artifacts/repo-host";41 import { CheckRunner, shaOf } from "@repo/checks/check-runner";42 import type { CheckAt } from "@repo/checks/check-runner";43 import { CheckRunnerLocal } from "@repo/checks/check-runner/local";44+import { cannedDrafter } from "@repo/drafting/draft-runs/canned";45+import { draftRunsInline } from "@repo/drafting/draft-runs/inline";46+import type { InlinePorts } from "@repo/drafting/draft-runs/inline";47+import type { Drafter } from "@repo/drafting/drafter";48 import { Projects } from "@repo/project/projects";49 import { VerifierBlocked } from "@repo/protocol/refusal";50 import { git } from "@repo/testkit/git";51 import { untouchable } from "@repo/testkit/untouchable";52 import {53 Console,54+ Context,55+ Deferred,56 Duration,57 Effect,58 FileSystem,59 Layer,119 unmodified lines179 worker: all,180 };181 };182 183+/**184+ * `plugIn` with draft runs in process beside it: each Project DO starts its185+ * rounds inline, on the Worker's ports (which the Worker's side hands over186+ * once built) and `drafter`.187+ */188+const withDrafts = (189+ plugIn: PlugIn,190+ ready: Deferred.Deferred<Context.Context<InlinePorts>>,191+ drafter: Context.Context<Drafter>192+): PlugIn => ({193+ project: Layer.merge(194+ plugIn.project ?? Layer.empty,195+ draftRunsInline(Deferred.await(ready))196+ ),197+ worker: Layer.merge(198+ plugIn.worker ?? Layer.empty,199+ Layer.effectDiscard(200+ Effect.flatMap(Effect.context<Projects | RepoHost>(), (ports) =>201+ Deferred.succeed(ready, Context.merge(drafter, ports))202+ )203+ )204+ ),205+});206+207 /** How long after the last round the world carries queued answer runs again. */208 const CARRY_EVERY = Duration.millis(250);209 210 const serve = Effect.gen(function* () {10 unmodified lines221 const { decodeEnv } = yield* Effect.promise(222 () => import("../src/platform.ts")223 );224 225+ const drafter = yield* Layer.build(cannedDrafter);226+ const ready = yield* Deferred.make<Context.Context<InlinePorts>>();227+ const plugged = cartridgesOver(cartridges, decodeEnv);228+229 const world = yield* coreLoopWorld({230 checker: localChecker,192- plugIn: cartridgesOver(cartridges, decodeEnv),231+ plugIn: (aside) => withDrafts(plugged(aside), ready, drafter),232 sessions,233 });234 235 // The Answer Workflow's stand-in: the queued runs, carried every21 unmodified linesmodified:apps/web/src/dev/examples.ts+23 added-2 removed
14 unmodified lines15 * A project's rules are its committed `policy.json`, the config folder the16 * `/json` rules evaluator reads, with every ask it will open stated there;17 * an ask opens when a decider lands its files. Each ask file is written18 * from the ask `policy.json` states, as the SDK call a maintainer writes,19- * so the two never disagree.19+ * so the two never disagree. datekit's `policy.json` also states the ask20+ * the dev world's drafter drafts, which only an accepted draft opens.21 */22 import { Brand } from "@repo/brand";23+import { cannedDraft } from "@repo/drafting/draft-runs/canned";24 import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";25 import { Command, SymbolName } from "@repo/protocol/domain/common";26 import type { AskKind } from "@repo/protocol/domain/kind";27 import { PolicyInput } from "@repo/protocol/domain/policy";242 unmodified lines270 want: "diffInDays counts calendar days across a daylight-saving change.",271 }),272 ];273 274+/**275+ * The ask the dev world's drafter drafts for any want (`cannedDraft`),276+ * stated beside datekit's own so the `/json` rules evaluator finds it once277+ * a draft's files are composed; nobody opens it in the seed. A decider who278+ * accepts the draft opens it.279+ */280+const draftedAsk: StatedAsk = {281+ askedBy: datekitPeople.decider,282+ blockedBy: [],283+ brief: { current: cannedDraft.current, want: cannedDraft.want },284+ check: encodeCheck(285+ CheckSpec.cases.RedThenGreen.make({ path: cannedDraft.test.path })286+ ),287+ file: `${dir}/asks/${cannedDraft.id}.ask.ts`,288+ id: cannedDraft.id,289+ kind: cannedDraft.kind,290+ territory: { module: ".", paths: [...cannedDraft.territory] },291+};292+293 const library: Files = new Map([294 [295 "README.md",296 [106 unmodified lines403 ],404 [405 `${dir}/policy.json`,406 policyJson({386- asks: datekitAsks.map(({ stated }) => stated),407+ asks: [...datekitAsks.map(({ stated }) => stated), draftedAsk],408 deciders: [409 { handles: [datekitPeople.decider], paths: "**" },410 { handles: [datekitPeople.zones], paths: "src/tz.ts" },411 ],284 unmodified linesmodified:apps/web/src/dev/world.ts+9 added-3 removed
4 unmodified lines5 * Lander does the trusted Lander's work over them (`lander.ts`); the6 * Checker is scripted (`checker.ts`); rules are read from each project's7 * committed `policy.json` (`/json`); answers run in process; alarms are8 * recorded and never fire; the front page is folded from the projection's9- * rows (`front-page.ts`); lane logs are kept in memory. One clock, set by10- * the seed, is the world's time (`clock.ts`).9+ * rows (`front-page.ts`); lane logs are kept in memory. A proposal made10+ * with a draft is drafted in process as it is made, by the memory drafter11+ * scripted with the canned draft (`@repo/drafting/draft-runs/canned`),12+ * and goes red first on the scripted Checker. One clock, set by the seed,13+ * is the world's time (`clock.ts`).14 */15 import type { RepoHost } from "@repo/artifacts/repo-host";16 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";17 import type { EvidenceStore } from "@repo/checks/evidence-store";18 import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";19+import { cannedDrafter } from "@repo/drafting/draft-runs/canned";20+import { withDraftRunsInline } from "@repo/drafting/draft-runs/inline";21 import { AlarmsMemory } from "@repo/project/alarms/memory";22 import { AnswerRunsInline } from "@repo/project/answer-runs/inline";23 import type { FrontPage } from "@repo/project/front-page";24 import { FinishersFromChecks } from "@repo/project/project";12 unmodified lines37 /** Every port a project needs but its store, shared by every project in the world. */38 const ports = Layer.mergeAll(39 AlarmsMemory,40 AnswerRunsInline,41+ cannedDrafter,42 DevProjection,43 RulesEvaluatorJson.pipe(Layer.provide(FinishersFromChecks))44 ).pipe(45 Layer.provideMerge(Layer.mergeAll(DevChecker, DevLander)),7 unmodified lines53 */54 export const devWorld: Layer.Layer<55 Projects | FrontPage | EvidenceStore | RepoHost | DevClock56 > = Layer.mergeAll(DevFrontPage, EvidenceStoreMemory).pipe(51- Layer.provideMerge(ProjectsMemory),57+ Layer.provideMerge(withDraftRunsInline(ProjectsMemory)),58 Layer.provideMerge(ports),59 Layer.provideMerge(devClockAt(devStart)),60 Layer.fresh61 );modified:apps/web/test/dev-backend.test.ts+62 added
3 unmodified lines4 * minutes from one fixed start (so a page looks the same on every machine5 * and every run), and an answer that landed with its credit.6 */7 import { describe, expect, it } from "@effect/vitest";8+import { Brand } from "@repo/brand";9 import { Client, Contracts } from "@repo/protocol/contracts";10 import { ProjectEvent } from "@repo/protocol/domain/event";11 import { Handle, ProjectName } from "@repo/protocol/ids";12 import {271 unmodified lines284 expect([climbed?.status, climbed?.text]).toStrictEqual([404, ""]);285 })286 );287 });288+289+/**290+ * bram proposes a want for datekit with a draft, and what follows: the291+ * proposal as anyone reads it, and ines-v's Today before and after.292+ */293+const drafted = inFreshWorld((as) =>294+ Effect.gen(function* () {295+ const anyone = yield* clientOf(as());296+ const ines = yield* clientOf(as(decider));297+ const bram = yield* clientOf(as(contributor));298+ const project = ProjectName.make("datekit");299+ const before = yield* ines.today({ project });300+301+ const { proposal } = yield* bram.proposeAsk({302+ draft: true,303+ project,304+ want: "datekit reads ordinal dates such as 2026-280.",305+ });306+307+ const shown = yield* anyone.showProposal({308+ project,309+ proposal: proposal.id,310+ });311+312+ return {313+ after: yield* ines.today({ project }),314+ before,315+ proposed: proposal,316+ shown,317+ };318+ })319+);320+321+describe("a draft in the dev world", seededWorlds, () => {322+ it.live(323+ "is drafted as it is proposed, red first on the scripted Checker, and its decision joins the decider's Today",324+ () =>325+ Effect.gen(function* () {326+ const { after, before, proposed, shown } = yield* drafted;327+328+ // The seeded decisions expire first and fill the day's budget, so329+ // the draft's decision waits on Today as its overflow.330+ expect({331+ files: shown.files.map(({ path }) => path),332+ overflow: [before.overflow, after.overflow],333+ proposed: proposed.draft?._tag,334+ ready: shown.proposal.draft?._tag,335+ shown: after.decisions.map(({ id }) => id),336+ }).toStrictEqual({337+ files: [338+ `${Brand.configDir}/asks/parse-ordinal.ask.ts`,339+ "test/asks/parse-ordinal.test.ts",340+ ],341+ overflow: [0, 1],342+ proposed: "Drafting",343+ ready: "Ready",344+ shown: before.decisions.map(({ id }) => id),345+ });346+ })347+ );348+});modified:packages/config/test/smoke-loop.test.ts+91 added-1 removed
27 unmodified lines28 import {29 DemoStageRefused,30 smokeLoop,31 } from "../../../scripts/lib/smoke/loop.ts";32-import { main } from "../../../scripts/smoke.ts";32+import { DraftNeedsLoop, main } from "../../../scripts/smoke.ts";33 import { Brand } from "../../brand/src/index.ts";34 import { Handle } from "../../protocol/src/ids.ts";35 36 const decider = Handle.make("ines-v");224 unmodified lines261 });262 }).pipe(Effect.provide(NodeServices.layer))263 );264 });265+266+describe("smokeLoop --draft, against the Node world", () => {267+ it.live(268+ "after the loop, the answerer's want is drafted red first by the memory drafter, the decider accepts it, and the ask opens disclosing the drafter beside the asker",269+ () =>270+ Effect.gen(function* () {271+ const fs = yield* FileSystem.FileSystem;272+ const path = yield* Path.Path;273+ const dir = yield* fs.makeTempDirectoryScoped({ prefix: "smoke-910-" });274+275+ const report = yield* Effect.scoped(276+ Effect.gen(function* () {277+ const origin = yield* servedWorld(278+ new Map([279+ [decider, tokens.decider],280+ [answerer, tokens.answerer],281+ ])282+ );283+284+ return yield* smokeLoop({285+ answerer: tokens.answerer,286+ decider: tokens.decider,287+ draft: true,288+ origin,289+ run: "r2",290+ stage: "node",291+ });292+ })293+ ).pipe(294+ Effect.provideService(LedgerFile, path.join(dir, "created.jsonl"))295+ );296+297+ expect({298+ attempts: report.draft?.attempts,299+ model: report.draft?.model,300+ steps: report.timings.map(({ step }) => step).slice(-3),301+ timed: (report.draft?.ms ?? -1) >= 0,302+ trailers: report.draft?.trailers.filter((trailer) =>303+ /^(?:Ask|Asked-by|Assisted-by):/u.test(trailer)304+ ),305+ }).toStrictEqual({306+ attempts: 1,307+ model: "memory",308+ steps: ["draft-propose", "draft-ready", "draft-accept"],309+ timed: true,310+ trailers: [311+ `Asked-by: ${credited("bram")}`,312+ `Assisted-by: ${Brand.cli}-drafter:memory (verified)`,313+ "Ask: smoke-r2/parse-ordinal",314+ ],315+ });316+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),317+ 240_000318+ );319+});320+321+describe("smoke --draft without --loop", () => {322+ it.live(323+ "is refused with DraftNeedsLoop before any request or process: only the loop has a project to draft on",324+ () =>325+ Effect.gen(function* () {326+ const fetched: string[] = [];327+ const spawner = yield* refusing;328+329+ const result = yield* main([330+ "--stage",331+ "dev-oscabriel",332+ "--draft",333+ ]).pipe(334+ Effect.provide(spawner.layer),335+ Effect.provideService(FetchHttpClient.Fetch, (input) => {336+ fetched.push(new Request(input).url);337+338+ return Promise.reject(new Error("smoke --draft fetched"));339+ }),340+ Effect.result341+ );342+343+ expect({344+ fetched,345+ result,346+ spawned: yield* spawner.asked,347+ }).toStrictEqual({348+ fetched: [],349+ result: Result.fail(new DraftNeedsLoop({ flag: "--draft" })),350+ spawned: [],351+ });352+ }).pipe(Effect.provide(NodeServices.layer))353+ );354+});added:packages/drafting/src/draft-runs/canned.ts+47 added
1+/**2+ * The draft the worlds without a model give every proposal drafted in them3+ * (the web's dev world, the platform's Node world): an ask for a reader of4+ * ordinal dates in `src/parse.ts`, whose test fails on main by its5+ * assertion wherever that file has none, in datekit and in smoke's6+ * throwaway project alike. So `bun run dev` and `smoke --loop --draft`7+ * show a draft end to end, offline.8+ */9+import { AskId, RepoPath } from "@repo/protocol/ids";10+import { Array } from "effect";11+import type { Layer } from "effect";12+13+import type { DraftedAsk } from "../drafted.ts";14+import type { Drafter } from "../drafter.ts";15+import { DrafterMemory } from "../drafter/memory.ts";16+import type { DraftsAsked } from "../drafter/memory.ts";17+18+/** How many drafts a world gives before its drafter's script runs out. */19+const CANNED_DRAFTS = 64;20+21+export const cannedDraft = {22+ current: "src/parse.ts reads no ordinal date.",23+ id: AskId.make("parse-ordinal"),24+ kind: "fix",25+ rationale:26+ "src/parse.ts exports no parseOrdinal, so the test fails by its assertion on main.",27+ territory: [RepoPath.make("src/parse.ts")],28+ test: {29+ path: RepoPath.make("test/asks/parse-ordinal.test.ts"),30+ source: [31+ 'import { expect, test } from "bun:test";',32+ "",33+ 'import * as parsing from "../../src/parse.ts";',34+ "",35+ 'test("parse.ts exports parseOrdinal, for dates such as 2026-280", () => {',36+ ' expect(typeof Reflect.get(parsing, "parseOrdinal")).toBe("function");',37+ "});",38+ "",39+ ].join("\n"),40+ },41+ want: "src/parse.ts exports parseOrdinal, which reads an ordinal date such as 2026-280.",42+} satisfies DraftedAsk;43+44+/** The memory drafter, scripted with the canned draft for every attempt a world makes. */45+export const cannedDrafter: Layer.Layer<Drafter | DraftsAsked> = DrafterMemory(46+ Array.replicate(cannedDraft, CANNED_DRAFTS)47+);added:packages/drafting/src/draft-runs/inline.ts+105 added
1+/**2+ * `DraftRuns` in process, for tests and the worlds that run without a3+ * Workflow engine (the web's dev world, the platform's Node world): `start`4+ * runs the round's program (`runDraft`) at once, to its settling, as5+ * `@repo/project`'s `AnswerRunsInline` runs an answer's steps. Each step runs6+ * once, its failures retried as its retries say, without waiting; nothing7+ * is recorded, since nothing replays. A round already under way is not8+ * started twice, and a run that dies is logged: the proposal stays9+ * drafting, and its proposer may draft it again.10+ *11+ * The run reaches the project through `Projects`, which is built over the12+ * project services that start runs: so the runs take their ports when a13+ * round starts (`draftRunsInline`), and `withDraftRunsInline` ties the knot14+ * for a `Projects` layer, handing its runs the `Projects` it builds.15+ */16+import type { RepoHost } from "@repo/artifacts/repo-host";17+import { DraftRuns } from "@repo/project/draft-runs";18+import type { DraftParams } from "@repo/project/draft-runs";19+import { Projects } from "@repo/project/projects";20+import { Context, Deferred, Effect, Layer, Ref } from "effect";21+22+import type { Drafter } from "../drafter.ts";23+import { runDraft } from "../run.ts";24+import type { DraftSteps } from "../run.ts";25+26+/** What a round runs on. */27+export type InlinePorts = Projects | Drafter | RepoHost;28+29+/** Steps run once each, in process: a failure retried as its retries say, at once. */30+const inlineSteps: DraftSteps = {31+ step: (_name, _schema, effect, retry) =>32+ Effect.retry(effect, { times: retry?.limit ?? 0 }),33+};34+35+/** One round's key: its project, proposal and round. */36+const keyOf = ({ project, proposal, round }: DraftParams) =>37+ `${project}/${proposal}/${round}`;38+39+/** `DraftRuns` that run each round in process, on the ports `portsOf` gives when it starts. */40+export const draftRunsInline = (41+ portsOf: Effect.Effect<Context.Context<InlinePorts>>42+): Layer.Layer<never> =>43+ Layer.effect(44+ DraftRuns,45+ Effect.gen(function* () {46+ const running = yield* Ref.make<ReadonlySet<string>>(new Set());47+48+ const claimRun = (key: string) =>49+ Ref.modify(running, (under) =>50+ under.has(key) ? [false, under] : [true, new Set(under).add(key)]51+ );52+53+ const endRun = (key: string) =>54+ Ref.update(running, (under) => {55+ const rest = new Set(under);56+57+ rest.delete(key);58+59+ return rest;60+ });61+62+ return {63+ start: (params) =>64+ Effect.gen(function* () {65+ const key = keyOf(params);66+67+ if (!(yield* claimRun(key))) {68+ return;69+ }70+71+ yield* runDraft(params, inlineSteps).pipe(72+ Effect.provideContext(yield* portsOf),73+ Effect.catchCause((cause) =>74+ Effect.logWarning("a draft's run died", cause)75+ ),76+ Effect.ensuring(endRun(key))77+ );78+ }),79+ };80+ })81+ );82+83+/**84+ * `projects` with in-process draft runs: every project service it builds85+ * starts its rounds through `draftRunsInline`, which reaches the projects86+ * through the `Projects` this layer builds.87+ */88+export const withDraftRunsInline = <E, R>(89+ projects: Layer.Layer<Projects, E, R>90+): Layer.Layer<Projects, E, R | Drafter | RepoHost> =>91+ Layer.effectContext(92+ Effect.gen(function* () {93+ const ready = yield* Deferred.make<Context.Context<InlinePorts>>();94+95+ const built = yield* Layer.build(96+ projects.pipe(Layer.provide(draftRunsInline(Deferred.await(ready))))97+ );98+99+ const around = yield* Effect.context<Drafter | RepoHost>();100+101+ yield* Deferred.succeed(ready, Context.merge(around, built));102+103+ return Context.make(Projects, Context.get(built, Projects));104+ })105+ );added:packages/drafting/src/run.ts+369 added
1+/**2+ * One draft run, as a program over named steps (W9-D14): the platform's3+ * `Answer` Workflow runs it with durable steps (`apps/platform`'s4+ * `workflows/draft-steps.ts`), and `draft-runs/inline.ts` runs it in5+ * process, so both reach the same end.6+ *7+ * - `context`: the project's open proposal (`draftContext`), and the files8+ * the drafter reads, picked from the canonical repo at the landed commit9+ * and read there (never a layer's repo). The step records them, so a10+ * replay reads nothing. A project with no `fix` kind settles at once,11+ * `Failed{IncompleteBrief}`, with no model call.12+ * - for each attempt n, at most `DRAFT_ROUNDS`: `draft-<n>`, the model's13+ * draft, recorded as `DraftedAsk`, so a replay never asks the model14+ * again; then `rehearse-<n>`, its files rehearsed as `accept` would open15+ * them (`rehearseOpen`). `Red` ends the round; `Refused` becomes the next16+ * attempt's feedback (the refusal as `protocol/render` says it, the17+ * diagnosis and the output's tail). A draft the model could not give is18+ * a spent attempt, except `rate-limited`, which the step retries.19+ * - `settle`: the round's end, told to the project (`draftSettled`), which20+ * ignores a round no longer current.21+ *22+ * A step whose retries are spent is kept failed by the engine and thrown23+ * again, unrun, in every replay, where its typed failure is gone: so what24+ * the program makes of it is recorded as a value in a step of its own25+ * (`<step>:gave-up`), which every replay reads back.26+ */27+import { RepoHost, Revision } from "@repo/artifacts/repo-host";28+import { DraftResult, DRAFT_ROUNDS, Rehearsal } from "@repo/project/draft-runs";29+import type { DraftParams } from "@repo/project/draft-runs";30+import { Projects } from "@repo/project/projects";31+import { RepoName, RepoPath } from "@repo/protocol/ids";32+import type { Refusal } from "@repo/protocol/refusal";33+import { IncompleteBrief, VerifierBlocked } from "@repo/protocol/refusal";34+import { Cause, Context, Effect, Option, Record, Schema } from "effect";35+36+import { askTestFolderOf, pickFiles } from "./context.ts";37+import { DraftContext, DraftedAsk, DraftFailed } from "./drafted.ts";38+import type { DraftInput } from "./drafted.ts";39+import { Drafter } from "./drafter.ts";40+import { feedbackText, policyDigest } from "./prompt.ts";41+import { draftedFiles } from "./render.ts";42+43+/** How often, and how far apart, a failed step runs again before it is spent. */44+export interface StepRetry {45+ readonly limit: number;46+ readonly delayMs: number;47+ readonly backoff: "constant" | "linear" | "exponential";48+}49+50+/**51+ * The steps a run takes: each named, its value recorded by `schema`, and52+ * run once per run (a replay reads the record back). A failure is retried53+ * per `retry`, and once spent fails the step.54+ */55+export interface DraftSteps {56+ readonly step: <A, I, E, R>(57+ name: string,58+ schema: Schema.Codec<A, I>,59+ effect: Effect.Effect<A, E, R>,60+ retry?: StepRetry61+ ) => Effect.Effect<A, E, R>;62+}63+64+/**65+ * The model the drafter asks, as a settled round names it (`drafted by`,66+ * and the accepted landing's `Assisted-by:`). The platform gives its67+ * `DRAFT_MODEL`; a world with the memory drafter keeps the default.68+ */69+export const DraftModel = Context.Reference<string>("drafting/DraftModel", {70+ defaultValue: () => "memory",71+});72+73+/** A rate-limited model is asked again, further apart each time. */74+export const rateLimitedRetry: StepRetry = {75+ backoff: "exponential",76+ delayMs: 15_000,77+ limit: 4,78+};79+80+/** A Checker that could not run, or a main that moved, is rehearsed again. */81+export const blockedRetry: StepRetry = {82+ backoff: "exponential",83+ delayMs: 60_000,84+ limit: 3,85+};86+87+/** What `context` records: what the attempts read, or why the round has none. */88+const Prepared = Schema.TaggedUnion({89+ /** The proposal is closed or gone: nothing to draft or settle. */90+ Gone: {},91+ /** The project has no `fix` kind, the only kind drafted. */92+ NoFix: {},93+ Ready: {94+ context: DraftContext,95+ territory: Schema.optionalKey(Schema.NonEmptyString),96+ want: Schema.NonEmptyString,97+ },98+});99+100+type Prepared = typeof Prepared.Type;101+102+/** What `draft-<n>` records: the model's draft, or why it gave none. */103+const Attempted = Schema.TaggedUnion({104+ Drafted: { drafted: DraftedAsk },105+ Spent: { reason: DraftFailed.fields.reason },106+});107+108+type Attempted = typeof Attempted.Type;109+110+/** The kind a draft is: W9 drafts `fix` asks only (W9-D13). */111+const draftedKind = "fix";112+113+/** A proposal's territory as the paths whose files the drafter reads. */114+const territoryPaths = (territory: string | undefined) =>115+ (territory ?? "")116+ .split(/[\s,]+/u)117+ .map((path) => path.replace(/(?:\/\*\*)?\/*$/u, ""))118+ .filter((path) => path !== "" && path !== ".")119+ .map((path) => RepoPath.make(path));120+121+const decoder = new TextDecoder();122+123+/** `{ [key]: value }` when `value` is there, else no key at all. */124+const field = <K extends string, A>(125+ key: K,126+ value: Option.Option<A>127+): Partial<Record<K, A>> =>128+ Option.match(value, {129+ onNone: () => ({}),130+ onSome: (present) => Record.singleton(key, present),131+ });132+133+/** What the next attempt is told when the model gave no draft. */134+const spentText = (reason: string) =>135+ `Your reply gave no draft (${reason}): answer with one JSON object that matches the schema, and nothing else.`;136+137+/** The refusal a round that never rehearsed ends with: no draft, and why. */138+const noDraft = (reason: string): Refusal =>139+ new IncompleteBrief({ missing: [`a draft (${reason})`] });140+141+/** Runs one round of a proposal's draft to its settling, over `steps`. */142+export const runDraft = (143+ params: DraftParams,144+ steps: DraftSteps145+): Effect.Effect<void, never, Projects | Drafter | RepoHost> =>146+ Effect.gen(function* () {147+ const { step } = steps;148+ const projects = yield* Projects;149+ const drafter = yield* Drafter;150+ const host = yield* RepoHost;151+ const model = yield* DraftModel;152+ const project = projects.get(params.project);153+154+ const prepare = Effect.gen(function* () {155+ const api = yield* project;156+ const data = yield* api.draftContext(params.proposal, params.round);157+158+ if (!data.policy.kinds.some(({ name }) => name === draftedKind)) {159+ return Prepared.cases.NoFix.make({});160+ }161+162+ const repo = RepoName.make(data.project);163+164+ const read = (path: RepoPath) =>165+ host.readFile(repo, Revision.Commit({ sha: data.at }), path).pipe(166+ Effect.map(167+ Option.match({168+ onNone: () => "",169+ onSome: (bytes) => decoder.decode(bytes),170+ })171+ ),172+ Effect.catchTag("RepoNotFound", () => Effect.succeed(""))173+ );174+175+ const files = yield* pickFiles(176+ data.paths,177+ { territory: territoryPaths(data.territory), want: data.want },178+ read179+ );180+181+ return Prepared.cases.Ready.make({182+ context: {183+ at: data.at,184+ files,185+ policy: policyDigest(data.policy, askTestFolderOf(files)),186+ project: data.project,187+ },188+ ...field("territory", Option.fromUndefinedOr(data.territory)),189+ want: data.want,190+ });191+ }).pipe(192+ Effect.catchTags({193+ ProposalClosed: () => Effect.succeed(Prepared.cases.Gone.make({})),194+ UnknownProject: () => Effect.succeed(Prepared.cases.Gone.make({})),195+ UnknownProposal: () => Effect.succeed(Prepared.cases.Gone.make({})),196+ })197+ );198+199+ const prepared: Prepared = yield* step("context", Prepared, prepare);200+201+ const settle = (result: DraftResult) =>202+ step(203+ "settle",204+ Schema.Boolean,205+ project.pipe(206+ Effect.flatMap((api) =>207+ api.draftSettled(params.proposal, params.round, result)208+ ),209+ Effect.as(true),210+ Effect.catchTag("UnknownProject", () => Effect.succeed(false))211+ )212+ );213+214+ /** Up to `DRAFT_ROUNDS` attempts, each fed the last one's failure. */215+ const attempts = (216+ ready: Extract<Prepared, { readonly _tag: "Ready" }>217+ ): Effect.Effect<DraftResult> =>218+ Effect.gen(function* () {219+ let feedback = Option.none<string>();220+ let last: Refusal = noDraft("none given");221+222+ for (let attempt = 1; attempt <= DRAFT_ROUNDS; attempt += 1) {223+ const input: DraftInput = {224+ attempt,225+ context: ready.context,226+ ...field("feedback", feedback),227+ ...field("note", Option.fromUndefinedOr(params.note)),228+ ...field("territory", Option.fromUndefinedOr(ready.territory)),229+ want: ready.want,230+ };231+232+ const tried: Attempted = yield* step(233+ `draft-${attempt}`,234+ Attempted,235+ drafter.draft(input).pipe(236+ Effect.map((drafted) =>237+ Attempted.cases.Drafted.make({ drafted })238+ ),239+ Effect.catchTag("DraftFailed", (failed) =>240+ failed.reason === "rate-limited"241+ ? Effect.fail(failed)242+ : Effect.succeed(243+ Attempted.cases.Spent.make({ reason: failed.reason })244+ )245+ )246+ ),247+ rateLimitedRetry248+ ).pipe(249+ // A model still rate-limited once the retries are spent, or a250+ // drafter that died: either way a spent attempt, said as it was.251+ Effect.catchCause((cause) =>252+ step(253+ `draft-${attempt}:gave-up`,254+ Attempted,255+ Effect.succeed(256+ Attempted.cases.Spent.make({257+ reason: Option.match(Cause.findErrorOption(cause), {258+ onNone: () => "model-error" as const,259+ onSome: ({ reason }) => reason,260+ }),261+ })262+ )263+ )264+ )265+ );266+267+ if (Attempted.guards.Spent(tried)) {268+ feedback = Option.some(spentText(tried.reason));269+ last = noDraft(tried.reason);270+271+ continue;272+ }273+274+ const { drafted } = tried;275+ const files = draftedFiles(drafted);276+277+ // A Checker still blocked (or a main still moving) once the278+ // retries are spent ends the round: another draft would not help.279+ const gaveUp = (cause: Cause.Cause<Refusal>) =>280+ step(281+ `rehearse-${attempt}:gave-up`,282+ Rehearsal,283+ Effect.succeed(284+ Rehearsal.cases.Refused.make({285+ diagnosis: "Blocked",286+ excerpt: "",287+ refusal: Option.getOrElse(288+ Cause.findErrorOption(cause),289+ (): Refusal => new VerifierBlocked({})290+ ),291+ })292+ )293+ ).pipe(Effect.map((rehearsal) => ({ blocked: true, rehearsal })));294+295+ const rehearsed = yield* step(296+ `rehearse-${attempt}`,297+ Rehearsal,298+ Effect.flatMap(project, (api) => api.rehearseOpen(files)).pipe(299+ Effect.catchTag("UnknownProject", () =>300+ Effect.fail(new VerifierBlocked({}))301+ )302+ ),303+ blockedRetry304+ ).pipe(305+ Effect.map((rehearsal) => ({ blocked: false, rehearsal })),306+ Effect.catchCause(gaveUp)307+ );308+309+ if (Rehearsal.guards.Red(rehearsed.rehearsal)) {310+ return DraftResult.cases.Red.make({311+ attempts: attempt,312+ files,313+ lane: rehearsed.rehearsal.lane,314+ model,315+ rationale: drafted.rationale,316+ signature: rehearsed.rehearsal.signature,317+ });318+ }319+320+ const refused = rehearsed.rehearsal;321+322+ last = refused.refusal;323+324+ if (rehearsed.blocked) {325+ return DraftResult.cases.Failed.make({326+ attempts: attempt,327+ model,328+ refusal: last,329+ });330+ }331+332+ feedback = Option.some(333+ feedbackText({334+ diagnosis: refused.diagnosis,335+ excerpt: refused.excerpt,336+ refusal: refused.refusal,337+ })338+ );339+ }340+341+ return DraftResult.cases.Failed.make({342+ attempts: DRAFT_ROUNDS,343+ model,344+ refusal: last,345+ });346+ });347+348+ const result: Option.Option<DraftResult> = yield* Prepared.match(prepared, {349+ Gone: () => Effect.succeedNone,350+ NoFix: () =>351+ Effect.succeedSome(352+ DraftResult.cases.Failed.make({353+ attempts: 1,354+ model,355+ refusal: new IncompleteBrief({ missing: ["kinds.fix"] }),356+ })357+ ),358+ Ready: (ready) => Effect.asSome(attempts(ready)),359+ });360+361+ if (Option.isSome(result)) {362+ yield* settle(result.value);363+ }364+ }).pipe(365+ Effect.annotateLogs({366+ proposal: params.proposal,367+ round: String(params.round),368+ })369+ );added:packages/drafting/test/run.test.ts+108 added
1+/**2+ * The draft run's program over a fake step runner: the steps it names, and3+ * what it settles, with the project and the drafter faked at their ports.4+ */5+import { describe, expect, it } from "@effect/vitest";6+import { RepoHost } from "@repo/artifacts/repo-host";7+import { DraftResult } from "@repo/project/draft-runs";8+import type { DraftContextData } from "@repo/project/draft-runs";9+import type { ProjectApi } from "@repo/project/project";10+import { Projects } from "@repo/project/projects";11+import { PublicPolicy } from "@repo/protocol/domain/policy";12+import { ProposalId } from "@repo/protocol/ids";13+import { IncompleteBrief } from "@repo/protocol/refusal";14+import { aProject } from "@repo/testkit/scenarios";15+import { untouchable } from "@repo/testkit/untouchable";16+import { Effect, Layer, Ref, Schema, Struct } from "effect";17+18+import { DrafterMemory, DraftsAsked } from "../src/drafter/memory.ts";19+import { DraftModel, runDraft } from "../src/run.ts";20+import type { DraftSteps } from "../src/run.ts";21+22+const scenario = aProject();23+24+const proposal = ProposalId.make("prop-000001");25+26+/** The scenario's policy as anyone reads it, with no `fix` kind. */27+const withoutFix = Schema.decodeSync(PublicPolicy)(28+ Schema.encodeSync(PublicPolicy)({29+ ...Struct.omit(scenario.policy, ["asks", "functions", "visibility"]),30+ kinds: scenario.policy.kinds.filter(({ name }) => name !== "fix"),31+ })32+);33+34+const context: DraftContextData = {35+ at: scenario.landed,36+ paths: [],37+ policy: withoutFix,38+ project: scenario.project,39+ proposal,40+ round: 1,41+ want: "Parse an ISO week date such as 2026-W41",42+};43+44+describe(runDraft, () => {45+ it.effect(46+ "settles Failed with IncompleteBrief, and never asks the drafter, when the project has no fix kind",47+ () =>48+ Effect.gen(function* () {49+ const names = yield* Ref.make<readonly string[]>([]);50+51+ const settled = yield* Ref.make<52+ readonly (readonly [number, DraftResult])[]53+ >([]);54+55+ const steps: DraftSteps = {56+ step: (name, _schema, effect) =>57+ Effect.andThen(58+ Ref.update(names, (all) => [...all, name]),59+ effect60+ ),61+ };62+63+ const api = untouchable<ProjectApi>("the project", {64+ draftContext: () => Effect.succeed(context),65+ draftSettled: (_proposal, round, result) =>66+ Ref.update(settled, (all) => [...all, [round, result] as const]),67+ });68+69+ yield* runDraft(70+ { project: scenario.project, proposal, round: 1 },71+ steps72+ ).pipe(73+ Effect.provide(74+ Layer.mergeAll(75+ Layer.succeed(Projects, {76+ create: () => Effect.die("no project is made"),77+ get: () => Effect.succeed(api),78+ }),79+ Layer.succeed(80+ RepoHost,81+ untouchable<RepoHost["Service"]>("RepoHost")82+ ),83+ Layer.succeed(DraftModel, "@cf/test/model")84+ )85+ )86+ );87+88+ expect({89+ asked: yield* DraftsAsked.use(({ inputs }) => inputs),90+ names: yield* Ref.get(names),91+ settled: yield* Ref.get(settled),92+ }).toStrictEqual({93+ asked: [],94+ names: ["context", "settle"],95+ settled: [96+ [97+ 1,98+ DraftResult.cases.Failed.make({99+ attempts: 1,100+ model: "@cf/test/model",101+ refusal: new IncompleteBrief({ missing: ["kinds.fix"] }),102+ }),103+ ],104+ ],105+ });106+ }).pipe(Effect.provide(DrafterMemory([])))107+ );108+});modified:scripts/lib/smoke/core-loop.ts+197 added-1 removed
15 unmodified lines16 import { Brand } from "@repo/brand";17 import { AnswerView } from "@repo/protocol/domain/answer";18 import { Ask } from "@repo/protocol/domain/ask";19 import { ClaimView } from "@repo/protocol/domain/claim";20+import { Decision, DecisionSubject } from "@repo/protocol/domain/decision";21 import { Outcome } from "@repo/protocol/domain/outcome";22+import { DraftState, Proposal } from "@repo/protocol/domain/proposal";23 import { Envelope } from "@repo/protocol/envelope";24 import { AskId, CommitSha, Handle, LandedSha } from "@repo/protocol/ids";23-import type { ProjectName } from "@repo/protocol/ids";25+import type { ProjectName, ProposalId } from "@repo/protocol/ids";26 import { explain } from "@repo/protocol/render";27 import {28 Array,29 Config,19 unmodified lines49 "out-of-scope",50 "answer",51 "landing",52 "verdict-note",53+ "draft-propose",54+ "draft-ready",55+ "draft-accept",56 ]);57 58 export type LoopStep = typeof LoopStep.Type;59 750 unmodified lines810 )811 )812 )813 );814+815+// ------------------------------------------------------------------ drafts816+817+/** What the loop's draft proposal wants: a reader of ordinal dates beside `parse`. */818+const DRAFT_WANT =819+ "src/parse.ts exports parseOrdinal, which reads an ordinal date such as 2026-280.";820+821+const Proposed = Schema.Struct({ proposal: Proposal });822+823+const Shown = Schema.Struct({ proposal: Proposal });824+825+/** Proposes the draft's want as `proposer`, with `--draft`: the proposal, drafting. */826+export const proposeDraft = (proposer: LoopPerson, project: ProjectName) =>827+ Effect.map(828+ cli(829+ "draft-propose",830+ proposer,831+ ["propose", "--project", project, "--want", DRAFT_WANT, "--draft"],832+ Proposed833+ ),834+ ({ proposal }) => proposal.id835+ );836+837+/** The draft is still being drafted. */838+class StillDrafting extends Schema.TaggedError<StillDrafting>()(839+ "StillDrafting",840+ {}841+) {}842+843+/** A draft that went red first: the model that drafted it, and its attempts. */844+export interface DraftReady {845+ readonly model: string;846+ readonly attempts: number;847+}848+849+/**850+ * Asks `<cli> proposal <id>` as `reader` until the draft is settled: ready,851+ * or the step fails with the last refusal a failed draft names.852+ */853+export const awaitDraft = (input: {854+ readonly reader: LoopPerson;855+ readonly project: ProjectName;856+ readonly proposal: ProposalId;857+ readonly patience: Patience;858+}) =>859+ Effect.gen(function* () {860+ const { project, proposal, reader } = input;861+862+ /** Where the draft stands: settled, or still drafting, which is asked again. */863+ const settled = (864+ shown: Proposal865+ ): Effect.Effect<DraftState, LoopFailed | StillDrafting> =>866+ Option.match(Option.fromUndefinedOr(shown.draft), {867+ onNone: () =>868+ Effect.fail(869+ failed("draft-ready", `the proposal ${proposal} has no draft`)870+ ),871+ onSome: (state) =>872+ DraftState.guards.Drafting(state)873+ ? Effect.fail(new StillDrafting())874+ : Effect.succeed(state),875+ });876+877+ const draft = yield* cli(878+ "draft-ready",879+ reader,880+ ["proposal", proposal, "--project", project],881+ Shown882+ ).pipe(883+ Effect.flatMap(({ proposal: shown }) => settled(shown)),884+ Effect.retry({885+ schedule: Schedule.spaced(input.patience.every).pipe(886+ Schedule.upTo({ duration: input.patience.within })887+ ),888+ while: Schema.is(StillDrafting),889+ }),890+ Effect.catchTag("StillDrafting", () =>891+ Effect.fail(892+ failed(893+ "draft-ready",894+ `the proposal ${proposal} was still drafting after ${Duration.format(input.patience.within)}`895+ )896+ )897+ )898+ );899+900+ if (DraftState.guards.Ready(draft)) {901+ return {902+ attempts: draft.attempts,903+ model: draft.model,904+ } satisfies DraftReady;905+ }906+907+ return yield* failed(908+ "draft-ready",909+ DraftState.guards.Failed(draft)910+ ? `the draft of ${proposal} failed after ${draft.attempts} attempts, last refused ${draft.refusal}`911+ : `the proposal ${proposal} is still drafting`912+ );913+ });914+915+const TodayIs = Schema.Struct({ decisions: Schema.Array(Decision) });916+917+const Decided = Schema.Struct({ decision: Decision });918+919+/**920+ * Accepts the drafted proposal as `decider`, from their Today, and reads921+ * the landing that opened its ask on main, fetched from the platform at922+ * `origin` into the repo at `dir`: its923+ * trailers, which must disclose the drafter (`Assisted-by:`) and credit924+ * `proposer` as its asker.925+ */926+export const acceptDraft = (input: {927+ readonly decider: LoopPerson;928+ readonly proposer: Handle;929+ readonly project: ProjectName;930+ readonly proposal: ProposalId;931+ readonly dir: string;932+ readonly origin: string;933+}) =>934+ Effect.gen(function* () {935+ const { decider, dir, project, proposal } = input;936+937+ const { decisions } = yield* cli(938+ "draft-accept",939+ decider,940+ ["today", "--project", project],941+ TodayIs942+ );943+944+ const decision = yield* Effect.fromOption(945+ Array.findFirst(946+ decisions,947+ ({ subject }) =>948+ DecisionSubject.guards.OpenProposal(subject) &&949+ subject.proposal === proposal950+ )951+ ).pipe(952+ Effect.mapError(() =>953+ failed(954+ "draft-accept",955+ `${decider.handle}'s Today holds no decision on ${proposal}`956+ )957+ )958+ );959+960+ yield* cli(961+ "draft-accept",962+ decider,963+ [964+ "decide",965+ "--project",966+ project,967+ "--decision",968+ decision.id,969+ "--choice",970+ "accept",971+ "--yes",972+ ],973+ Decided974+ );975+976+ yield* gitOk("draft-accept", decider, dir, [977+ "fetch",978+ "--quiet",979+ `${input.origin}/${project}.git`,980+ "refs/heads/main",981+ ]);982+983+ const trailers = (yield* gitOk("draft-accept", decider, dir, [984+ "log",985+ "-1",986+ "--format=%(trailers:only,unfold)",987+ "FETCH_HEAD",988+ ]))989+ .split("\n")990+ .filter((line) => line.length > 0);991+992+ const missing = [993+ "Assisted-by: ",994+ `Asked-by: ${input.proposer} `,995+ "Ask: ",996+ ].filter((prefix) => !trailers.some((line) => line.startsWith(prefix)));997+998+ return missing.length === 0999+ ? trailers1000+ : yield* failed(1001+ "draft-accept",1002+ `the landing that opened ${proposal}'s ask lacks ${missing.map((prefix) => prefix.trim()).join(" and ")}: its trailers are ${trailers.join("; ") || "none"}`1003+ );1004+ });modified:scripts/lib/smoke/loop.ts+83 added-11 removed
13 unmodified lines14 * 7. `landing`: it lands on main, with the answerer as author, the platform15 * as committer, and the `Asked-by` and `Signed-off-by` trailers;16 * 8. `verdict-note`: its verdict note is on the answer's head in the fork.17 *18+ * With `draft`, three more steps on the same project:19+ *20+ * 9. `draft-propose`: the answerer proposes a want with `--draft`;21+ * 10. `draft-ready`: `proposal <id>` until the platform's agent has22+ * drafted it, red first (a failed draft fails the step);23+ * 11. `draft-accept`: the decider accepts it from Today, and the landing24+ * that opened its ask discloses the drafter (`Assisted-by:`) and25+ * credits the answerer as its asker.26+ *27 * Each step is timed and printed as it passes; the first that fails ends28 * the run. The throwaway project, its repo and the claim's fork are written29 * to the throwaway ledger (`infra/created.ts`, by `smoke`) as soon as each30 * exists. It never runs on `demo`: a throwaway project would show on the17 unmodified lines48 import { recordCreated } from "../../../infra/created.ts";49 import type { Created } from "../../../infra/created.ts";50 import { declaredStage, resources } from "../../../infra/stages.ts";51 import {52+ acceptDraft,53+ awaitDraft,54 awaitLanding,55 claimAsk,56 initProject,57 LoopFailed,58 openAsk,59 personAt,60+ proposeDraft,61 pushAnswer,62 pushOutOfScope,63 readLanding,64 readVerdictNote,17 unmodified lines82 readonly step: LoopStep;83 readonly ms: number;84 }85 86+/** A drafted ask the loop accepted: the model, its attempts, and its landing's trailers. */87+export interface DraftReport {88+ readonly model: string;89+ readonly attempts: number;90+ /** From the proposal to the draft settled, in ms. */91+ readonly ms: number;92+ readonly trailers: readonly string[];93+}94+95 /** A loop that passed: what each step found, and how long each took. */96 export interface SmokeLoopReport {97 readonly project: ProjectName;98 /** The refusals git printed for the out-of-territory push: `OutOfScope` among them. */5 unmodified lines104 /** Every trailer of the landing commit, as git prints them. */105 readonly trailers: readonly string[];106 readonly noteFound: boolean;107 readonly timings: readonly StepTiming[];108+ /** With `draft`, the drafted ask it accepted. */109+ readonly draft?: DraftReport;110 }111 112 /** What one loop runs on, and as whom. */113 export interface LoopInput {8 unmodified lines122 /** Claims the ask and pushes the answer. */123 readonly answerer: Redacted.Redacted;124 /** How the loop waits for the landing: every 2 s, for up to 10 minutes, unless given. */125 readonly patience?: Patience;126+ /** Also propose with a draft, wait for it, and accept it (`--draft`). */127+ readonly draft?: boolean;128 }129 130 const PATIENCE: Patience = {131 every: Duration.seconds(2),217 unmodified lines349 stage,350 "verdict-note"351 )(readVerdictNote({ answerer, dir: work, head }));352 328- return {353+ const timings = [354+ people,355+ init,356+ opened,357+ claimed,358+ refused,359+ answered,360+ landing,361+ noted,362+ ];363+364+ const report = {365 author: read.author,366 committer: read.committer,367 landed,368 noteFound: true,369 project,370 refusedWith,335- timings: [336- people,337- init,338- opened,339- claimed,340- refused,341- answered,342- landing,343- noted,344- ],371+ timings,372 trailers: read.trailers,373 };374+375+ if (input.draft !== true) {376+ return report;377+ }378+379+ const [proposal, proposed] = yield* timed(380+ stage,381+ "draft-propose"382+ )(proposeDraft(answerer, project));383+384+ const [ready, drafted] = yield* timed(385+ stage,386+ "draft-ready"387+ )(388+ awaitDraft({389+ patience: input.patience ?? PATIENCE,390+ project,391+ proposal,392+ reader: answerer,393+ })394+ );395+396+ const [trailers, accepted] = yield* timed(397+ stage,398+ "draft-accept"399+ )(400+ acceptDraft({401+ decider,402+ dir: `${dir}/start`,403+ origin,404+ project,405+ proposal,406+ proposer: answerer.handle,407+ })408+ );409+410+ return {411+ ...report,412+ draft: {413+ ...ready,414+ ms: proposed.ms + drafted.ms,415+ trailers,416+ },417+ timings: [...timings, proposed, drafted, accepted],418+ };419 }).pipe(Effect.scoped);modified:scripts/smoke.ts+46 added-4 removed
25 unmodified lines26 * bun scripts/smoke.ts --stage dev-oscabriel --loop27 *28 * `--loop` refuses `--stage demo` before anything else: the throwaway would29 * show on the front page the user records.30+ *31+ * `--loop --draft` also has the platform's agent draft an ask on the32+ * throwaway project: the answerer proposes a want with `--draft`, the loop33+ * waits for the draft to go red first, and the decider accepts it; the34+ * landing that opens the ask must disclose the drafter (`Assisted-by:`).35+ * It prints the model, the attempts and the time. `--draft` without36+ * `--loop` is refused before any request.37 */38 import { BunRuntime, BunServices } from "@effect/platform-bun";39 import { Handle, sameHandle } from "@repo/protocol/ids";40 import {16 unmodified lines57 subdomainFile,58 } from "../infra/stages.ts";59 import { DemoStageRefused, LoopFailed, smokeLoop } from "./lib/smoke/loop.ts";60 61+/** `--draft` was given without `--loop`: only the loop has a project to draft on. */62+export class DraftNeedsLoop extends Schema.TaggedError<DraftNeedsLoop>()(63+ "DraftNeedsLoop",64+ { flag: Schema.Literal("--draft") }65+) {66+ override get message() {67+ return `${this.flag} drafts an ask on the loop's throwaway project: run it with --loop`;68+ }69+}70+71 export {72 NoOrigin,73 platformProbes,74 probes,107 unmodified lines182 const run = yield* runName;183 184 yield* Console.log(`smoke ${stage}: loop smoke-${run} at ${origin}`);185 169- const report = yield* smokeLoop({ ...tokens, origin, run, stage });186+ const report = yield* smokeLoop({187+ ...tokens,188+ draft: argv.includes("--draft"),189+ origin,190+ run,191+ stage,192+ });193+194 const total = report.timings.reduce((sum, { ms }) => sum + ms, 0);195 196 yield* Console.log(197 `smoke ${stage}: loop passed in ${total} ms: ${report.project} landed ${report.landed.slice(0, 12)} by ${report.author}, refused first with ${report.refusedWith.join(", ")}; trailers ${report.trailers.join("; ")}`198 );199+200+ if (report.draft !== undefined) {201+ const { attempts, model, ms, trailers } = report.draft;202+203+ yield* Console.log(204+ `smoke ${stage}: draft by ${model} went red first in ${attempts} of 3 attempts, ${ms} ms from proposal to draft; its ask opened with ${trailers.join("; ")}`205+ );206+ }207 });208 209 /**178- * `bun scripts/smoke.ts --stage <s> [--loop] …`: the probes, and with179- * `--loop` the core loop after them.210+ * `bun scripts/smoke.ts --stage <s> [--loop [--draft]] …`: the probes, and211+ * with `--loop` the core loop after them; `--draft` alone is refused.212 */213 export const main = (argv: readonly string[]) =>182- argv.includes("--loop") ? loopMain(argv) : probeMain(argv);214+ Effect.gen(function* () {215+ if (argv.includes("--loop")) {216+ return yield* loopMain(argv);217+ }218 219+ if (argv.includes("--draft")) {220+ return yield* new DraftNeedsLoop({ flag: "--draft" });221+ }222+223+ return yield* probeMain(argv);224+ });225+226 if (import.meta.main) {227 BunRuntime.runMain(228 Effect.gen(function* () {229 const args = yield* (yield* Stdio.Stdio).args;5 unmodified lines