Run a proposal's draft durably as a Draft round of the Answer Workflow
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- packages/drafting/src/run.ts: `runDraft(params, steps)`, the round as named steps shared by the Workflow and the inline run: `context` (the open proposal, files picked from the canonical repo at the landed SHA and recorded, so a replay reads nothing), up to three `draft-<n>` (the model's draft recorded as JSON, so a replay never calls the model) and `rehearse-<n>` (red first, no landing), then `settle`. A refusal feeds the next attempt as protocol/render says it, with diagnosis and output tail. A project without `fix` settles Failed{IncompleteBrief} with no model call. - Retries: `rate-limited` is a step retry ({4, 15 s, exponential}) and no spent attempt; VerifierBlocked/StaleBase {3, 60 s, exponential}. A spent step's outcome is recorded in `<step>:gave-up` (OnPush's `settle` pattern), so a replay that finds the engine's kept failure converges; a rehearsal still blocked ends the round Failed, since redrafting cannot help. - The model a round names comes from `DraftModel` (a Context.Reference, default `memory`): the Drafter port carries none; the platform gives `DRAFT_MODEL`. - apps/platform: `DraftParams` (tagged `Draft`, the note travelling with it) in `WorkflowParams`, `draftId` = draft-<project>-<proposal>-r<round>; `Answer.run` dispatches it to `workflows/draft-steps.ts`, with every draft step handed `timeout: "10 minutes"` (`timedSteps`, so step.ts stays as it is). No Workflow, binding, DO or class added or renamed. - `adapters/draft-runs-workflow.ts`: create-or-restart over ANSWER, but a `complete` instance is never restarted (that would ask the model again for a settled round); `ports.ts` provides it in every port set, and `draftPorts` (DrafterWorkersAi(AI, DRAFT_MODEL)) only to draft rounds, so WorkerPorts and the test world keep their shape. - handlers.ts: `proposeAsk` with `draft` spends the draft rate limit before the proposal limit (CapReached past it); `draftAsk` already did. - `draft-runs/inline.ts`: the same program in process; `withDraftRunsInline` ties a Projects layer to its own runs. `draft-runs/canned.ts`: the canned `parse-ordinal` draft, red on any src/parse.ts lacking parseOrdinal. The web's dev world and the Node world (serve-world.ts) draft with it offline; datekit's dev policy.json states that ask, unopened. - smoke: `--loop --draft` proposes with --draft on the throwaway project, polls `proposal <id>` until settled, accepts as the operator, and checks the opening landing has Assisted-by, Asked-by the proposer and Ask:; it prints model, attempts and time. `--draft` without `--loop` is refused (DraftNeedsLoop) before any request. - Tests: packages/drafting/test/run.test.ts (no fix kind: no model call); apps/platform/test/workflows/draft.test.ts (NotRedFirst fed to attempt 2, one decision, Ready{attempts: 2}, a replay asks 2 not 4; three refusals settle Failed with the last tag; rate-limited retried as a step; a gone proposal stops after context; one instance per round; errored restarts, complete never; the engine's timeouts and retries; the draft limit); core-loop.test.ts (propose with draft, the inline run, accept, Asked-by, Decided-by and Assisted-by verified); dev-backend.test.ts (a dev-world draft Ready, its decision joining Today); smoke-loop.test.ts (--draft against the Node world; --draft without --loop refused, no request). - Platform entry +13,505 bytes (1,645,355 to 1,658,860 of 1,900,000). - ASSUMPTION: in the seeded dev world the draft's decision waits on ines-v's Today as overflow (seeded decisions expire first), so the dev test asserts the overflow, not a shown card.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
20 files+2087 added−35 removed
- tests:+981 added−3 removed
- other:+1106 added−32 removed
Provenance
- Commit
fb60580- Tree
50e4a66- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
bbe1442
20 files changed+2087 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+47 added-5 removed
12345677 unmodified lines15161718192021222324252627282930233132253334353637383940414241 unmodified lines84858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119871201211221239112412512693127128129130131132133134135136137138139140141142import type { RepoHost } from "@repo/artifacts/repo-host";import type { Drafter } from "@repo/drafting/drafter";import type { Projects } from "@repo/project/projects";/** * The `Answer` Workflow: carries one admitted answer through merge, checks * and landing, each a durable step. The class is thin: * it decodes its params, runs `runAnswer` with its steps over the engine's7 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 { 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 config = decodeEnv(this.env); const ports = Layer.unwrap(Effect.map(decodeEnv(this.env), workerPorts)); const ports = Layer.unwrap(Effect.map(config, workerPorts)); const { payload } = event;
if (drafts(payload)) { return runDraftWorkflow( Layer.merge(ports, Layer.unwrap(Effect.map(config, draftPorts))), payload, step ); }
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+29 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+/** The instance a draft's round runs as: one per project, proposal and round. */68+export const draftId = (69+ params: Pick<DraftParams, "project" | "proposal" | "round">70+) =>71+ `draft-${params.project}-${params.proposal}-r${params.round}`.slice(72+ 0,73+ ID_LENGTH74+ );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+535 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+ ProposalId,30+ RepoName,31+ RepoPath,32+} from "@repo/protocol/ids";33+import { Anonymous, Person } from "@repo/protocol/principal";34+import { CapReached } from "@repo/protocol/refusal";35+import { advanceTo } from "@repo/testkit/clock";36+import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";37+import { Context, Effect, Layer, Option, Ref, Schema } from "effect";38+39+import { DraftRunsWorkflow } from "../../src/adapters/draft-runs-workflow.ts";40+import type { DraftWorkflow } from "../../src/adapters/draft-runs-workflow.ts";41+import { DraftParams, draftId } from "../../src/answer-runs.ts";42+import { Handlers } from "../../src/handlers.ts";43+import type { PlatformConfig } from "../../src/platform.ts";44+import { runDraftWorkflow } from "../../src/workflows/answer.ts";45+import type { EngineSteps } from "../../src/workflows/draft-steps.ts";46+import { draftSteps } from "../../src/workflows/draft-steps.ts";47+import { memoSteps, StepRunner } from "../../src/workflows/step.ts";48+import type { StepRetry } from "../../src/workflows/step.ts";49+import { as, seeded, worldOf } from "../handlers.fixtures.ts";50+import { Checker, Pusher, worldWith } from "./answer.fixtures.ts";51+52+/** What the engine is handed with each step. */53+type EngineConfig = Parameters<EngineSteps["do"]>[1];54+55+/** datekit, decided by alice, with carol vouched and one `fix` ask she may want drafted. */56+const scenario = aProject({ people: ["carol"] }).pipe(57+ withVouches(["carol"]),58+ withAsk({ id: "parse-week", territory: "." })59+);60+61+const { policy, project } = scenario;62+63+const repo = RepoName.make(project);64+65+const alice = Person.make({ handle: scenario.initializer });66+67+const carol = Person.make({68+ handle: scenario.people.get("carol") ?? scenario.initializer,69+});70+71+const redThenGreen = LaneName.make("redThenGreen");72+73+const model = "@cf/moonshotai/kimi-k2.7-code";74+75+const want = "Parse an ISO week date such as 2026-W41";76+77+const proposal = ProposalId.make("prop-000001");78+79+const params = DraftParams.make({ project, proposal, round: 1 });80+81+const start = [82+ ["package.json", '{ "name": "datekit", "type": "module" }\n'],83+ ["src/parse.ts", "export const parse = (s) => ({});\n"],84+] as const;85+86+/** A draft of the scenario's ask whose test says `assertion`. */87+const draftOf = (assertion: string, id = "parse-week"): DraftedAsk => ({88+ id: AskId.make(id),89+ kind: "fix",90+ rationale: `${id}: parseWeek is missing, so its test fails by an assertion`,91+ territory: [RepoPath.make("src/parse.ts")],92+ test: {93+ path: RepoPath.make(`test/${id}.test.ts`),94+ source: [95+ 'import { expect, it } from "bun:test";',96+ 'import { parse } from "../src/parse.ts";',97+ "",98+ `it("${id}", () => {`,99+ ` ${assertion}`,100+ "});",101+ "",102+ ].join("\n"),103+ },104+ want,105+});106+107+/** A test that passes on main, so its draft is not red first. */108+const passing = draftOf("expect(parse('2026-W41')).toStrictEqual({});");109+110+/** A second test that passes on main. */111+const passingToo = draftOf("expect(parse('2026-W42')).toStrictEqual({});");112+113+/** A test that fails on main by its assertion. */114+const red = draftOf("expect(parse('2026-W41').week).toBe(41);");115+116+/** A draft of an ask the project's rules do not state. */117+const unstated = draftOf(118+ "expect(parse('2026-W41').week).toBe(41);",119+ "parse-month"120+);121+122+/** carol proposes the want with a draft, on datekit's first push. */123+const proposed = Effect.gen(function* () {124+ yield* advanceTo("2026-10-08T12:00:00Z");125+126+ const api = yield* Projects.use((each) => each.create(project)).pipe(127+ Effect.orDie128+ );129+130+ yield* api.initProject(alice, {}).pipe(Effect.orDie);131+132+ const first = yield* Pusher.use((each) =>133+ each.push(repo, Option.none(), start)134+ );135+136+ yield* api.recordFirstPush(alice, first).pipe(Effect.orDie);137+138+ // The project's first proposal: `proposal`.139+ yield* api140+ .proposeAsk(carol, { draft: true, territory: "src/parse.ts", want })141+ .pipe(Effect.orDie);142+143+ return { api, main: LandedSha.make(first) };144+});145+146+/** `drafted`'s files composed onto `main`, its check scripted to end `runs` there. */147+const scripted = (148+ main: LandedSha,149+ drafted: DraftedAsk,150+ result: "passed" | "failed"151+) =>152+ Effect.gen(function* () {153+ const { commit } = yield* Lander.use((lander) =>154+ lander.compose({ files: draftedFiles(drafted), main, repo })155+ ).pipe(Effect.orDie);156+157+ yield* Checker.use((script) =>158+ script.script(CheckAt.cases.Commit.make({ commit }), redThenGreen, [159+ result === "passed"160+ ? { result }161+ : { result, signature: "redThenGreen: expected 41, got undefined" },162+ ])163+ );164+ });165+166+/** The proposal's draft state, as anyone reads it. */167+const draftOfProposal = (api: ProjectApi) =>168+ Effect.map(169+ Effect.orDie(api.showProposal(Anonymous.make({}), proposal)),170+ ({ proposal: shown }) => shown.draft171+ );172+173+/** alice's open-proposal decisions on Today. */174+const proposalDecisions = (api: ProjectApi) =>175+ Effect.map(Effect.orDie(api.today(alice)), ({ decisions }) =>176+ decisions.filter(({ subject }) =>177+ DecisionSubject.guards.OpenProposal(subject)178+ )179+ );180+181+const asked = DraftsAsked.use(({ inputs }) => inputs);182+183+/** The world, the memory drafter scripted with `script`, and the platform's model. */184+const worldDrafting = (script: Parameters<typeof DrafterMemory>[0]) =>185+ Layer.mergeAll(186+ worldWith(policy),187+ DrafterMemory(script),188+ Layer.succeed(DraftModel, model)189+ );190+191+describe("a draft's run, over steps that replay", () => {192+ it.effect(193+ "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",194+ () =>195+ Effect.gen(function* () {196+ const { api, main } = yield* proposed;197+198+ yield* scripted(main, passing, "passed");199+ yield* scripted(main, red, "failed");200+201+ const steps = yield* memoSteps();202+203+ yield* draftSteps(params).pipe(Effect.provide(steps));204+205+ const inputs = yield* asked;206+ const decisions = yield* proposalDecisions(api);207+208+ expect({209+ attempts: inputs.map(({ attempt }) => attempt),210+ decisions: decisions.length,211+ draft: yield* draftOfProposal(api),212+ firstFeedback: inputs[0]?.feedback,213+ redFirst: decisions[0]?.evidence.find(214+ ({ label }) => label === "red first"215+ )?.value,216+ refusedWith: inputs[1]?.feedback?.split("\n")[0]?.split(":")[0],217+ }).toStrictEqual({218+ attempts: [1, 2],219+ decisions: 1,220+ draft: DraftState.cases.Ready.make({221+ attempts: 2,222+ model,223+ red: {224+ lane: redThenGreen,225+ signature: "redThenGreen: expected 41, got undefined",226+ },227+ round: 1,228+ }),229+ firstFeedback: undefined,230+ redFirst: `${redThenGreen}: redThenGreen: expected 41, got undefined`,231+ refusedWith: "NotRedFirst",232+ });233+234+ // The finished instance, run again: every step reads its record.235+ yield* draftSteps(params).pipe(Effect.provide(steps));236+237+ expect({238+ asked: (yield* asked).length,239+ decisions: (yield* proposalDecisions(api)).length,240+ }).toStrictEqual({ asked: 2, decisions: 1 });241+ }).pipe(Effect.provide(worldDrafting([passing, red])))242+ );243+244+ it.effect(245+ "settles Failed with the last refusal's tag once three attempts are refused",246+ () =>247+ Effect.gen(function* () {248+ const { api, main } = yield* proposed;249+250+ yield* scripted(main, passing, "passed");251+ yield* scripted(main, passingToo, "passed");252+253+ yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));254+255+ expect({256+ asked: (yield* asked).length,257+ decisions: (yield* proposalDecisions(api)).length,258+ draft: yield* draftOfProposal(api),259+ }).toStrictEqual({260+ asked: 3,261+ decisions: 1,262+ draft: DraftState.cases.Failed.make({263+ attempts: 3,264+ model,265+ refusal: "IncompleteBrief",266+ round: 1,267+ }),268+ });269+ }).pipe(Effect.provide(worldDrafting([passing, passingToo, unstated])))270+ );271+272+ it.effect(273+ "retries a rate-limited model as a step, without spending an attempt",274+ () =>275+ Effect.gen(function* () {276+ const { api, main } = yield* proposed;277+278+ yield* scripted(main, red, "failed");279+280+ yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));281+282+ expect({283+ asked: (yield* asked).map(({ attempt }) => attempt),284+ draft: yield* draftOfProposal(api),285+ }).toStrictEqual({286+ asked: [1, 1],287+ draft: DraftState.cases.Ready.make({288+ attempts: 1,289+ model,290+ red: {291+ lane: redThenGreen,292+ signature: "redThenGreen: expected 41, got undefined",293+ },294+ round: 1,295+ }),296+ });297+ }).pipe(298+ Effect.provide(299+ worldDrafting([new DraftFailed({ reason: "rate-limited" }), red])300+ )301+ )302+ );303+304+ it.effect(305+ "stops after its context when the proposal is gone: no attempt, no settling",306+ () =>307+ Effect.gen(function* () {308+ yield* proposed;309+310+ const names = yield* Ref.make<readonly string[]>([]);311+312+ const memo = Context.get(313+ yield* Layer.build(yield* memoSteps()),314+ StepRunner315+ );316+317+ const logged = StepRunner.of({318+ step: (name, schema, effect, retry?: StepRetry) =>319+ Effect.andThen(320+ Ref.update(names, (all) => [...all, name]),321+ memo.step(name, schema, effect, retry)322+ ),323+ });324+325+ yield* draftSteps(326+ DraftParams.make({327+ project,328+ proposal: ProposalId.make("prop-000009"),329+ round: 1,330+ })331+ ).pipe(Effect.provideService(StepRunner, logged));332+333+ expect({334+ asked: (yield* asked).length,335+ names: yield* Ref.get(names),336+ }).toStrictEqual({ asked: 0, names: ["context"] });337+ }).pipe(Effect.provide(worldDrafting([])))338+ );339+});340+341+/** A fake `ANSWER` binding: each instance made and restarted, every instance in `status`. */342+const fakeWorkflow = (status: InstanceStatus["status"]) => {343+ const made: string[] = [];344+ const restarted: string[] = [];345+346+ const workflow: DraftWorkflow = {347+ create: ({ id }) => {348+ if (made.includes(id)) {349+ return Promise.reject(new Error(`instance ${id} already exists`));350+ }351+352+ made.push(id);353+354+ return Promise.resolve({ id });355+ },356+ get: (id) =>357+ Promise.resolve({358+ id,359+ restart: () => {360+ restarted.push(id);361+362+ return Promise.resolve();363+ },364+ status: () => Promise.resolve({ status }),365+ }),366+ };367+368+ return { made, restarted, workflow };369+};370+371+describe("the Workflow's draft runs", () => {372+ it.effect(373+ "starts one instance per round: a second start finds it, and a run still going is left alone",374+ () =>375+ Effect.gen(function* () {376+ const fake = fakeWorkflow("running");377+378+ const starting = DraftRuns.pipe(379+ Effect.flatMap((runs) =>380+ runs.start({ note: "keep it small", project, proposal, round: 1 })381+ ),382+ Effect.provide(DraftRunsWorkflow(fake.workflow))383+ );384+385+ yield* starting;386+ yield* starting;387+388+ expect({389+ made: fake.made,390+ restarted: fake.restarted,391+ }).toStrictEqual({392+ made: [`draft-${project}-${proposal}-r1`],393+ restarted: [],394+ });395+396+ expect(draftId(params)).toBe(`draft-${project}-${proposal}-r1`);397+ })398+ );399+400+ it.effect(401+ "starts an errored round's instance again, and never a complete one, which would ask the model again",402+ () =>403+ Effect.gen(function* () {404+ const errored = fakeWorkflow("errored");405+ const complete = fakeWorkflow("complete");406+407+ const twice = (workflow: DraftWorkflow) =>408+ DraftRuns.pipe(409+ Effect.flatMap((runs) =>410+ Effect.andThen(411+ runs.start({ project, proposal, round: 1 }),412+ runs.start({ project, proposal, round: 1 })413+ )414+ ),415+ Effect.provide(DraftRunsWorkflow(workflow))416+ );417+418+ yield* twice(errored.workflow);419+ yield* twice(complete.workflow);420+421+ expect({422+ complete: complete.restarted,423+ errored: errored.restarted,424+ }).toStrictEqual({425+ complete: [],426+ errored: [`draft-${project}-${proposal}-r1`],427+ });428+ })429+ );430+431+ it.effect(432+ "gives the engine a 10-minute timeout on each step, and the rate-limit retries on the model's",433+ () =>434+ Effect.gen(function* () {435+ const { main } = yield* proposed;436+437+ yield* scripted(main, red, "failed");438+439+ const configs: (readonly [string, EngineConfig])[] = [];440+ const kept = new Map<string, Schema.Json>();441+442+ const engine: EngineSteps = {443+ do: (name, config, body) => {444+ configs.push([name, config]);445+446+ const found = kept.get(name);447+448+ return found === undefined449+ ? body().then((value) => {450+ kept.set(name, value);451+452+ return value;453+ })454+ : Promise.resolve(found);455+ },456+ };457+458+ const ports = yield* Effect.context<Projects | Drafter | RepoHost>();459+460+ const payload = yield* Schema.encodeEffect(DraftParams)(params);461+462+ yield* Effect.promise(() =>463+ runDraftWorkflow(Layer.succeedContext(ports), payload, engine)464+ );465+466+ expect(configs.map(([name]) => name)).toStrictEqual([467+ "context",468+ "draft-1",469+ "rehearse-1",470+ "settle",471+ ]);472+473+ expect(new Map(configs).get("draft-1")).toStrictEqual({474+ retries: { backoff: "exponential", delay: 15_000, limit: 4 },475+ timeout: "10 minutes",476+ });477+478+ expect(479+ configs.filter(([, config]) => config.timeout !== "10 minutes")480+ ).toStrictEqual([]);481+ }).pipe(Effect.provide(worldDrafting([red])))482+ );483+484+ it("takes the Worker's bindings as the generated Env types them", () => {485+ expectTypeOf<Env["ANSWER"]>().toExtend<486+ Parameters<typeof DraftRunsWorkflow>[0]487+ >();488+ expectTypeOf<PlatformConfig["AI"]>().toExtend<AiLike>();489+ });490+});491+492+describe("proposing with a draft", () => {493+ it.effect(494+ "spends the person's draft limit first: past it, CapReached, while a proposal without a draft still goes through",495+ () =>496+ Effect.gen(function* () {497+ yield* advanceTo("2026-10-08T12:00:00Z");498+ yield* seeded(scenario);499+500+ const asCarol = yield* as("carol");501+502+ const drafted = yield* asCarol.proposeAsk({503+ draft: true,504+ project,505+ want,506+ });507+508+ const past = yield* Effect.flip(509+ asCarol.proposeAsk({ draft: true, project, want })510+ );511+512+ const plain = yield* asCarol.proposeAsk({ project, want });513+514+ expect({515+ drafted: drafted.proposal.draft?._tag,516+ past,517+ plain: plain.proposal.draft,518+ }).toStrictEqual({519+ drafted: "Drafting",520+ past: new CapReached({ cap: 1 }),521+ plain: undefined,522+ });523+ }).pipe(524+ Effect.provide(525+ Handlers.pipe(526+ Layer.provideMerge(527+ worldOf([scenario], {528+ limits: { claim: 5, draft: 1, proposal: 5 },529+ })530+ )531+ )532+ )533+ )534+ );535+});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+362 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+ Effect.catchCause(() =>250+ step(251+ `draft-${attempt}:gave-up`,252+ Attempted,253+ Effect.succeed(254+ Attempted.cases.Spent.make({ reason: "rate-limited" })255+ )256+ )257+ )258+ );259+260+ if (Attempted.guards.Spent(tried)) {261+ feedback = Option.some(spentText(tried.reason));262+ last = noDraft(tried.reason);263+264+ continue;265+ }266+267+ const { drafted } = tried;268+ const files = draftedFiles(drafted);269+270+ // A Checker still blocked (or a main still moving) once the271+ // retries are spent ends the round: another draft would not help.272+ const gaveUp = (cause: Cause.Cause<Refusal>) =>273+ step(274+ `rehearse-${attempt}:gave-up`,275+ Rehearsal,276+ Effect.succeed(277+ Rehearsal.cases.Refused.make({278+ diagnosis: "Blocked",279+ excerpt: "",280+ refusal: Option.getOrElse(281+ Cause.findErrorOption(cause),282+ (): Refusal => new VerifierBlocked({})283+ ),284+ })285+ )286+ ).pipe(Effect.map((rehearsal) => ({ blocked: true, rehearsal })));287+288+ const rehearsed = yield* step(289+ `rehearse-${attempt}`,290+ Rehearsal,291+ Effect.flatMap(project, (api) => api.rehearseOpen(files)).pipe(292+ Effect.catchTag("UnknownProject", () =>293+ Effect.fail(new VerifierBlocked({}))294+ )295+ ),296+ blockedRetry297+ ).pipe(298+ Effect.map((rehearsal) => ({ blocked: false, rehearsal })),299+ Effect.catchCause(gaveUp)300+ );301+302+ if (Rehearsal.guards.Red(rehearsed.rehearsal)) {303+ return DraftResult.cases.Red.make({304+ attempts: attempt,305+ files,306+ lane: rehearsed.rehearsal.lane,307+ model,308+ rationale: drafted.rationale,309+ signature: rehearsed.rehearsal.signature,310+ });311+ }312+313+ const refused = rehearsed.rehearsal;314+315+ last = refused.refusal;316+317+ if (rehearsed.blocked) {318+ return DraftResult.cases.Failed.make({319+ attempts: attempt,320+ model,321+ refusal: last,322+ });323+ }324+325+ feedback = Option.some(326+ feedbackText({327+ diagnosis: refused.diagnosis,328+ excerpt: refused.excerpt,329+ refusal: refused.refusal,330+ })331+ );332+ }333+334+ return DraftResult.cases.Failed.make({335+ attempts: DRAFT_ROUNDS,336+ model,337+ refusal: last,338+ });339+ });340+341+ const result: Option.Option<DraftResult> = yield* Prepared.match(prepared, {342+ Gone: () => Effect.succeedNone,343+ NoFix: () =>344+ Effect.succeedSome(345+ DraftResult.cases.Failed.make({346+ attempts: 1,347+ model,348+ refusal: new IncompleteBrief({ missing: ["kinds.fix"] }),349+ })350+ ),351+ Ready: (ready) => Effect.asSome(attempts(ready)),352+ });353+354+ if (Option.isSome(result)) {355+ yield* settle(result.value);356+ }357+ }).pipe(358+ Effect.annotateLogs({359+ proposal: params.proposal,360+ round: String(params.round),361+ })362+ );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