Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI binding
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- Protocol: ten contracts (listRefs, readTree, listPaths, readFile, log, showCommit, why on rpc and web only; projectPolicy, showProposal, draftAsk on every surface), domain/code.ts, PublicPolicy (Policy minus asks, functions, visibility), DraftState and Proposal.draft, ProposalDrafted, proposeAsk's draft flag with a check that a drafted proposal carries no files or sealed answer. Five refusals: UnknownPath, UnknownRevision, UnknownProposal, ProposalClosed, DraftInProgress. UnknownPath names its commit as `commit`, since `at` is every refusal's line pointer. - A `true`-or-absent payload field is a bare CLI switch, so `propose --draft` reads as one; `policy`, `proposal` and `ask draft` derive from the contracts. - RepoHost: Commit carries authoredAt/committedAt (Unix seconds) in every adapter and both fakes; log takes an optional offset; `tags` lists every refs/tags/* peeled to its commit (smart HTTP's peeled lines, or isomorphic-git's readCommit peel). The isomorphic-git stores now copy an annotated tag object on push. `refs` is unchanged. - Project: ProjectApi gains head, landings, forks (claim forks; the DO records no working forks) and policy, built; draftAsk, showProposal and proposeAsk's draft branch die "not built" until drafting lands. repo-names moves into @repo/project (the platform re-exports it). The code facade (@repo/project/code) has its final signatures with stub bodies; CodeCache is a Context.Reference that caches nothing by default. - Platform: both handler files serve every new contract through the facade or ProjectApi; draftAsk spends a new "draft" rate limit. `GET /` and `GET /:project/raw/*` reach stubs answering 501, both exempt from the 401. HostInfo (web URL, draft model) lives in host-info.ts, re-exported by surfaces.ts, so home.ts and surfaces.ts make no import cycle. - Wrangler: the `ai` binding, DRAFT_LIMIT (2 a minute; ids 1004/1104/1204), DRAFT_MODEL and PUBLIC_WEB_URL in all three blocks; types regenerated; the env decodes them. Local PUBLIC_WEB_URL is Vite's default port, 5173 (ASSUMPTION: apps/web sets no other). - packages/drafting skeleton: DraftedAsk, DraftContext, DraftInput, DraftFailed, the Drafter port and a scripted memory adapter, with its full dependency list so later work edits no lockfile. - Byte limits per Worker. Measured: platform entry 1,617,480 of 1,900,000; sandbox 570,420 of 1,665,000; web entry 717,922 of 1,665,000 and JavaScript 2,394,604 of 2,500,000. - import-examples: a root script whose entry says it is not built yet and exits 1, its tsconfig allowances, and its AGENTS.md line. - Tests: w9-contracts (policy over /rpc, code reads reach the facade, draft needs a person, / and raw slots open to a stale bearer), bindings (AI, DRAFT_LIMIT, vars per block), do-reads, code-facade, the RepoHost contract's commit times, log offset and peeled tags on every adapter, refusal and render rows, the contracts table and fixtures, the CLI switch, per-Worker budgets, the import-examples entry. - agent-kit's refusal guidance is unchanged: it covers answer refusals only, and the new ones file under Decision and Lookup.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
78 files+2827 added−179 removed
- tests:+1045 added−38 removed
- other:+1782 added−141 removed
Provenance
- Commit
fc4691d- Tree
344d9fa- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
235ff53
78 files changed+2827 added−179 removed
This commit is too large to show whole: its files are listed by path, without their changes.
modified:apps/cli/test/surfaces.test.ts+2 added-2 removed
206 unmodified lines207 ])208 );209 });210 211- it("puts ask open and ask flag under ask, and env shape beside env set", () => {212- expect(subcommandsOf(top("ask"))).toStrictEqual(["open", "flag"]);211+ it("puts ask open, ask draft and ask flag under ask, and env shape beside env set", () => {212+ expect(subcommandsOf(top("ask"))).toStrictEqual(["open", "draft", "flag"]);213 expect(subcommandsOf(top("env"))).toStrictEqual(["shape", "set"]);214 });215 216 it("leaves init and env set to their local commands", () => {415 unmodified linesmodified:apps/platform/src/adapters/do-projects.ts+7 added
89 unmodified lines90 answer: (requestId) => on("answer", [requestId]),91 claim: (caller, ask) => assumingMade(on("claim", [caller, ask])),92 credits: (caller, handle) => on("credits", [caller, handle]),93 decide: (caller, input) => assumingMade(on("decide", [caller, input])),94+ draftAsk: (caller, input) => assumingMade(on("draftAsk", [caller, input])),95 events: (since, limit) => on("events", [since, limit]),96 // A name pointing at another project is the service's own97 // `UnknownProject`, so it crosses as the refusal it is.98 evidence: (caller, ref) => on("evidence", [caller, ref]),99 finish: (caller, input) => assumingMade(on("finish", [caller, input])),100 firstPusher: () => on("firstPusher", []),101 flagAsk: (caller, input) => assumingMade(on("flagAsk", [caller, input])),102 fork: (caller) => assumingMade(on("fork", [caller])),103+ forks: () => on("forks", []),104+ head: () => on("head", []),105 heldBackJob: (requestId) => on("heldBackJob", [requestId]),106 initProject: (caller, input) => on("initProject", [caller, input]),107 land: (caller, input) => assumingMade(on("land", [caller, input])),108 landing: (caller, sha) => assumingMade(on("landing", [caller, sha])),109+ landings: (shas) => on("landings", [shas]),110 layerAccess: (caller, layer) => on("layerAccess", [caller, layer]),111 layerFacts: (caller) => on("layerFacts", [caller]),112 ledger: (caller) => assumingMade(on("ledger", [caller])),113 listAsks: (caller) => assumingMade(on("listAsks", [caller])),114 onAlarm: () => on("onAlarm", []),115 openAsk: (caller, input) => assumingMade(on("openAsk", [caller, input])),116+ policy: () => on("policy", []),117 proposeAsk: (caller, input) =>118 assumingMade(on("proposeAsk", [caller, input])),119 recordAdmission: (input) => on("recordAdmission", [input]),120 recordFirstPush: (caller, head) => on("recordFirstPush", [caller, head]),5 unmodified lines126 release: (caller, ask) => assumingMade(on("release", [caller, ask])),127 scanForValues: (input) => on("scanForValues", [input]),128 setEnv: (caller, input) => assumingMade(on("setEnv", [caller, input])),129 showAsk: (caller, ask) => assumingMade(on("showAsk", [caller, ask])),130+ showProposal: (caller, proposal) =>131+ assumingMade(on("showProposal", [caller, proposal])),132 status: (caller) => assumingMade(on("status", [caller])),133 submitAnswer: (caller, input) =>134 assumingMade(on("submitAnswer", [caller, input])),135 today: (caller) => assumingMade(on("today", [caller])),50 unmodified linesmodified:apps/platform/src/adapters/rate-limits.ts+9 added-2 removed
13 unmodified lines14 15 /** How many of each kind one person may make. */16 export interface Limits {17 readonly claim: number;18+ readonly draft: number;19 readonly proposal: number;20 }21 22 /**23 * What `wrangler.jsonc` lets each binding admit per person, every 60 s, in23- * every stage: `CLAIM_LIMIT` and `PROPOSAL_LIMIT`'s `simple.limit`. A binding24+ * every stage: `CLAIM_LIMIT`, `DRAFT_LIMIT` and `PROPOSAL_LIMIT`'s25+ * `simple.limit`. A binding26 * can't say its own limit, so a refusal reads its cap here.27 */26-export const WorkerCaps = { claim: 10, proposal: 5 } as const satisfies Limits;28+export const WorkerCaps = {29+ claim: 10,30+ draft: 2,31+ proposal: 5,32+} as const satisfies Limits;33 34 /** A refusal for one more of `kind` than `limits` allow. */35 const capped = (limits: Limits, kind: Limited) =>36 new CapReached({ cap: limits[kind] });3 unmodified lines40 * defect: a call it could not count is not let through.41 */42 export const WorkerRateLimits = (bindings: {43 readonly claim: RateLimit;44+ readonly draft: RateLimit;45 readonly proposal: RateLimit;46 }): Layer.Layer<RateLimits> =>47 Layer.succeed(48 RateLimits,42 unmodified linesmodified:apps/platform/src/handlers.ts+75 added-2 removed
6 unmodified lines7 * `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.10 * `evidence` asks the project who may read a lane's log, which it reads11- * from the stage's `EvidenceStore`. `watch` is served by `watch.ts`: live11+ * from the stage's `EvidenceStore`. The code reads (`listRefs`, `readTree`,12+ * `listPaths`, `readFile`, `log`, `showCommit`, `why`) run here, over the13+ * Worker's `RepoHost` and the project's canonical repo (`@repo/project/code`),14+ * asking the project only for main's landed commit, its landings and forks. `watch` is served by `watch.ts`: live15 * for a caller on the framed `/rpc`, replayed and ended over JSON.16 *17 * Every `remote` a caller gets back is the platform's git URL for the repo,18 * at the origin the caller reached the platform by: never a storage URL.19 */20+import { RepoHost } from "@repo/artifacts/repo-host";21 import { EvidenceStore, LogRef } from "@repo/checks/evidence-store";22+import {23+ codeProjectOf,24+ commitOf,25+ fileOf,26+ logOf,27+ pathsOf,28+ refsOf,29+ treeOf,30+ whyOf,31+} from "@repo/project/code";32+import type { CodeProject } from "@repo/project/code";33 import { envSchemaMethod } from "@repo/project/deciders";34 import { FrontPage } from "@repo/project/front-page";35 import { GatewayUrl } from "@repo/project/project";36 import type { ProjectApi } from "@repo/project/project";14 unmodified lines51 52 import { RateLimits } from "./rate-limits.ts";53 import { servedFramed, watchHandler } from "./watch.ts";54 55+/** How many commits a page of `log` holds when the caller names no limit. */56+const LOG_PAGE = 30;57+58 /** How many projects a call without one asks at once. */59 const FAN_OUT = 8;60 61 /** The caller, as the `Authenticated` server side named them. */111 unmodified lines173 */174 export const Handlers: Layer.Layer<175 Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>,176 never,159- Projects | FrontPage | RateLimits | EvidenceStore177+ Projects | FrontPage | RateLimits | EvidenceStore | RepoHost178 > = Contracts.toLayer(179 Effect.gen(function* () {180 const projects = yield* Projects;181 const frontPage = yield* FrontPage;182 const rateLimits = yield* RateLimits;183 const evidence = yield* EvidenceStore;184+ const host = yield* RepoHost;185 186 /** `call` on the project named `project`; one never made is `UnknownProject`. */187 const on = <A, E>(188 project: ProjectName,189 call: (api: ProjectApi) => Effect.Effect<A, E>190 ) => Effect.flatMap(projects.get(project), call);191 192+ /** A code read of `project`'s canonical repo, over the Worker's `RepoHost`. */193+ const code = <A, E>(194+ project: ProjectName,195+ read: (of: CodeProject) => Effect.Effect<A, E, RepoHost>196+ ) =>197+ on(project, (api) =>198+ read(codeProjectOf(api, project)).pipe(199+ Effect.provideService(RepoHost, host)200+ )201+ );202+203 /**204 * `call` on every project the projection lists, in name order. A205 * project the platform never made adds nothing, and so does one where206 * `call` finds nothing for the caller; any other failure is the call's.38 unmodified lines245 decide: ({ project, ...input }) =>246 Effect.flatMap(person, (who) =>247 on(project, (api) => api.decide(who, input))248 ),249+ draftAsk: ({ project, ...input }) =>250+ Effect.gen(function* () {251+ const who = yield* person;252+253+ yield* rateLimits.check("draft", who.handle);254+255+ return yield* on(project, (api) => api.draftAsk(who, input));256+ }),257 evidence: ({ project, ref }) =>258 Effect.flatMap(person, (who) =>259 on(project, (api) =>260 api57 unmodified lines318 listAsks: ({ project }) =>319 Effect.flatMap(caller, (who) =>320 on(project, (api) => api.listAsks(who))321 ),322+ listPaths: ({ at, project }) =>323+ code(project, (of) => pathsOf(of, Option.fromUndefinedOr(at))),324 listProjects: () =>325 Effect.map(frontPage.projects(), (listed) => ({ projects: listed })),326+ listRefs: ({ project }) => code(project, refsOf),327+ log: ({ at, from = 0, limit = LOG_PAGE, path, project }) =>328+ code(project, (of) =>329+ logOf(of, {330+ at: Option.fromUndefinedOr(at),331+ from,332+ limit,333+ path: Option.fromUndefinedOr(path),334+ })335+ ),336 openAsk: ({ project, ...input }) =>337 Effect.flatMap(person, (who) =>338 on(project, (api) => api.openAsk(who, input))339 ),340+ projectPolicy: ({ project }) =>341+ on(project, (api) =>342+ Effect.map(api.policy(), (policy) =>343+ Option.match(policy, {344+ onNone: () => ({}),345+ onSome: (evaluated) => ({ policy: evaluated }),346+ })347+ )348+ ),349 proposeAsk: ({ project, ...input }) =>350 Effect.gen(function* () {351 const who = yield* person;352 353 yield* rateLimits.check("proposal", who.handle);354 355 return yield* on(project, (api) => api.proposeAsk(who, input));356 }),357+ readFile: ({ at, path, project }) =>358+ code(project, (of) => fileOf(of, Option.fromUndefinedOr(at), path)),359+ readTree: ({ at, path, project }) =>360+ code(project, (of) =>361+ treeOf(of, Option.fromUndefinedOr(at), Option.fromUndefinedOr(path))362+ ),363 release: ({ ask, project }) =>364 Effect.flatMap(person, (who) =>365 on(project, (api) => api.release(who, ask))366 ),4 unmodified lines371 showAsk: ({ ask, project }) =>372 Effect.flatMap(caller, (who) =>373 on(project, (api) => api.showAsk(who, ask))374 ),375+ showCommit: ({ project, sha }) =>376+ code(project, (of) => commitOf(of, sha)),377+ showProposal: ({ project, proposal }) =>378+ Effect.flatMap(caller, (who) =>379+ on(project, (api) => api.showProposal(who, proposal))380+ ),381 status: ({ project }) =>382 Effect.gen(function* () {383 const who = yield* person;384 47 unmodified lines432 watch: (payload) =>433 Stream.unwrap(434 Effect.map(servedFramed, (live) => watchHandler(payload, { live }))435 ).pipe(Stream.provideService(Projects, projects)),436+ why: ({ at, path, project }) =>437+ code(project, (of) => whyOf(of, Option.fromUndefinedOr(at), path)),438 };439 })440 );added:apps/platform/src/home.ts+21 added
1+/**2+ * The platform's `/`: a page saying what this host serves (clone URLs, MCP,3+ * agent skills, sign-in, the CLI and its releases, the web app), in HTML4+ * for a browser and in Markdown for an agent. A stub until 906 lands: it5+ * answers 501, naming what it read.6+ */7+import type { FrontPage } from "@repo/project/front-page";8+import { Effect } from "effect";9+10+import { HostInfo } from "./host-info.ts";11+12+export const homeResponse = (13+ _request: Request14+): Effect.Effect<Response, never, FrontPage | HostInfo> =>15+ Effect.map(16+ Effect.service(HostInfo),17+ ({ draftModel }) =>18+ new Response(`not built: 906 (draft model ${draftModel})`, {19+ status: 501,20+ })21+ );added:apps/platform/src/host-info.ts+16 added
1+/**2+ * What the platform's `/` says of its host beyond the request: where the3+ * web app lives (`PUBLIC_WEB_URL`, none on a stage without one) and the4+ * model that drafts asks (`DRAFT_MODEL`). `platformOn` provides it from5+ * the decoded env; `surfaces.ts` re-exports it with the other services.6+ */7+import { Context } from "effect";8+import type { Option } from "effect";9+10+export class HostInfo extends Context.Service<11+ HostInfo,12+ {13+ readonly webUrl: Option.Option<string>;14+ readonly draftModel: string;15+ }16+>()("platform/HostInfo") {}modified:apps/platform/src/platform.ts+20 added-3 removed
19 unmodified lines20 import { ReleaseStoreBinding } from "./releases/binding.ts";21 import { Sessions } from "./sessions.ts";22 import { firstOf } from "./sessions/first-of.ts";23 import { sessionTable } from "./sessions/table.ts";24-import { Stage } from "./surfaces.ts";24+import { HostInfo, Stage } from "./surfaces.ts";25 import type { Services } from "./surfaces.ts";26 27 /**28 * A binding the runtime hands the Worker: present, and an object. The36 unmodified lines65 * typed by the generated `Env`, so a binding removed from `wrangler.jsonc`66 * fails `typecheck` here and wherever it is used.67 */68 export const PlatformBindings = Schema.Struct({69+ /** Workers AI, which drafts asks (`DRAFT_MODEL` names the model). */70+ AI: binding<Env["AI"]>("Workers AI"),71 ANSWER: binding<Env["ANSWER"]>("the Answer Workflow"),72 ARTIFACTS: binding<Env["ARTIFACTS"]>("an Artifacts namespace"),73 /**74 * The private namespace that holds every project's layer repos. Only3 unmodified lines78 ARTIFACTS_PRIVATE: binding<Env["ARTIFACTS_PRIVATE"]>(79 "the private Artifacts namespace"80 ),81 CLAIM_LIMIT: binding<Env["CLAIM_LIMIT"]>("a rate limit"),82+ DRAFT_LIMIT: binding<Env["DRAFT_LIMIT"]>("a rate limit"),83 EVIDENCE: binding<Env["EVIDENCE"]>("an R2 bucket"),84 FRONT_PAGE: binding<Env["FRONT_PAGE"]>("a D1 database"),85 LOADER: binding<Env["LOADER"]>("a Worker Loader"),86 OAUTH_KV: binding<Env["OAUTH_KV"]>("a KV namespace"),14 unmodified lines101 });102 103 /** The vars `wrangler.jsonc` sets in every block. */104 export const PlatformVars = Schema.Struct({105+ /** The Workers AI model that drafts asks: `@cf/moonshotai/kimi-k2.7-code`. */106+ DRAFT_MODEL: Schema.NonEmptyString,107 LANDER_ADAPTER: LanderAdapter.pipe(108 Schema.withDecodingDefaultKey(Effect.succeed("container"))109 ),110 OPERATOR_HANDLE: Handle,111+ /** The web app's own URL, which `/` links to; a stage without one links nowhere. */112+ PUBLIC_WEB_URL: Schema.optionalKey(113+ Schema.String.check(Schema.isPattern(/^https?:\/\//u))114+ ),115 STAGE: StageName,116 });117 118 /**118 unmodified lines237 );238 239 /**240 * The surfaces' services over `ports`: every contract's handler, sessions,232- * the CLI's releases (over `RELEASES`) and the stage from the decoded env,241+ * the CLI's releases (over `RELEASES`), the stage and what `/` says of the242+ * host (the web's URL, the drafter's model) from the decoded env,243 * and the ports beside them (git's routes take the same `Projects` and244 * `Upstream` the handlers do). The Worker runs them over245 * `workerPorts(config)`; the core-loop test runs the same composition over246 * its own adapters of the same ports.5 unmodified lines252 Layer.mergeAll(253 Handlers,254 sessionsOf(config),255 ReleaseStoreBinding(config.RELEASES),246- Layer.succeed(Stage, Stage.of({ name: config.STAGE }))256+ Layer.succeed(Stage, Stage.of({ name: config.STAGE })),257+ Layer.succeed(258+ HostInfo,259+ HostInfo.of({260+ draftModel: config.DRAFT_MODEL,261+ webUrl: Option.fromUndefinedOr(config.PUBLIC_WEB_URL),262+ })263+ )264 ).pipe(Layer.provideMerge(ports));265 266 /**267 * The surfaces' services from the decoded env: every contract's handler,8 unmodified linesmodified:apps/platform/src/ports.ts+1 added
122 unmodified lines123 // entry it follows each project's event log instead.124 Layer.succeed(ProjectSockets, Option.some(config.PROJECT)),125 WorkerRateLimits({126 claim: config.CLAIM_LIMIT,127+ draft: config.DRAFT_LIMIT,128 proposal: config.PROPOSAL_LIMIT,129 }),130 EvidenceStoreR2(config.EVIDENCE)131 ).pipe(7 unmodified linesmodified:apps/platform/src/project-calls.ts+6 added
101 unmodified lines102 claim: callOf(MethodSchemas.claim),103 credits: callOf(MethodSchemas.credits),104 [envSchemaMethod]: callOf(MethodSchemas[envSchemaMethod]),105 decide: callOf(MethodSchemas.decide),106+ draftAsk: callOf(MethodSchemas.draftAsk),107 events: callOf(MethodSchemas.events),108 evidence: callOf(MethodSchemas.evidence),109 finish: callOf(MethodSchemas.finish),110 firstPusher: callOf(MethodSchemas.firstPusher),111 flagAsk: callOf(MethodSchemas.flagAsk),112 fork: callOf(MethodSchemas.fork),113+ forks: callOf(MethodSchemas.forks),114+ head: callOf(MethodSchemas.head),115 heldBackJob: callOf(MethodSchemas.heldBackJob),116 initProject: callOf(MethodSchemas.initProject),117 land: callOf(MethodSchemas.land),118 landing: callOf(MethodSchemas.landing),119+ landings: callOf(MethodSchemas.landings),120 layerAccess: callOf(MethodSchemas.layerAccess),121 layerFacts: callOf(MethodSchemas.layerFacts),122 ledger: callOf(MethodSchemas.ledger),123 listAsks: callOf(MethodSchemas.listAsks),124 onAlarm: callOf(MethodSchemas.onAlarm),125 openAsk: callOf(MethodSchemas.openAsk),126+ policy: callOf(MethodSchemas.policy),127 proposeAsk: callOf(MethodSchemas.proposeAsk),128 recordAdmission: callOf(MethodSchemas.recordAdmission),129 recordFirstPush: callOf(MethodSchemas.recordFirstPush),130 recordHeldBack: callOf(MethodSchemas.recordHeldBack),3 unmodified lines134 release: callOf(MethodSchemas.release),135 scanForValues: callOf(MethodSchemas.scanForValues),136 setEnv: callOf(MethodSchemas.setEnv),137 showAsk: callOf(MethodSchemas.showAsk),138+ showProposal: callOf(MethodSchemas.showProposal),139 status: callOf(MethodSchemas.status),140 submitAnswer: callOf(MethodSchemas.submitAnswer),141 today: callOf(MethodSchemas.today),142 verdict: callOf(MethodSchemas.verdict),66 unmodified linesmodified:apps/platform/src/rate-limits.ts+2 added-2 removed
10 unmodified lines11 import type { CapReached } from "@repo/protocol/refusal";12 import { Context } from "effect";13 import type { Effect } from "effect";14 15-/** What a rate limit counts: claims, or proposals (flags among them). */16-export type Limited = "claim" | "proposal";15+/** What a rate limit counts: claims, proposals (flags among them), or drafts. */16+export type Limited = "claim" | "proposal" | "draft";17 18 export class RateLimits extends Context.Service<19 RateLimits,20 {7 unmodified linesadded:apps/platform/src/raw.ts+17 added
1+/**2+ * A project's raw bytes: `GET /<project>/raw/<rev>/<path…>`, from its3+ * canonical repo only, under a sandboxing CSP and `nosniff` so no file runs4+ * as script on this origin. A stub until 903 lands: it answers 501.5+ * `rest` is everything after `raw/`, undecoded: the revision and the path.6+ */7+import type { RepoHost } from "@repo/artifacts/repo-host";8+import type { Projects } from "@repo/project/projects";9+import type { ProjectName } from "@repo/protocol/ids";10+import { Effect } from "effect";11+12+export const rawResponse = (13+ _request: Request,14+ _project: ProjectName,15+ _rest: string16+): Effect.Effect<Response, never, RepoHost | Projects> =>17+ Effect.succeed(new Response("not built: 903", { status: 501 }));modified:apps/platform/src/repo-names.ts+9 added-84 removed
1 /**2- * What a repo's name says it is: a project's canonical repo3- * `<project>`, a claim's fork `<project>--<ask>--<handle>`, or a person's4- * working fork `<project>--me--<handle>`, each handle in lowercase. `--`5- * occurs in no project or ask name, so a name splits back into its parts.6- * Pure: the gateway, the handlers and OnPush read names7- * with it.2+ * What a repo's name says it is, from `@repo/project/repo-names`, where3+ * the project service lists its forks by it too: the gateway, the handlers4+ * and OnPush read names from here.5 */9-import { forkName } from "@repo/project/claim";10-import { AskId, Handle, ProjectName, RepoName } from "@repo/protocol/ids";11-import { Data, Option, Schema } from "effect";12-13-/** What a repo is, read from its name alone. */14-export type RepoKind =15- | { readonly _tag: "Canonical"; readonly project: ProjectName }16- | {17- readonly _tag: "ClaimFork";18- readonly project: ProjectName;19- readonly ask: AskId;20- /** As the name spells it: in lowercase. */21- readonly handle: Handle;22- }23- | {24- readonly _tag: "WorkingFork";25- readonly project: ProjectName;26- /** As the name spells it: in lowercase. */27- readonly handle: Handle;28- }29- | { readonly _tag: "Unknown" };30-31-export const RepoKind = Data.taggedEnum<RepoKind>();32-33-const asProject = Schema.decodeOption(ProjectName);34-35-const asAsk = Schema.decodeOption(AskId);36-37-const asHandle = Schema.decodeOption(Handle);38-39-/** The word that names a working fork where a claim's fork names its ask. */40-const WORKING = "me";41-42-/** What `name` says it is; `Unknown` for any name the platform never makes. */43-export const repoKind = (name: RepoName): RepoKind => {44- const [first = "", second, third, ...rest] = name.split("--");45-46- const kind = Option.flatMap(47- asProject(first),48- (project): Option.Option<RepoKind> => {49- if (second === undefined) {50- return Option.some(RepoKind.Canonical({ project }));51- }52-53- if (third === undefined || rest.length > 0) {54- return Option.none();55- }56-57- const handle = Option.filter(58- asHandle(third),59- (spelled) => spelled === spelled.toLowerCase()60- );61-62- return second === WORKING63- ? Option.map(handle, (owner) =>64- RepoKind.WorkingFork({ handle: owner, project })65- )66- : Option.map(67- Option.all({ ask: asAsk(second), handle }),68- ({ ask, handle: claimant }) =>69- RepoKind.ClaimFork({ ask, handle: claimant, project })70- );71- }72- );73-74- return Option.getOrElse(kind, () => RepoKind.Unknown());75-};76-77-/** A claim's fork: `<project>--<ask>--<handle in lowercase>`. */78-export const claimForkName: (79- project: ProjectName,80- ask: AskId,81- handle: Handle82-) => RepoName = forkName;83-84-/** A person's working fork: `<project>--me--<handle in lowercase>`. */85-export const workingForkName = (project: ProjectName, handle: Handle) =>86- RepoName.make(`${project}--${WORKING}--${handle.toLowerCase()}`);6+export {7+ claimForkName,8+ repoKind,9+ RepoKind,10+ workingForkName,11+} from "@repo/project/repo-names";modified:apps/platform/src/surfaces.ts+81 added-7 removed
1 import { commandDocs } from "@repo/agent-kit/command-doc";2 import { platformSkill } from "@repo/agent-kit/platform";3-import type { RepoHost } from "@repo/artifacts/repo-host";3+import { RepoHost } from "@repo/artifacts/repo-host";4 import { Brand } from "@repo/brand";5 import { Upstream } from "@repo/git/upstream";6-import type { FrontPage } from "@repo/project/front-page";6+import { FrontPage } from "@repo/project/front-page";7 import { Projects } from "@repo/project/projects";8 import { authenticated, bearerToken } from "@repo/protocol/authenticate";9 import { Client, Contracts, surfaced } from "@repo/protocol/contracts";10+import { ProjectName } from "@repo/protocol/ids";11 import { toToolkit } from "@repo/protocol/mcp";12 import {13 briefResources,14 skillIn,15 skillPrompt,16 } from "@repo/protocol/mcp-extras";17 import { Authenticated } from "@repo/protocol/principal";18 import type { Person } from "@repo/protocol/principal";18-import { Context, Effect, Layer, Option } from "effect";19+import { Context, Effect, Layer, Option, Schema } from "effect";20 import { McpProtocol, McpServer } from "effect/ai";21 import {22 Headers,23 HttpRouter,9 unmodified lines33 } from "effect/rpc";34 35 import { serveGit } from "./git.ts";36 import type { GitServices } from "./git.ts";37+import { homeResponse } from "./home.ts";38+import { HostInfo } from "./host-info.ts";39 import { LayerGate } from "./layer-gate.ts";40+import { rawResponse } from "./raw.ts";41 import { releaseRoutes } from "./releases.ts";42 import type { ReleaseStore } from "./releases.ts";43 import { Sessions } from "./sessions.ts";44 import { isFramed } from "./watch.ts";45 import { agentSkillRoutes } from "./well-known.ts";46 47+/** What `/` says of the host: the web app's URL and the drafter's model. */48+export { HostInfo } from "./host-info.ts";49+50 /** Which stage this Worker serves: `/health` says so. */51 export class Stage extends Context.Service<Stage, { readonly name: string }>()(52 "platform/Stage"53 ) {}54 55 /**56 * What the surfaces need from the platform: the contracts' handlers,57 * sessions, what git's paths need, the CLI's releases, the front page and51- * the repos the projects' skills are read from, and the stage.58+ * the repos the projects' skills and raw files are read from, the stage,59+ * and what `/` says of the host.60 */61 export type Services =62 | Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>63 | Sessions64 | GitServices65 | ReleaseStore66 | FrontPage67 | RepoHost60- | Stage;68+ | Stage69+ | HostInfo;70 71 /** git's smart-HTTP paths: `/<repo>(.git)/info/refs` and the two services. */72 const GIT_PATH =73 /^\/[A-Za-z0-9._-]+\/(?:info\/refs|git-upload-pack|git-receive-pack)$/u;11 unmodified lines85 */86 const SIGN_IN_PATH = /^\/(?:authorize|signup|token|oauth(?:\/.*)?)$/u;87 88 /**89+ * A project's raw files, `/<project>/raw/<rev>/<path…>`: no git path, whose90+ * second segment is `info` or a git service, ever matches it.91+ */92+const RAW_PATH = /^\/[a-z0-9]+(?:-[a-z0-9]+)*\/raw\/.+$/u;93+94+/**95 * The CLI's install script and releases (`releases.ts`):96 * `/install.sh`, `/releases/manifest.json` and `/releases/:version/:asset`.97 */98 const RELEASE_PATH =10 unmodified lines109 * 401: `/health`; git's, whose gateway decides who may read and push (and110 * answers an unknown credential with its own 401); the paths that tell a111 * client how to sign in, or sign it in, which may carry a stale token or an112 * OAuth client's own credential; the CLI's downloads, which anyone may98- * fetch, with whatever credential an installer happens to carry; and the99- * projects' skills, which an agent fetches the same way.113+ * fetch, with whatever credential an installer happens to carry; the114+ * projects' skills, which an agent fetches the same way; the host's own115+ * page, `/`; and a project's raw files, which a README's images name.116 */117 const isExempt = (path: string) =>118+ path === "/" ||119 path === "/health" ||120+ RAW_PATH.test(path) ||121 GIT_PATH.test(path) ||122 DISCOVERY_PATH.test(path) ||123 SIGN_IN_PATH.test(path) ||124 RELEASE_PATH.test(path) ||230 unmodified lines355 );356 })357 );358 359+/** A route that answers with a web `Response` from `respond`, given the web request. */360+const fromWeb =361+ <R>(respond: (web: Request) => Effect.Effect<Response, never, R>) =>362+ (request: HttpServerRequest.HttpServerRequest) =>363+ HttpServerRequest.toWeb(request).pipe(364+ Effect.flatMap(respond),365+ Effect.map(HttpServerResponse.fromWeb),366+ Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 400 }))367+ );368+369+/** `/`: what this host serves, for a browser and for an agent (`home.ts`). */370+const home = HttpRouter.use((router) =>371+ Effect.gen(function* () {372+ const services = Context.make(FrontPage, yield* FrontPage).pipe(373+ Context.add(HostInfo, yield* HostInfo)374+ );375+376+ yield* router.add(377+ "GET",378+ "/",379+ fromWeb((web) => Effect.provide(homeResponse(web), services))380+ );381+ })382+);383+384+const decodeProject = Schema.decodeUnknownOption(ProjectName);385+386+/** `/<project>/raw/<rev>/<path…>`: a project's raw files (`raw.ts`). */387+const raw = HttpRouter.use((router) =>388+ Effect.gen(function* () {389+ const services = Context.make(RepoHost, yield* RepoHost).pipe(390+ Context.add(Projects, yield* Projects)391+ );392+393+ yield* router.add("GET", "/:project/raw/*", (request) =>394+ Effect.gen(function* () {395+ const params = yield* HttpRouter.params;396+397+ return yield* Option.match(decodeProject(params.project), {398+ onNone: () =>399+ Effect.succeed(HttpServerResponse.empty({ status: 404 })),400+ onSome: (project) =>401+ fromWeb((web) =>402+ Effect.provide(403+ rawResponse(web, project, params["*"] ?? ""),404+ services405+ )406+ )(request),407+ });408+ })409+ );410+ })411+);412+413 /**414 * The protected-resource document (RFC 9728), answered to anyone: where a415 * client learns that the platform is its own authorization server. The416 * authorization server's document is the sign-in provider's, which answers51 unmodified lines468 /** The platform's fetch handler over `services`. */469 export const serve = <E>(services: Layer.Layer<Services, E>) =>470 HttpRouter.toWebHandler(471 Layer.mergeAll(472+ home,473 health,474 discovery,475+ raw,476 git,477 mcp,478 rpc,479 releaseRoutes,5 unmodified linesmodified:apps/platform/test/bindings.test.ts+81 added
116 unmodified lines117 * A key that is neither here nor in `NOT_BINDINGS` fails the test: whoever118 * adds it says which it is.119 */120 const BindingKinds = Schema.Struct({121+ ai: Schema.optionalKey(Schema.Struct({ binding: Schema.String })),122 artifacts: Schema.optionalKey(Bound),123 d1_databases: Schema.optionalKey(Bound),124 durable_objects: Schema.optionalKey(Schema.Struct({ bindings: Named })),125 kv_namespaces: Schema.optionalKey(Bound),53 unmodified lines179 /** What one block declares: its bindings, vars and required secrets, each sorted, and any key this test does not know. */180 const declaredIn = (raw: typeof Raw.Type) =>181 Effect.map(decodeBlock(raw), (block) => ({182 bindings: sorted([183+ ...(block.ai === undefined ? [] : [block.ai.binding]),184 ...(block.artifacts ?? []).map(({ binding }) => binding),185 ...(block.d1_databases ?? []).map(({ binding }) => binding),186 ...(block.durable_objects?.bindings ?? []).map(({ name }) => name),187 ...(block.kv_namespaces ?? []).map(({ binding }) => binding),63 unmodified lines251 ].flatMap(({ groups }) => (groups?.key === undefined ? [] : [groups.key]))252 )253 );254 255+/** The draft limit as a stage's block declares it, under its own namespace id. */256+const draftLimit = (id: string) => ({257+ name: "DRAFT_LIMIT",258+ namespace_id: id,259+ simple: { limit: 2, period: 60 },260+});261+262 describe("a wrangler.jsonc, read as data", () => {263 it.effect(264 "loses its comments and trailing commas, a comment between a comma and its bracket too, and keeps every string whole",265 () =>40 unmodified lines306 });307 }).pipe(Effect.provide(NodeServices.layer))308 );309 310+ // The drafter's model and the web's address are stage vars, and drafts311+ // are rate-limited apart from proposals, two a minute per person.312+ it.effect(313+ "set the drafter's model, the web's address and the draft limit in every stage",314+ () =>315+ Effect.gen(function* () {316+ const raw = yield* Effect.flatMap(317+ fileText("wrangler.jsonc"),318+ readJsonc319+ );320+321+ const { env = {} } = yield* Schema.decodeUnknownEffect(Staged)(raw);322+323+ const DraftBlock = Schema.Struct({324+ ai: Schema.Struct({ binding: Schema.String }),325+ ratelimits: Schema.Array(326+ Schema.Struct({327+ name: Schema.String,328+ namespace_id: Schema.String,329+ simple: Schema.Struct({330+ limit: Schema.Int,331+ period: Schema.Int,332+ }),333+ })334+ ),335+ vars: PlatformVars,336+ });337+338+ const read = (block: typeof Raw.Type | undefined) =>339+ Effect.map(340+ Schema.decodeUnknownEffect(DraftBlock)(block),341+ ({ ai, ratelimits, vars }) => ({342+ ai: ai.binding,343+ draftLimit: ratelimits.find(({ name }) => name === "DRAFT_LIMIT"),344+ model: vars.DRAFT_MODEL,345+ web: vars.PUBLIC_WEB_URL,346+ })347+ );348+349+ const model = "@cf/moonshotai/kimi-k2.7-code";350+351+ expect({352+ demo: yield* read(env.demo),353+ "dev-oscabriel": yield* read(env["dev-oscabriel"]),354+ top: yield* read(raw),355+ }).toStrictEqual({356+ demo: {357+ ai: "AI",358+ draftLimit: draftLimit("1204"),359+ model,360+ web: "https://web-demo.oscargabriel.workers.dev",361+ },362+ "dev-oscabriel": {363+ ai: "AI",364+ draftLimit: draftLimit("1104"),365+ model,366+ web: "https://web-dev-oscabriel.oscargabriel.workers.dev",367+ },368+ top: {369+ ai: "AI",370+ draftLimit: draftLimit("1004"),371+ model,372+ web: "http://localhost:5173",373+ },374+ });375+ }).pipe(Effect.provide(NodeServices.layer))376+ );377+378 it("are all the Env the Worker is given, and nothing else", () => {379 expectTypeOf<keyof Env>().toEqualTypeOf<380 Exclude<381 keyof PlatformConfig,30 unmodified lines412 >();413 expectTypeOf<Env["PROPOSAL_LIMIT"]>().toExtend<414 Parameters<typeof WorkerRateLimits>[0]["proposal"]415 >();416+ expectTypeOf<Env["DRAFT_LIMIT"]>().toExtend<417+ Parameters<typeof WorkerRateLimits>[0]["draft"]418+ >();419+ expectTypeOf<PlatformConfig["AI"]>().toEqualTypeOf<Env["AI"]>();420 expectTypeOf<Env["FRONT_PAGE"]>().toExtend<421 Parameters<typeof D1Client.layer>[0]["db"]422 >();423 expectTypeOf<Env["OAUTH_KV"]>().toExtend<47 unmodified linesmodified:apps/platform/test/do-projects.test.ts+20 added-2 removed
10 unmodified lines11 EnvKey,12 LandedSha,13 LayerName,14 ProjectName,15+ ProposalId,16 RequestId,17 } from "@repo/protocol/ids";18 import { ProjectExists, UnknownProject } from "@repo/protocol/refusal";19 import { advanceTo } from "@repo/testkit/clock";64 unmodified lines84 choice: "accept",85 decision: DecisionId.make("dec-none0001"),86 })87 ),88+ draftAsk: settled(89+ "draftAsk",90+ api.draftAsk(carol, { proposal: ProposalId.make("prop-000001") })91+ ),92 [envSchemaMethod]: settled(envSchemaMethod, api[envSchemaMethod](anyone)),93 events: settled("events", api.events(0, 100)),94 evidence: settled(95 "evidence",8 unmodified lines104 "flagAsk",105 api.flagAsk(bob, { ask: parseIso, reason: "It names no format." })106 ),107 fork: settled("fork", api.fork(carol)),108+ forks: settled("forks", api.forks()),109+ head: settled("head", api.head()),110 heldBackJob: settled("heldBackJob", api.heldBackJob(requestId)),111 initProject: settled("initProject", api.initProject(alice, {})),112 land: settled(113 "land",114 api.land(bob, { base: sha, head: sha, message: "Tidy", requestId })115 ),116 landing: settled("landing", api.landing(anyone, sha)),117+ landings: settled("landings", api.landings([sha])),118 layerAccess: settled("layerAccess", api.layerAccess(alice, layer)),119 layerFacts: settled("layerFacts", api.layerFacts(bob)),120 ledger: settled("ledger", api.ledger(anyone)),121 listAsks: settled("listAsks", api.listAsks(anyone)),1 unmodified line123 openAsk: settled(124 "openAsk",125 api.openAsk(bob, { ask: parseIso, files: askFiles() })126 ),127+ policy: settled("policy", api.policy()),128 proposeAsk: settled(129 "proposeAsk",130 api.proposeAsk(carol, { want: "Parse ISO week dates." })131 ),37 unmodified lines169 value: Redacted.make("a-value-long-enough-0123"),170 })171 ),172 showAsk: settled("showAsk", api.showAsk(anyone, parseIso)),173+ showProposal: settled(174+ "showProposal",175+ api.showProposal(anyone, ProposalId.make("prop-000001"))176+ ),177 status: settled("status", api.status(bob)),178 submitAnswer: settled(179 "submitAnswer",180 api.submitAnswer(bob, { ask: parseIso, base: sha, head: sha, requestId })75 unmodified lines256 expect(Object.keys(throughDo.each).toSorted()).toStrictEqual(257 projectMethods.toSorted()258 );259 expect(throughDo).toStrictEqual(inProcess);247- // Only a step reported for an answer request that never was dies.248- expect(died).toStrictEqual(["advanceAnswer"]);260+ // Only a step reported for an answer request that never was dies,261+ // and the drafting stubs, until 909 builds them.262+ expect(died).toStrictEqual([263+ "advanceAnswer",264+ "draftAsk",265+ "showProposal",266+ ]);267 })268 );269 });modified:apps/platform/test/fake-env.ts+4 added
148 unmodified lines149 * one with `UnknownProject`, each noted (`callsTo`). The optional secrets150 * are absent.151 */152 export const fakeEnv = (): Env => ({153+ AI: untouchable("AI"),154 ANSWER: untouchable("ANSWER"),155 ARTIFACTS: untouchable("ARTIFACTS"),156 ARTIFACTS_PRIVATE: untouchable("ARTIFACTS_PRIVATE"),157 CLAIM_LIMIT: untouchable("CLAIM_LIMIT"),158 COOKIE_KEY: cookieKey,159+ DRAFT_LIMIT: untouchable("DRAFT_LIMIT"),160+ DRAFT_MODEL: "@cf/moonshotai/kimi-k2.7-code",161 EVIDENCE: untouchable("EVIDENCE"),162 FRONT_PAGE: untouchable("FRONT_PAGE"),163 LANDER_ADAPTER: "container",164 LOADER: untouchable("LOADER"),4 unmodified lines169 OPERATOR_TOKEN: operatorToken,170 PASSWORD_PEPPER: passwordPepper,171 PROJECT: fakeProjects(),172 PROPOSAL_LIMIT: untouchable("PROPOSAL_LIMIT"),173+ PUBLIC_WEB_URL: "http://localhost:5173",174 RELEASES: untouchable("RELEASES"),175 SANDBOX: untouchable("SANDBOX"),176 SIGN_IN_LIMIT: untouchable("SIGN_IN_LIMIT"),177 STAGE: "local",21 unmodified linesmodified:apps/platform/test/handlers.fixtures.ts+10 added-2 removed
134 unmodified lines135 export interface WorldOptions {136 /** What the front page reads back; nothing by default. */137 readonly frontPage?: FrontPageSeed;138 /** Claims and proposals each person may make; 100 of each by default. */139- readonly limits?: { readonly claim: number; readonly proposal: number };139+ readonly limits?: {140+ readonly claim: number;141+ readonly draft?: number;142+ readonly proposal: number;143+ };144 }145 146 const noFrontPage: FrontPageSeed = { credits: [], entries: [], projects: [] };147 16 unmodified lines164 ).pipe(Layer.provideMerge(LanderIsogit), Layer.provideMerge(allRed))165 )166 ),167 FrontPageMemory.layer(options.frontPage ?? noFrontPage),164- MemoryRateLimits(options.limits ?? { claim: 100, proposal: 100 }),168+ MemoryRateLimits({169+ claim: options.limits?.claim ?? 100,170+ draft: options.limits?.draft ?? 100,171+ proposal: options.limits?.proposal ?? 100,172+ }),173 EvidenceStoreMemory174 ).pipe(Layer.provideMerge(RepoHostMemory));175 176 /**33 unmodified linesmodified:apps/platform/test/handlers.test.ts+11 added-2 removed
825 unmodified lines826 };827 828 describe("the Worker's rate limits", () => {829 it.effect(830- "count claims and proposals apart, per person whatever the case of their handle",830+ "count claims, proposals and drafts apart, per person whatever the case of their handle",831 () =>832 Effect.gen(function* () {833 const claims = fakeLimit(2);834 const proposals = fakeLimit(1);835+ const drafts = fakeLimit(1);836 837 const spent = yield* RateLimits.use(({ check }) =>838 Effect.all([839 Effect.result(check("claim", Handle.make("Alice"))),1 unmodified line841 Effect.result(check("claim", Handle.make("alice"))),842 Effect.result(check("claim", Handle.make("bob"))),843 Effect.result(check("proposal", Handle.make("alice"))),844 Effect.result(check("proposal", Handle.make("alice"))),845+ Effect.result(check("draft", Handle.make("alice"))),846+ Effect.result(check("draft", Handle.make("Alice"))),847 ])848 ).pipe(849 Effect.provide(850 WorkerRateLimits({851 claim: claims.binding,852+ draft: drafts.binding,853 proposal: proposals.binding,854 })855 )856 );4 unmodified lines861 Result.fail(new CapReached({ cap: WorkerCaps.claim })),862 Result.void,863 Result.void,864 Result.fail(new CapReached({ cap: WorkerCaps.proposal })),865+ Result.void,866+ Result.fail(new CapReached({ cap: WorkerCaps.draft })),867 ]);868 expect(claims.keys).toStrictEqual(["alice", "alice", "alice", "bob"]);869 expect(proposals.keys).toStrictEqual(["alice", "alice"]);870+ expect(drafts.keys).toStrictEqual(["alice", "alice"]);871 })872 );873 874 it.effect("die when the binding fails, rather than let a call through", () =>5 unmodified lines880 const spent = yield* Effect.exit(881 RateLimits.use(({ check }) =>882 check("claim", Handle.make("alice"))883 ).pipe(877- Effect.provide(WorkerRateLimits({ claim: broken, proposal: broken }))884+ Effect.provide(885+ WorkerRateLimits({ claim: broken, draft: broken, proposal: broken })886+ )887 )888 );889 890 expect(Exit.hasDies(spent)).toBeTruthy();36 unmodified linesmodified:apps/platform/test/harness.ts+19 added-7 removed
5 unmodified lines6 import { Projects } from "@repo/project/projects";7 import { Contracts } from "@repo/protocol/contracts";8 import { UnknownProject } from "@repo/protocol/refusal";9 import { untouchable } from "@repo/testkit/untouchable";10-import { Effect, Layer, Schema } from "effect";10+import { Effect, Layer, Option, Schema } from "effect";11 import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";12 import { RpcClient, RpcSerialization } from "effect/rpc";13 14 import { MemoryRateLimits, WorkerCaps } from "../src/adapters/rate-limits.ts";15 import { Handlers } from "../src/handlers.ts";16 import { ReleaseStore } from "../src/releases.ts";17-import { serve, Stage } from "../src/surfaces.ts";17+import { HostInfo, serve, Stage } from "../src/surfaces.ts";18 import type { Services } from "../src/surfaces.ts";19 20 /** Where every test request goes: the platform as `served` answers it. */21 export const origin = "http://localhost";112 unmodified lines134 /**135 * What a surfaces test may leave out: git's ports and the release store,136 * unused (no test here pushes, and only the releases test downloads), a137 * front page that lists no project and the repos behind it, unused (so the138- * skills index is empty), and the stage, `local`.138+ * skills index is empty), the stage, `local`, and a host with no web app139+ * whose drafter is `test-model`.140 */141 const defaults = Layer.mergeAll(142 Layer.succeed(143 Projects,2 unmodified lines146 Layer.succeed(Upstream, Upstream.of({ exchange: unused("Upstream") })),147 Layer.succeed(ReleaseStore, ReleaseStore.of({ get: unused("ReleaseStore") })),148 FrontPageMemory.layer({ credits: [], entries: [], projects: [] }),149 Layer.succeed(RepoHost, untouchable<RepoHost["Service"]>("RepoHost")),149- Layer.succeed(Stage, Stage.of({ name: "local" }))150+ Layer.succeed(Stage, Stage.of({ name: "local" })),151+ Layer.succeed(152+ HostInfo,153+ HostInfo.of({ draftModel: "test-model", webUrl: Option.none() })154+ )155 );156 157 /**158 * The contracts before any project exists, served by the platform's own159 * handlers: a call that names a project finds none (`UnknownProject`), the155- * front page lists nothing, nobody is near a rate limit, and no lane has156- * left a log.160+ * front page lists nothing, nobody is near a rate limit, no lane has161+ * left a log, and no repo is read.162 */163 export const noProjects = Handlers.pipe(164 Layer.provide([165 Layer.succeed(5 unmodified lines171 ),172 FrontPageMemory.layer({ credits: [], entries: [], projects: [] }),173 MemoryRateLimits(WorkerCaps),174 EvidenceStoreMemory,175+ Layer.succeed(RepoHost, untouchable<RepoHost["Service"]>("RepoHost")),176 ])177 );178 179 /**3 unmodified lines183 export const served = Effect.fnUntraced(function* <E>(184 services: Layer.Layer<185 Exclude<186 Services,181- Projects | ReleaseStore | Upstream | FrontPage | RepoHost | Stage187+ | Projects188+ | ReleaseStore189+ | Upstream190+ | FrontPage191+ | RepoHost192+ | Stage193+ | HostInfo194 >,195 E196 >197 ) {39 unmodified linesmodified:apps/platform/test/mcp.test.ts+13 added
22 unmodified lines23 DecisionId,24 Handle,25 LaneName,26 ProjectName,27+ ProposalId,28 RepoPath,29 RequestId,30 } from "@repo/protocol/ids";31 import { CurrentPrincipal, Principal } from "@repo/protocol/principal";367 unmodified lines399 [EnvSchemaOf._tag]: {400 args: { project: nowhere },401 refusal: new UnknownProject({ project: nowhere }),402 },403+ draftAsk: {404+ args: { project: nowhere, proposal: ProposalId.make("prop-000001") },405+ refusal: new UnknownProject({ project: nowhere }),406+ },407 finish: {408 args: { ask: fixWeek, base, head, project, requestId },409 refusal: new NotDecider({}),410 },28 unmodified lines439 openAsk: {440 args: { ask: nope, files: askFiles, project },441 refusal: new NotDecider({}),442 },443+ projectPolicy: {444+ args: { project: nowhere },445+ refusal: new UnknownProject({ project: nowhere }),446+ },447 proposeAsk: {448 args: { project: nowhere, want },449 refusal: new UnknownProject({ project: nowhere }),450 },4 unmodified lines455 showAsk: {456 args: { ask: nope, project },457 refusal: new UnknownAsk({ ask: nope }),458 },459+ showProposal: {460+ args: { project: nowhere, proposal: ProposalId.make("prop-000001") },461+ refusal: new UnknownProject({ project: nowhere }),462+ },463 status: {464 args: { project: nowhere },465 refusal: new UnknownProject({ project: nowhere }),466 },401 unmodified linesadded:apps/platform/test/w9-contracts.test.ts+156 added
1+/**2+ * The code browser's, the people page's and drafting's contracts and3+ * routes, wired end to end through the platform's fetch4+ * handler before their bodies exist: the policy read answers, each code5+ * read reaches the façade (which names the issue that builds it), a draft6+ * needs a person, and `/` and a project's raw files have their slots, open7+ * to a stale credential as every public path is.8+ */9+import { describe, expect, it } from "@effect/vitest";10+import { ProposalId } from "@repo/protocol/ids";11+import { Unauthenticated } from "@repo/protocol/principal";12+import { advanceTo } from "@repo/testkit/clock";13+import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";14+import { Cause, Effect, Exit, Layer, Option } from "effect";15+16+import { Handlers } from "../src/handlers.ts";17+import { MemorySessions } from "../src/sessions/memory.ts";18+import { seeded, worldOf } from "./handlers.fixtures.ts";19+import { origin, rpcClient, served } from "./harness.ts";20+21+const datekit = aProject({ people: ["bob"] }).pipe(22+ withVouches(["bob"]),23+ withAsk({ id: "parse-iso", territory: "packages/parser" })24+);25+26+const { project } = datekit;27+28+const sessions = MemorySessions.layer({});29+30+/** The platform over datekit's world, seeded: made, pushed to, its ask open. */31+const platform = Effect.gen(function* () {32+ yield* advanceTo("2026-10-07T12:00:00Z");33+34+ const world = yield* Layer.build(worldOf([datekit]));35+36+ yield* seeded(datekit).pipe(Effect.provide(world));37+38+ const ports = Layer.succeedContext(world);39+40+ return yield* served(41+ Layer.mergeAll(Handlers.pipe(Layer.provide(ports)), ports, sessions)42+ );43+});44+45+/** What a call died with, as text; none when it did not die. */46+const diedWith = <A, E>(call: Effect.Effect<A, E>) =>47+ Effect.map(Effect.exit(call), (exit) =>48+ Exit.isFailure(exit) && Cause.hasDies(exit.cause)49+ ? Option.some(String(Cause.squash(exit.cause)))50+ : Option.none()51+ );52+53+describe("the code, policy and drafting contracts over /rpc", () => {54+ it.effect("give anyone a project's policy, without its layers", () =>55+ Effect.gen(function* () {56+ const { handler } = yield* platform;57+ const anyone = yield* rpcClient(handler);58+59+ const { policy } = yield* anyone.projectPolicy({ project });60+61+ expect(policy?.source).toBe("config");62+ expect(policy?.deciders).toStrictEqual(datekit.policy.deciders);63+ expect(Object.keys(policy ?? {})).not.toContain("visibility");64+ expect(Object.keys(policy ?? {})).not.toContain("asks");65+ })66+ );67+68+ it.effect("reach the code façade, which names the issue that builds it", () =>69+ Effect.gen(function* () {70+ const { handler } = yield* platform;71+ const anyone = yield* rpcClient(handler);72+73+ expect(yield* diedWith(anyone.listRefs({ project }))).toStrictEqual(74+ Option.some("not built: 903")75+ );76+ expect(yield* diedWith(anyone.readTree({ project }))).toStrictEqual(77+ Option.some("not built: 903")78+ );79+ })80+ );81+82+ it.effect("refuse a draft to anyone not signed in", () =>83+ Effect.gen(function* () {84+ const { handler } = yield* platform;85+ const anyone = yield* rpcClient(handler);86+87+ expect(88+ yield* Effect.exit(89+ anyone.draftAsk({90+ project,91+ proposal: ProposalId.make("prop-000001"),92+ })93+ )94+ ).toStrictEqual(Exit.fail(new Unauthenticated()));95+ })96+ );97+});98+99+describe("the host page and raw files routes", () => {100+ it.effect(101+ "answer / and a project's raw files from their slots, a stale bearer or not",102+ () =>103+ Effect.gen(function* () {104+ const { fetch } = yield* platform;105+106+ const stale = {107+ authorization: "Bearer not-a-token-the-platform-knows",108+ };109+110+ const read = (path: string, headers: Record<string, string> = {}) =>111+ Effect.flatMap(112+ fetch(new Request(`${origin}${path}`, { headers })),113+ (response) =>114+ Effect.map(115+ Effect.promise(() => response.text()),116+ (text) => ({ status: response.status, text })117+ )118+ );119+120+ const raw = `/${project}/raw/${"4".repeat(40)}/README.md`;121+122+ expect({123+ home: yield* read("/"),124+ homeStale: yield* read("/", stale),125+ raw: yield* read(raw),126+ rawStale: yield* read(raw, stale),127+ }).toStrictEqual({128+ home: {129+ status: 501,130+ text: "not built: 906 (draft model test-model)",131+ },132+ homeStale: {133+ status: 501,134+ text: "not built: 906 (draft model test-model)",135+ },136+ raw: { status: 501, text: "not built: 903" },137+ rawStale: { status: 501, text: "not built: 903" },138+ });139+ })140+ );141+142+ it.effect("leaves git's own paths to git, beside the raw route", () =>143+ Effect.gen(function* () {144+ const { fetch } = yield* platform;145+146+ const response = yield* fetch(147+ new Request(`${origin}/${project}/raw/info/refs`)148+ );149+150+ expect(response.status).toBe(501);151+ expect(yield* Effect.promise(() => response.text())).toBe(152+ "not built: 903"153+ );154+ })155+ );156+});modified:apps/platform/package.json+1 added
13 unmodified lines14 "@repo/agent-kit": "workspace:*",15 "@repo/artifacts": "workspace:*",16 "@repo/brand": "workspace:*",17 "@repo/checks": "workspace:*",18+ "@repo/drafting": "workspace:*",19 "@repo/gate": "workspace:*",20 "@repo/git": "workspace:*",21 "@repo/project": "workspace:*",22 "@repo/protocol": "workspace:*",17 unmodified linesmodified:apps/platform/worker-configuration.d.ts+14 added-2 removed
1 /* eslint-disable */2-// Generated by Wrangler by running `wrangler types --include-runtime=false --strict-vars=false` (hash: 8c12fe014598b33e00210997684fcc6b)2+// Generated by Wrangler by running `wrangler types --include-runtime=false --strict-vars=false` (hash: 850febac061bf22321125e7870cc2f45)3 interface __BaseEnv_Env {4 OAUTH_KV: KVNamespace;5 EVIDENCE: R2Bucket;6 RELEASES: R2Bucket;2 unmodified lines9 ARTIFACTS_PRIVATE: Artifacts;10 CLAIM_LIMIT: RateLimit;11 PROPOSAL_LIMIT: RateLimit;12 SIGN_IN_LIMIT: RateLimit;13+ DRAFT_LIMIT: RateLimit;14 LOADER: WorkerLoader;15+ AI: Ai;16 OPERATOR_HANDLE: string;17 STAGE: string;18 LANDER_ADAPTER: string;19+ DRAFT_MODEL: string;20+ PUBLIC_WEB_URL: string;21 OPERATOR_TOKEN: string;22 COOKIE_KEY: string;23 PASSWORD_PEPPER: string;24 MASTER_KEY: string;16 unmodified lines41 ARTIFACTS_PRIVATE: Artifacts;42 CLAIM_LIMIT: RateLimit;43 PROPOSAL_LIMIT: RateLimit;44 SIGN_IN_LIMIT: RateLimit;45+ DRAFT_LIMIT: RateLimit;46 LOADER: WorkerLoader;47+ AI: Ai;48 OPERATOR_HANDLE: string;49 STAGE: string;50 LANDER_ADAPTER: string;51+ DRAFT_MODEL: string;52+ PUBLIC_WEB_URL: string;53 OPERATOR_TOKEN: string;54 COOKIE_KEY: string;55 PASSWORD_PEPPER: string;56 MASTER_KEY: string;11 unmodified lines68 ARTIFACTS_PRIVATE: Artifacts;69 CLAIM_LIMIT: RateLimit;70 PROPOSAL_LIMIT: RateLimit;71 SIGN_IN_LIMIT: RateLimit;72+ DRAFT_LIMIT: RateLimit;73 LOADER: WorkerLoader;74+ AI: Ai;75 OPERATOR_HANDLE: string;76 STAGE: string;77 LANDER_ADAPTER: string;78+ DRAFT_MODEL: string;79+ PUBLIC_WEB_URL: string;80 OPERATOR_TOKEN: string;81 COOKIE_KEY: string;82 PASSWORD_PEPPER: string;83 MASTER_KEY: string;8 unmodified lines92 type StringifyValues<EnvType extends Record<string, unknown>> = {93 [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;94 };95 declare namespace NodeJS {84- interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "OPERATOR_HANDLE" | "STAGE" | "LANDER_ADAPTER" | "OPERATOR_TOKEN" | "COOKIE_KEY" | "PASSWORD_PEPPER" | "MASTER_KEY">> {}96+ interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "OPERATOR_HANDLE" | "STAGE" | "LANDER_ADAPTER" | "DRAFT_MODEL" | "PUBLIC_WEB_URL" | "OPERATOR_TOKEN" | "COOKIE_KEY" | "PASSWORD_PEPPER" | "MASTER_KEY">> {}97 }modified:apps/platform/wrangler.jsonc+28 added
36 unmodified lines37 "OPERATOR_HANDLE": "oscabriel",38 "STAGE": "local",39 // "container" (apps/sandbox) or "isogit" (in this Worker).40 "LANDER_ADAPTER": "container",41+ // The Workers AI model that drafts asks; swap it here, no code change.42+ "DRAFT_MODEL": "@cf/moonshotai/kimi-k2.7-code",43+ // The web app, which `/` links to: `vite dev`'s URL locally.44+ "PUBLIC_WEB_URL": "http://localhost:5173",45 },46 "secrets": {47 // Declared in .env.schema; the user sets the values. SESSION_TOKENS is48 // optional; sign-in's cookie key and pepper are not, since accounts are37 unmodified lines86 { "binding": "EVIDENCE", "bucket_name": "evidence-local" },87 { "binding": "RELEASES", "bucket_name": "releases-local" },88 ],89 "worker_loaders": [{ "binding": "LOADER" }],90+ // Workers AI, for the drafter (no key: the account's own).91+ "ai": { "binding": "AI" },92 "services": [{ "binding": "SANDBOX", "service": "sandbox" }],93 // Namespace ids differ per stage, so one stage's counts never spend94 // another's.95 "ratelimits": [13 unmodified lines109 "name": "SIGN_IN_LIMIT",110 "namespace_id": "1003",111 "simple": { "limit": 5, "period": 60 },112 },113+ // Drafts per person: each one is a model call and Checker runs.114+ {115+ "name": "DRAFT_LIMIT",116+ "namespace_id": "1004",117+ "simple": { "limit": 2, "period": 60 },118+ },119 ],120 "triggers": {121 "events": [122 {8 unmodified lines131 "vars": {132 "OPERATOR_HANDLE": "oscabriel",133 "STAGE": "dev-oscabriel",134 "LANDER_ADAPTER": "container",135+ "DRAFT_MODEL": "@cf/moonshotai/kimi-k2.7-code",136+ "PUBLIC_WEB_URL": "https://web-dev-oscabriel.oscargabriel.workers.dev",137 },138 "secrets": {139 "required": [140 "OPERATOR_TOKEN",37 unmodified lines178 { "binding": "EVIDENCE", "bucket_name": "evidence-dev-oscabriel" },179 { "binding": "RELEASES", "bucket_name": "releases-dev-oscabriel" },180 ],181 "worker_loaders": [{ "binding": "LOADER" }],182+ "ai": { "binding": "AI" },183 "services": [184 { "binding": "SANDBOX", "service": "sandbox-dev-oscabriel" },185 ],186 "ratelimits": [11 unmodified lines198 "name": "SIGN_IN_LIMIT",199 "namespace_id": "1103",200 "simple": { "limit": 5, "period": 60 },201 },202+ {203+ "name": "DRAFT_LIMIT",204+ "namespace_id": "1104",205+ "simple": { "limit": 2, "period": 60 },206+ },207 ],208 "triggers": {209 "events": [210 {10 unmodified lines221 "vars": {222 "OPERATOR_HANDLE": "oscabriel",223 "STAGE": "demo",224 "LANDER_ADAPTER": "container",225+ "DRAFT_MODEL": "@cf/moonshotai/kimi-k2.7-code",226+ "PUBLIC_WEB_URL": "https://web-demo.oscargabriel.workers.dev",227 },228 "secrets": {229 "required": [230 "OPERATOR_TOKEN",33 unmodified lines264 { "binding": "EVIDENCE", "bucket_name": "evidence-demo" },265 { "binding": "RELEASES", "bucket_name": "releases-demo" },266 ],267 "worker_loaders": [{ "binding": "LOADER" }],268+ "ai": { "binding": "AI" },269 "services": [{ "binding": "SANDBOX", "service": "sandbox-demo" }],270 "ratelimits": [271 {272 "name": "CLAIM_LIMIT",9 unmodified lines282 "name": "SIGN_IN_LIMIT",283 "namespace_id": "1203",284 "simple": { "limit": 5, "period": 60 },285 },286+ {287+ "name": "DRAFT_LIMIT",288+ "namespace_id": "1204",289+ "simple": { "limit": 2, "period": 60 },290+ },291 ],292 "triggers": {293 "events": [294 {11 unmodified linesmodified:apps/web/src/client/watch.ts+1 added
77 unmodified lines78 Judged: ({ ask }) => keys.ask(project, ask),79 Landed: () => keys.project(project),80 Lapsed: () => keys.project(project),81 LedgerAppended: () => keys.ledger(project),82+ ProposalDrafted: () => keys.project(project),83 ProposalOpened: () => keys.project(project),84 Pushed: ({ ask }) => keys.ask(project, ask),85 Released: () => keys.project(project),86 Warned: ({ ask }) => keys.ask(project, ask),48 unmodified linesmodified:apps/web/src/dev/front-page.ts+1 added
90 unmodified lines91 Judged: () => rows,92 Landed: () => rows,93 Lapsed: ({ ask }) => withClaims(rows, keyOf(project, ask), -1),94 LedgerAppended: () => rows,95+ ProposalDrafted: () => rows,96 ProposalOpened: () => rows,97 Pushed: () => rows,98 Released: ({ ask }) => withClaims(rows, keyOf(project, ask), -1),99 Warned: () => rows,129 unmodified linesmodified:apps/web/src/dev/handlers.ts+70 added-2 removed
6 unmodified lines7 * projects; `status` and `today` without a project ask every project it8 * lists and merge what each says; `evidence` reads the world's lane logs.9 * Unlike the platform, nothing spends a rate limit: the world has one10 * browser at a time. Every `remote` names the origin the caller reached the11- * world by, as the platform's do.11+ * world by, as the platform's do. The code reads run the same12+ * `@repo/project/code` functions the platform's do, over the world's13+ * `RepoHost`.14 */15+import { RepoHost } from "@repo/artifacts/repo-host";16 import { EvidenceStore, LogRef } from "@repo/checks/evidence-store";17+import {18+ codeProjectOf,19+ commitOf,20+ fileOf,21+ logOf,22+ pathsOf,23+ refsOf,24+ treeOf,25+ whyOf,26+} from "@repo/project/code";27+import type { CodeProject } from "@repo/project/code";28 import { FrontPage } from "@repo/project/front-page";29 import type { ProjectApi } from "@repo/project/project";30 import { Projects } from "@repo/project/projects";31 import { Contracts, EnvSchemaOf } from "@repo/protocol/contracts";9 unmodified lines41 import type { Layer } from "effect";42 import { HttpServerRequest } from "effect/http";43 import type { Rpc, RpcGroup } from "effect/rpc";44 45+/** How many commits a page of `log` holds when the caller names no limit. */46+const LOG_PAGE = 30;47+48 /** How many events `watch` reads from its project at a time. */49 const EVENT_PAGE = 100;50 51 /** The caller, as the `Authenticated` server side named them. */95 unmodified lines147 /** Every contract over the dev world. A missing contract is a type error here. */148 export const devHandlers: Layer.Layer<149 Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>,150 never,134- Projects | FrontPage | EvidenceStore151+ Projects | FrontPage | EvidenceStore | RepoHost152 > = Contracts.toLayer(153 Effect.gen(function* () {154 const projects = yield* Projects;155 const frontPage = yield* FrontPage;156 const evidence = yield* EvidenceStore;157+ const host = yield* RepoHost;158 159 /** `call` on the project named `project`; one never made is `UnknownProject`. */160 const on = <A, E>(161 project: ProjectName,162 call: (api: ProjectApi) => Effect.Effect<A, E>163 ) => Effect.flatMap(projects.get(project), call);164 165+ /** A code read of `project`'s canonical repo, over the world's `RepoHost`. */166+ const code = <A, E>(167+ project: ProjectName,168+ read: (of: CodeProject) => Effect.Effect<A, E, RepoHost>169+ ) =>170+ on(project, (api) =>171+ read(codeProjectOf(api, project)).pipe(172+ Effect.provideService(RepoHost, host)173+ )174+ );175+176 /** `call` on every project the front page lists, in name order, keeping what each finds. */177 const everywhere = <A, E>(178 call: (api: ProjectApi) => Effect.Effect<Option.Option<A>, E>179 ) =>28 unmodified lines208 decide: ({ project, ...input }) =>209 Effect.flatMap(person, (who) =>210 on(project, (api) => api.decide(who, input))211 ),212+ draftAsk: ({ project, ...input }) =>213+ Effect.flatMap(person, (who) =>214+ on(project, (api) => api.draftAsk(who, input))215+ ),216 evidence: ({ project, ref }) =>217 Effect.flatMap(person, (who) =>218 on(project, (api) =>219 api54 unmodified lines274 listAsks: ({ project }) =>275 Effect.flatMap(caller, (who) =>276 on(project, (api) => api.listAsks(who))277 ),278+ listPaths: ({ at, project }) =>279+ code(project, (of) => pathsOf(of, Option.fromUndefinedOr(at))),280 listProjects: () =>281 Effect.map(frontPage.projects(), (listed) => ({ projects: listed })),282+ listRefs: ({ project }) => code(project, refsOf),283+ log: ({ at, from = 0, limit = LOG_PAGE, path, project }) =>284+ code(project, (of) =>285+ logOf(of, {286+ at: Option.fromUndefinedOr(at),287+ from,288+ limit,289+ path: Option.fromUndefinedOr(path),290+ })291+ ),292 openAsk: ({ project, ...input }) =>293 Effect.flatMap(person, (who) =>294 on(project, (api) => api.openAsk(who, input))295 ),296+ projectPolicy: ({ project }) =>297+ on(project, (api) =>298+ Effect.map(api.policy(), (policy) =>299+ Option.match(policy, {300+ onNone: () => ({}),301+ onSome: (evaluated) => ({ policy: evaluated }),302+ })303+ )304+ ),305 proposeAsk: ({ project, ...input }) =>306 Effect.flatMap(person, (who) =>307 on(project, (api) => api.proposeAsk(who, input))308 ),309+ readFile: ({ at, path, project }) =>310+ code(project, (of) => fileOf(of, Option.fromUndefinedOr(at), path)),311+ readTree: ({ at, path, project }) =>312+ code(project, (of) =>313+ treeOf(of, Option.fromUndefinedOr(at), Option.fromUndefinedOr(path))314+ ),315 release: ({ ask, project }) =>316 Effect.flatMap(person, (who) =>317 on(project, (api) => api.release(who, ask))318 ),4 unmodified lines323 showAsk: ({ ask, project }) =>324 Effect.flatMap(caller, (who) =>325 on(project, (api) => api.showAsk(who, ask))326 ),327+ showCommit: ({ project, sha }) =>328+ code(project, (of) => commitOf(of, sha)),329+ showProposal: ({ project, proposal }) =>330+ Effect.flatMap(caller, (who) =>331+ on(project, (api) => api.showProposal(who, proposal))332+ ),333 status: ({ project }) =>334 Effect.gen(function* () {335 const who = yield* person;336 55 unmodified lines392 ])393 )394 )395 ),396+ why: ({ at, path, project }) =>397+ code(project, (of) => whyOf(of, Option.fromUndefinedOr(at), path)),398 };399 })400 );modified:apps/web/package.json+1 added
41 unmodified lines42 "@playwright/test": "1.63.0",43 "@repo/artifacts": "workspace:*",44 "@repo/checks": "workspace:*",45 "@repo/config": "workspace:*",46+ "@repo/drafting": "workspace:*",47 "@repo/git": "workspace:*",48 "@repo/project": "workspace:*",49 "@repo/rules": "workspace:*",50 "@repo/testkit": "workspace:*",12 unmodified linesmodified:packages/agent-kit/test/command-doc.test.ts+7 added-1 removed
158 unmodified lines159 expect(160 words.filter((name) => name.startsWith("ask") || name.startsWith("env"))161 ).toStrictEqual([162 "ask",163+ "ask draft",164 "ask flag",165 "ask open",166 "asks",167 "env set",168 "env shape",169 ]);169- expect(words.slice(0, 3)).toStrictEqual(["ask", "ask flag", "ask open"]);170+ expect(words.slice(0, 4)).toStrictEqual([171+ "ask",172+ "ask draft",173+ "ask flag",174+ "ask open",175+ ]);176 });177 178 // `init` and `env set` do local work around the contract they call, so179 // their hand-written rows stand for those contracts.5 unmodified linesmodified:packages/artifacts/src/repo-host/binding.ts+19 added-5 removed
57 unmodified lines58 refOf,59 secondsOf,60 } from "./artifacts-api.ts";61 import type { Code } from "./artifacts-api.ts";62-import { listRefs, pushRefs } from "./smart-http.ts";62+import { listRefs, listTags, pushRefs } from "./smart-http.ts";63 64 /**65 * The codes a message names when the error carries none: Artifacts'66 * words, the fake's, and the code itself.100 unmodified lines167 168 const commitOf = (metadata: ArtifactsCommitMetadata) =>169 decodeCommit({170 author: metadata.author,171+ authoredAt: metadata.authoredAt,172+ committedAt: metadata.committedAt,173 committer: metadata.committer,174 message: metadata.message,175 parents: metadata.parents,176 sha: metadata.hash,95 unmodified lines272 return yield* listRefs(remote, token);273 })274 );275 276+/** The repo's tags over smart HTTP, peeled: the binding lists no refs. */277+const tagsOf = (name: RepoName, repo: ArtifactsRepo) =>278+ Effect.scoped(279+ Effect.gen(function* () {280+ const { remote, token } = yield* access(name, repo, "read");281+282+ return yield* listTags(remote, token);283+ })284+ );285+286 /**287 * After a 500 and then an already-exists or a second 500, the fork may be288 * made: it is, if it lists `main`. Otherwise it is still being made, or289 * was undone; either way the caller tries again later.112 unmodified lines402 const log = (403 name: RepoName,404 repo: ArtifactsRepo,405 at: Revision,394- limit: number406+ limit: number,407+ offset: number408 ) =>409 Effect.gen(function* () {410 const ref = refOf(at);411 const commits: Commit[] = [];1 unmodified line413 while (commits.length < limit) {414 const asked = Math.min(limit - commits.length, LOG_PAGE);415 416 const page = yield* call(name, () =>404- repo.log({ limit: asked, offset: commits.length, ref })417+ repo.log({ limit: asked, offset: offset + commits.length, ref })418 );419 420 for (const metadata of page) {421 commits.push(yield* commitOf(metadata));74 unmodified lines496 ),497 Effect.provideService(Fetch, fetch)498 ),499 importFrom: (name, source) => importFrom(binding, name, source),487- log: (name, at, limit) =>488- read(name, (repo) => log(name, repo, at, limit)),500+ log: (name, at, limit, offset = 0) =>501+ read(name, (repo) => log(name, repo, at, limit, offset)),502 mintToken: (name, scope, ttl) =>503 read(name, (repo) => mintToken(name, repo, scope, ttl)),504 push: (name, source, updates) =>505 withRepo(binding, name, (repo) =>52 unmodified lines558 Effect.catchTag("Thrown", asDefect)559 ),560 revokeToken: (name, id) =>561 read(name, (repo) => call(name, () => repo.revokeToken(id))),562+ tags: (name) => read(name, (repo) => tagsOf(name, repo)),563 });564 });565 566 /**7 unmodified linesmodified:packages/artifacts/src/repo-host/isogit-store.ts+73 added-5 removed
5 unmodified lines6 init,7 listRefs,8 readBlob,9 readCommit,10+ readTag,11 readTree,12 resolveRef,13 writeBlob,14 writeCommit,15 writeRef,16+ writeTag,17 writeTree,18 } from "isomorphic-git";19 20 import {140 unmodified lines161 );162 yield* keep(oid, () => writeCommit({ ...into, commit }));163 });164 165+/**166+ * A ref's target, objects first: an annotated tag after what it names167+ * (a commit, or another tag), or else a commit and its history.168+ */169+const copyTarget = (170+ source: PushSource,171+ into: GitDir,172+ oid: string173+): Effect.Effect<void> =>174+ Effect.gen(function* () {175+ const tag = yield* unlessMissing(() => readTag({ ...source, oid }));176+177+ if (Option.isNone(tag)) {178+ yield* copyCommit(source, into, oid);179+180+ return;181+ }182+183+ const present = yield* unlessMissing(() => readTag({ ...into, oid }));184+185+ if (Option.isSome(present)) {186+ return;187+ }188+189+ yield* copyTarget(source, into, tag.value.tag.object);190+ yield* keep(oid, () => writeTag({ ...into, tag: tag.value.tag }));191+ });192+193 /** Sets the new repo `into`'s `ref` to `source`'s `tip`, objects first. */194 export const seedRef = (195 source: PushSource,196 into: GitDir,20 unmodified lines217 if (!Equal.equals(tip, update.from)) {218 return RefOutcome.Stale({ ref: update.ref, tip });219 }220 191- yield* copyCommit(source, into, update.to);221+ yield* copyTarget(source, into, update.to);222 yield* git(() =>223 writeRef({ ...into, force: true, ref: update.ref, value: update.to })224 ).pipe(Effect.orDie);225 11 unmodified lines237 unlessMissing(() => readCommit({ ...repo, oid: sha })).pipe(238 Effect.map(239 Option.map(({ commit, oid }): Commit => ({240 author: { email: commit.author.email, name: commit.author.name },241+ authoredAt: commit.author.timestamp,242+ committedAt: commit.committer.timestamp,243 committer: {244 email: commit.committer.email,245 name: commit.committer.name,246 },18 unmodified lines265 export const objectsAndRefs = (266 known: (name: RepoName) => Effect.Effect<StoredRepo, RepoNotFound>267 ): Pick<268 RepoHost["Service"],237- "log" | "push" | "readBlob" | "readCommit" | "readFile" | "readTree" | "refs"269+ | "log"270+ | "push"271+ | "readBlob"272+ | "readCommit"273+ | "readFile"274+ | "readTree"275+ | "refs"276+ | "tags"277 > => ({239- log: (name, at, limit) =>278+ log: (name, at, limit, offset = 0) =>279 Effect.gen(function* () {280 const { dir } = yield* known(name);281 const commits: Commit[] = [];282 let next = yield* resolve(dir, at);283 245- while (Option.isSome(next) && commits.length < limit) {284+ while (Option.isSome(next) && commits.length < offset + limit) {285 const commit = yield* commitAt(dir, next.value);286 287 if (Option.isNone(commit)) {288 break;2 unmodified lines291 commits.push(commit.value);292 next = Option.fromNullishOr(commit.value.parents[0]);293 }294 256- return commits;295+ return commits.slice(offset);296 }),297 push: (name, source, updates) =>298 Effect.gen(function* () {299 const { dir, lock } = yield* known(name);68 unmodified lines368 );369 370 return new Map(Array.getSomes(listed));371 }),372+ // isomorphic-git's `readCommit` peels an annotated tag to its commit; a373+ // tag naming a tree or a blob names no commit, and is left out.374+ tags: (name) =>375+ Effect.gen(function* () {376+ const { dir } = yield* known(name);377+378+ const names = yield* git(() =>379+ listRefs({ ...dir, filepath: "refs/tags" })380+ ).pipe(Effect.orDie);381+382+ const listed = yield* Effect.forEach(names, (relative) =>383+ Effect.gen(function* () {384+ const ref = RefName.make(`refs/tags/${relative}`);385+ const tip = yield* tipOf(dir, ref);386+387+ const peeled = yield* Option.match(tip, {388+ onNone: () => Effect.succeedNone,389+ onSome: (oid) => unlessMissing(() => readCommit({ ...dir, oid })),390+ });391+392+ return Option.map(peeled, ({ oid }) => ({393+ name: ref,394+ sha: CommitSha.make(oid),395+ }));396+ })397+ );398+399+ return Array.getSomes(listed);400+ }),401 });modified:packages/artifacts/src/repo-host/rest.ts+34 added-6 removed
103 unmodified lines104 refOf,105 secondsOf,106 } from "./artifacts-api.ts";107 import type { Code } from "./artifacts-api.ts";108-import { listRefs, pushRefs } from "./smart-http.ts";108+import { listRefs, listTags, pushRefs } from "./smart-http.ts";109 110 /** A refusal that names no code at all, such as a proxy's, read by status. */111 const byStatus = (status: number): Option.Option<Code> =>112 Match.value(status).pipe(81 unmodified lines194 message: Schema.String,195 parents: Schema.Array(CommitSha),196 };197 198+// ASSUMPTION: the REST API spells the binding's times as it spells199+// `tree_hash`, in snake case, or as the binding does.200 const Metadata = Schema.Union([199- Schema.Struct({ ...commitFields, tree_hash: ObjectId }),200- Schema.Struct({ ...commitFields, treeHash: ObjectId }),201+ Schema.Struct({202+ ...commitFields,203+ authored_at: Schema.Int,204+ committed_at: Schema.Int,205+ tree_hash: ObjectId,206+ }),207+ Schema.Struct({208+ ...commitFields,209+ authoredAt: Schema.Int,210+ committedAt: Schema.Int,211+ treeHash: ObjectId,212+ }),213 ]);214 215 type Metadata = typeof Metadata.Type;216 10 unmodified lines227 const decodeEntries = Schema.decodeUnknownEffect(Schema.Array(TreeEntry));228 229 const commitOf = (metadata: Metadata): Commit => ({230 author: metadata.author,231+ ...("tree_hash" in metadata232+ ? {233+ authoredAt: metadata.authored_at,234+ committedAt: metadata.committed_at,235+ tree: metadata.tree_hash,236+ }237+ : {238+ authoredAt: metadata.authoredAt,239+ committedAt: metadata.committedAt,240+ tree: metadata.treeHash,241+ }),242 committer: metadata.committer,243 message: metadata.message,244 parents: metadata.parents,245 sha: metadata.hash,223- tree: "tree_hash" in metadata ? metadata.tree_hash : metadata.treeHash,246 });247 248 // Artifacts gives canonical modes: a folder is `40000`, as git stores it, not249 // `040000`, as `ls-tree` prints it and the port has it.455 unmodified lines705 : Effect.die(refused)706 )707 );708 687- const log = (name: RepoName, at: Revision, limit: number) =>709+ const log = (name: RepoName, at: Revision, limit: number, offset = 0) =>710 Effect.gen(function* () {711 const commits: Commit[] = [];712 713 while (commits.length < limit) {714 const more = yield* page(715 name,716 refOf(at),695- commits.length,717+ offset + commits.length,718 Math.min(limit - commits.length, LOG_PAGE)719 );720 721 if (more.length === 0) {112 unmodified lines834 // The route takes the id alone; the repo is checked to exist, as the835 // binding's `get` does.836 revokeToken: (name, id) =>837 remoteOf(name).pipe(Effect.andThen(revoke(id))),838+ tags: (name) =>839+ accessOf(name, "read").pipe(840+ Effect.flatMap(({ remote, token }) => listTags(remote, token)),841+ Effect.catchTag("ForkInProgress", Effect.die),842+ Effect.provideService(Fetch, fetch)843+ ),844 });845 });846 847 /**16 unmodified linesmodified:packages/artifacts/src/repo-host/smart-http.ts+43 added-1 removed
43 unmodified lines44 RefOutcome,45 RepoName,46 RepoNotFound,47 } from "../repo-host.ts";48-import type { PushSource, RefUpdate } from "../repo-host.ts";48+import type { PushSource, RefUpdate, Tag } from "../repo-host.ts";49 50 /** What isomorphic-git or a response body threw, before it is read. */51 class GitFailure extends Data.TaggedError("GitFailure")<{52 readonly cause: unknown;219 unmodified lines272 )273 );274 275 /**276+ * Every `refs/tags/*` the remote lists, each peeled to what it names: the277+ * `^{}` line protocol v1 advertises after an annotated tag, else the tag's278+ * own target.279+ */280+const tagsAt = (remote: string, http: HttpClient) =>281+ git(() =>282+ listServerRefs({283+ http,284+ peelTags: true,285+ prefix: "refs/tags/",286+ protocolVersion: 1,287+ url: remote,288+ })289+ ).pipe(290+ Effect.catchTags({291+ GitFailure: ({ cause }) => Effect.die(cause),292+ HostBusy: Effect.die,293+ }),294+ Effect.map((refs) =>295+ refs.flatMap(({ oid, peeled, ref }) =>296+ Option.match(Option.all([decodeRef(ref), decodeSha(peeled ?? oid)]), {297+ onNone: () => [],298+ onSome: ([name, sha]) => [{ name, sha }],299+ })300+ )301+ )302+ );303+304+/** Every tag the remote lists, peeled to its commit. */305+export const listTags = (306+ remote: string,307+ token: Redacted.Redacted308+): Effect.Effect<readonly Tag[], RepoNotFound, Fetch> =>309+ Effect.scoped(310+ Effect.gen(function* () {311+ const name = yield* repoOf(remote);312+313+ return yield* tagsAt(remote, yield* httpFor(remote, token, name));314+ })315+ );316+317+/**318 * Every ref the remote lists, as `ls-remote` lists them: what reads by name319 * cannot reach.320 */321 export const listRefs = (197 unmodified linesmodified:packages/artifacts/src/repo-host.ts+20 added-2 removed
68 unmodified lines69 export const Revision = Data.taggedEnum<Revision>();70 71 const Person = Schema.Struct({ email: Schema.String, name: Schema.String });72 73+/** A commit, with when it was written and when committed, in Unix seconds. */74 export const Commit = Schema.Struct({75 author: Person,76+ authoredAt: Schema.Int,77+ committedAt: Schema.Int,78 committer: Person,79 message: Schema.String,80 parents: Schema.Array(CommitSha),81 sha: CommitSha,1 unmodified line83 });84 85 export type Commit = typeof Commit.Type;86 87+/** One tag: its full ref, and the commit it names, peeled. */88+export interface Tag {89+ readonly name: RefName;90+ readonly sha: CommitSha;91+}92+93 export type TokenScope = "read" | "write";94 95 export interface RepoToken {96 readonly id: string;108 unmodified lines205 readonly readBlob: (206 name: RepoName,207 blob: ObjectId208 ) => Effect.Effect<Option.Option<Uint8Array>, RepoNotFound>;200- /** First parents from `at`, newest first. */209+ /** First parents from `at`, newest first, the first `offset` (0 when absent) skipped. */210 readonly log: (211 name: RepoName,212 at: Revision,204- limit: number213+ limit: number,214+ offset?: number215 ) => Effect.Effect<readonly Commit[], RepoNotFound>;216 /** Every ref, as `ls-remote` lists them, custom refs included. */217 readonly refs: (218 name: RepoName219 ) => Effect.Effect<ReadonlyMap<RefName, CommitSha>, RepoNotFound>;220+ /**221+ * Every `refs/tags/*`, each peeled to the commit it names: an annotated222+ * tag's ref names a tag object, which `readCommit` cannot read.223+ * `refs` keeps what git lists.224+ */225+ readonly tags: (226+ name: RepoName227+ ) => Effect.Effect<readonly Tag[], RepoNotFound>;228 readonly push: (229 name: RepoName,230 source: PushSource,231 updates: Array.NonEmptyReadonlyArray<RefUpdate>3 unmodified linesmodified:packages/artifacts/test/fake-rest.ts+9 added-4 removed
261 unmodified lines262 const prefix = `${apiBase}/accounts/${options.accountId}/artifacts/namespaces/${options.namespace}`;263 const forkFailures = yield* Ref.make(options.forkFailures ?? 0);264 const tokens = yield* Ref.make<ReadonlyMap<string, Minted>>(new Map());265 266- // `RepoHost`'s commits carry no times, so the fake reports the epoch.266+ // The times the host read from the commit itself.267 const metadataOf = (commit: Commit) => {268 const fields = {269 author: commit.author,270 committer: commit.committer,2 unmodified lines273 parents: commit.parents,274 };275 276 return options.casing === "camel"277- ? { ...fields, authoredAt: 0, committedAt: 0, treeHash: commit.tree }277+ ? {278+ ...fields,279+ authoredAt: commit.authoredAt,280+ committedAt: commit.committedAt,281+ treeHash: commit.tree,282+ }283 : {284 ...fields,280- authored_at: 0,281- committed_at: 0,285+ authored_at: commit.authoredAt,286+ committed_at: commit.committedAt,287 tree_hash: commit.tree,288 };289 };290 289 unmodified linesmodified:packages/artifacts/test/repo-host-contract.ts+181 added-1 removed
1 import { describe, expect, it } from "@effect/vitest";2-import { RepoPath } from "@repo/protocol/ids";2+import { CommitSha, RepoPath } from "@repo/protocol/ids";3 import { gitClient } from "@repo/testkit/git-client";4 import { DateTime, Duration, Effect, Option, Redacted } from "effect";5 import type { Layer } from "effect";6+import { readCommit, writeCommit, writeTag } from "isomorphic-git";7 8 import {9 BranchName,10 ObjectId,4 unmodified lines15 RepoName,16 RepoNotFound,17 Revision,18 } from "../src/repo-host.ts";19+import type { Commit } from "../src/repo-host.ts";20 import { memoryFs } from "../src/repo-host/memory-fs.ts";21 22 const main = RefName.make("refs/heads/main");23 7 unmodified lines31 32 /** No object in any repo here has this id. */33 const absent = ObjectId.make("0".repeat(40));34 35+/** When a commit was written, and when committed: two different instants. */36+const authored = 1_700_000_000;37+38+const committed = 1_700_000_500;39+40+/** The test client's repo, which a push takes objects from. */41+type Source = Parameters<RepoHost["Service"]["push"]>[1];42+43+/**44+ * A commit on `parent`'s tree written by hand, so its author and committer45+ * times differ (the test client stamps both alike).46+ */47+const timedCommit = (source: Source, parent: CommitSha) =>48+ Effect.gen(function* () {49+ const { commit } = yield* Effect.promise(() =>50+ readCommit({ ...source, oid: parent })51+ );52+53+ const oid = yield* Effect.promise(() =>54+ writeCommit({55+ ...source,56+ commit: {57+ author: {58+ email: "author@example.com",59+ name: "Author",60+ timestamp: authored,61+ timezoneOffset: 0,62+ },63+ committer: {64+ email: "committer@example.com",65+ name: "Committer",66+ timestamp: committed,67+ timezoneOffset: -120,68+ },69+ message: "timed\n",70+ parent: [parent],71+ tree: commit.tree,72+ },73+ })74+ );75+76+ return CommitSha.make(oid);77+ });78+79+/** When a commit was written and committed, as a store read it. */80+const times = (commit: Commit) => ({81+ authoredAt: commit.authoredAt,82+ committedAt: commit.committedAt,83+});84+85+/** An annotated tag object naming `commit`; its id, as a push sends it. */86+const annotatedTag = (source: Source, name: string, commit: CommitSha) =>87+ Effect.map(88+ Effect.promise(() =>89+ writeTag({90+ ...source,91+ tag: {92+ message: `${name}\n`,93+ object: commit,94+ tag: name,95+ tagger: {96+ email: "tagger@example.com",97+ name: "Tagger",98+ timestamp: committed,99+ timezoneOffset: 0,100+ },101+ type: "commit",102+ },103+ })104+ ),105+ // SAFETY: a tag's id is a 40-hex object id, which a ref update carries as a commit's.106+ (oid) => CommitSha.make(oid)107+ );108+109 /** What an adapter's run of the suite adds to the shared cases. */110 export interface RepoHostSuite {111 /**112 * The URL `importFrom` reads the repo `name` from, as this adapter's261 unmodified lines374 ).toStrictEqual([]);375 }).pipe(Effect.provide(host))376 );377 378+ it.effect("reads when a commit was written and when committed", () =>379+ Effect.gen(function* () {380+ const repos = yield* RepoHost;381+ const client = yield* gitClient(memoryFs());382+ const first = yield* client.commit("first", [["a", "1"]]);383+ const timed = yield* timedCommit(client.source, first);384+ const name = RepoName.make("times");385+386+ yield* repos.create(name);387+ yield* repos.push(name, client.source, [388+ { from: Option.none(), ref: main, to: timed },389+ ]);390+391+ expect(392+ Option.map(yield* repos.readCommit(name, timed), times)393+ ).toStrictEqual(394+ Option.some({ authoredAt: authored, committedAt: committed })395+ );396+ expect(397+ (yield* repos.log(398+ name,399+ Revision.Branch({ name: BranchName.make("main") }),400+ 10401+ )).map(times)402+ ).toStrictEqual([403+ { authoredAt: authored, committedAt: committed },404+ { authoredAt: 1_791_300_000, committedAt: 1_791_300_000 },405+ ]);406+ }).pipe(Effect.provide(host))407+ );408+409+ it.effect("logs from an offset, skipping the newest commits", () =>410+ Effect.gen(function* () {411+ const repos = yield* RepoHost;412+ const client = yield* gitClient(memoryFs());413+ const first = yield* client.commit("first", [["a", "1"]]);414+ const second = yield* client.commit("second", [["a", "2"]], [first]);415+ const third = yield* client.commit("third", [["a", "3"]], [second]);416+ const name = RepoName.make("offsets");417+418+ yield* repos.create(name);419+ yield* repos.push(name, client.source, [420+ { from: Option.none(), ref: main, to: third },421+ ]);422+423+ const tip = Revision.Branch({ name: BranchName.make("main") });424+425+ const shas = (limit: number, offset?: number) =>426+ repos427+ .log(name, tip, limit, offset)428+ .pipe(Effect.map((commits) => commits.map(({ sha }) => sha)));429+430+ expect(yield* shas(10, 1)).toStrictEqual([second, first]);431+ expect(yield* shas(1, 1)).toStrictEqual([second]);432+ expect(yield* shas(10, 3)).toStrictEqual([]);433+ expect(yield* shas(10, 0)).toStrictEqual([third, second, first]);434+ }).pipe(Effect.provide(host))435+ );436+437+ // An annotated tag names a tag object, which no commit read can read:438+ // `tags` peels each to its commit, while `refs` keeps what git lists.439+ it.effect("lists every tag peeled to its commit", () =>440+ Effect.gen(function* () {441+ const repos = yield* RepoHost;442+ const client = yield* gitClient(memoryFs());443+ const first = yield* client.commit("first", [["a", "1"]]);444+ const second = yield* client.commit("second", [["a", "2"]], [first]);445+ const annotated = yield* annotatedTag(client.source, "v1.0.0", first);446+ const name = RepoName.make("tagged");447+ const v1 = RefName.make("refs/tags/v1.0.0");448+ const light = RefName.make("refs/tags/light");449+450+ yield* repos.create(name);451+ yield* repos.push(name, client.source, [452+ { from: Option.none(), ref: main, to: second },453+ ]);454+ expect(yield* repos.tags(name)).toStrictEqual([]);455+ yield* repos.push(name, client.source, [456+ { from: Option.none(), ref: v1, to: annotated },457+ ]);458+ yield* repos.push(name, client.source, [459+ { from: Option.none(), ref: light, to: second },460+ ]);461+462+ const tags = yield* repos.tags(name);463+464+ expect(465+ tags.toSorted((one, other) => one.name.localeCompare(other.name))466+ ).toStrictEqual([467+ { name: light, sha: second },468+ { name: v1, sha: first },469+ ]);470+ expect((yield* repos.refs(name)).get(v1)).toBe(annotated);471+ expect(472+ yield* Effect.forEach(tags, ({ sha }) =>473+ Effect.map(repos.readCommit(name, sha), Option.isSome)474+ )475+ ).toStrictEqual([true, true]);476+ expect(477+ yield* Effect.flip(repos.tags(RepoName.make("missing")))478+ ).toStrictEqual(new RepoNotFound({ name: RepoName.make("missing") }));479+ }).pipe(Effect.provide(host))480+ );481+482 // Artifacts refuses `--atomic`, so landing pushes main by itself and483 // treats each ref's outcome on its own.484 it.effect("applies each ref's compare-and-swap on its own", () =>485 Effect.gen(function* () {190 unmodified linesmodified:packages/artifacts/test/rest.test.ts+2 added
653 unmodified lines654 655 expect(commit).toStrictEqual(656 Option.some({657 author: { email: "answerer@example.com", name: "Answerer" },658+ authoredAt: 1_791_300_000,659+ committedAt: 1_791_300_000,660 committer: { email: "answerer@example.com", name: "Answerer" },661 message: "first",662 parents: [],663 sha: first,37 unmodified linesmodified:packages/config/test/scripts.test.ts+21 added-13 removed
1 /**2 * The demo-readiness scripts: a maintainer types `bun run swarm`,3- * `bun run seed` or `bun run release`, and each runs one entry file that3+ * `bun run seed`, `bun run release` or `bun run import-examples`, and each4+ * runs one entry file that5 * exists, so the work that builds them fills an entry without touching a6 * root file.7 */8 import { NodeServices } from "@effect/platform-node";28 unmodified lines37 };38 });39 40 describe("the demo-readiness scripts", () => {40- it.live("swarm, seed and release each run one entry file that exists", () =>41- Effect.gen(function* () {42- expect({43- release: yield* entryOf("release"),44- seed: yield* entryOf("seed"),45- swarm: yield* entryOf("swarm"),46- }).toStrictEqual({47- release: { command: "bun scripts/release.ts", exists: true },48- seed: { command: "bun scripts/seed.ts", exists: true },49- swarm: { command: "bun scripts/swarm.ts", exists: true },50- });51- }).pipe(Effect.provide(NodeServices.layer))41+ it.live(42+ "swarm, seed, release and import-examples each run one entry file that exists",43+ () =>44+ Effect.gen(function* () {45+ expect({46+ "import-examples": yield* entryOf("import-examples"),47+ release: yield* entryOf("release"),48+ seed: yield* entryOf("seed"),49+ swarm: yield* entryOf("swarm"),50+ }).toStrictEqual({51+ "import-examples": {52+ command: "bun scripts/import-examples.ts",53+ exists: true,54+ },55+ release: { command: "bun scripts/release.ts", exists: true },56+ seed: { command: "bun scripts/seed.ts", exists: true },57+ swarm: { command: "bun scripts/swarm.ts", exists: true },58+ });59+ }).pipe(Effect.provide(NodeServices.layer))60 );61 });modified:packages/config/test/web-wiring.test.ts+14 added-1 removed
18 unmodified lines19 stages,20 subdomainFile,21 WorkersDev,22 } from "../../../infra/stages.ts";23-import { workers } from "../../../scripts/startup-budget.ts";23+import { budgets, workers } from "../../../scripts/startup-budget.ts";24 import { repoRoot } from "./root.ts";25 26 /** A file under the repo root, as text, once its presence is asserted. */27 const presentText = (file: string) =>190 unmodified lines218 describe("the byte alarm", () => {219 it("measures the web Worker", () => {220 expect(workers.map(({ dir }) => dir)).toContain("apps/web");221 });222+223+ // Each Worker grows on its own, so each has limits of its own: the224+ // platform's at the ceiling the code browser and drafting land under.225+ it("holds each Worker it measures to limits of its own", () => {226+ expect(budgets).toStrictEqual({227+ "apps/platform": { entry: 1_900_000, javascript: 2_500_000 },228+ "apps/sandbox": { entry: 1_665_000, javascript: 2_500_000 },229+ "apps/web": { entry: 1_665_000, javascript: 2_500_000 },230+ });231+ expect(Object.keys(budgets).toSorted()).toStrictEqual(232+ workers.map(({ dir }) => dir).toSorted()233+ );234+ });235 });236 237 describe("the examples", () => {238 it.effect(18 unmodified linesadded:packages/drafting/src/drafter/memory.ts+49 added
1+/**2+ * The `Drafter` in memory: each call takes the next answer from a script3+ * (a drafted ask, or the failure to give), and every input is kept for the4+ * test to read (`DraftsAsked`). A call past the script's end is the test's5+ * defect.6+ */7+import { Context, Effect, Layer, Ref, Schema } from "effect";8+9+import { DraftFailed } from "../drafted.ts";10+import type { DraftedAsk, DraftInput } from "../drafted.ts";11+import { Drafter } from "../drafter.ts";12+13+const isFailure = Schema.is(DraftFailed);14+15+/** What the memory drafter was asked, in order. */16+export class DraftsAsked extends Context.Service<17+ DraftsAsked,18+ { readonly inputs: Effect.Effect<readonly DraftInput[]> }19+>()("drafting/DraftsAsked") {}20+21+/** A drafter that answers `script` in order, one entry per call. */22+export const DrafterMemory = (23+ script: readonly (DraftedAsk | DraftFailed)[]24+): Layer.Layer<Drafter | DraftsAsked> =>25+ Layer.effectContext(26+ Effect.gen(function* () {27+ const left = yield* Ref.make(script);28+ const asked = yield* Ref.make<readonly DraftInput[]>([]);29+30+ const draft = (input: DraftInput) =>31+ Effect.gen(function* () {32+ yield* Ref.update(asked, (all) => [...all, input]);33+34+ const [next, ...rest] = yield* Ref.get(left);35+36+ if (next === undefined) {37+ return yield* Effect.die("the memory drafter's script ran out");38+ }39+40+ yield* Ref.set(left, rest);41+42+ return isFailure(next) ? yield* next : next;43+ });44+45+ return Context.make(Drafter, Drafter.of({ draft })).pipe(46+ Context.add(DraftsAsked, DraftsAsked.of({ inputs: Ref.get(asked) }))47+ );48+ })49+ );added:packages/drafting/src/drafted.ts+88 added
1+/**2+ * What drafting reads and writes. The model returns `DraftedAsk`, fields3+ * only: code renders the ask file from them, so only the test file is the4+ * model's own text. `DraftContext` is what it reads, from the canonical5+ * repo at the landed commit (never a layer's), and `DraftInput` one6+ * attempt's question. `DraftFailed` stays inside the run: it is no public7+ * refusal.8+ */9+import { AtLeastOne } from "@repo/protocol/domain/common";10+import { AskId, LandedSha, ProjectName, RepoPath } from "@repo/protocol/ids";11+import { Schema } from "effect";12+13+/** A string the model writes, bounded so no reply fills the Worker. */14+const Text = Schema.NonEmptyString.check(Schema.isMaxLength(4000));15+16+/** One ask, drafted: only `fix` asks are drafted. */17+export const DraftedAsk = Schema.Struct({18+ context: Schema.optionalKey(Schema.Array(Text)),19+ current: Schema.optionalKey(Text),20+ /** Becomes `<config>/asks/<id>.ask.ts`. */21+ id: AskId,22+ kind: Schema.Literal("fix"),23+ outOfScope: Schema.optionalKey(Schema.Array(Text)),24+ /** Shown to the decider as evidence; never landed. */25+ rationale: Schema.String.check(Schema.isMaxLength(4000)),26+ /** The files an answer may change. */27+ territory: Schema.NonEmptyArray(RepoPath),28+ /** The ask's check: a test that fails on main by an assertion. */29+ test: Schema.Struct({30+ path: RepoPath,31+ source: Schema.NonEmptyString.check(Schema.isMaxLength(100_000)),32+ }),33+ /** One testable sentence. */34+ want: Text,35+});36+37+export type DraftedAsk = typeof DraftedAsk.Type;38+39+/** One file the drafter reads, as text. */40+export const ContextFile = Schema.Struct({41+ content: Schema.String,42+ path: RepoPath,43+});44+45+export type ContextFile = typeof ContextFile.Type;46+47+/**48+ * What a draft reads: the project's public policy as a short digest, and49+ * the files picked from its canonical tree at the landed commit.50+ */51+export const DraftContext = Schema.Struct({52+ at: LandedSha,53+ files: Schema.Array(ContextFile),54+ policy: Schema.String,55+ project: ProjectName,56+});57+58+export type DraftContext = typeof DraftContext.Type;59+60+/** One attempt's question: the want, what it reads, and what went wrong before. */61+export const DraftInput = Schema.Struct({62+ attempt: AtLeastOne,63+ context: DraftContext,64+ /** The last attempt's refusal and its output's tail, for the next to mend. */65+ feedback: Schema.optionalKey(Schema.String),66+ /** A decider's or the proposer's note on what to do differently. */67+ note: Schema.optionalKey(Schema.String),68+ territory: Schema.optionalKey(Schema.NonEmptyString),69+ want: Schema.NonEmptyString,70+});71+72+export type DraftInput = typeof DraftInput.Type;73+74+/**75+ * The model gave no draft: its reply was no JSON, or not the schema's, it76+ * was rate-limited, or it failed.77+ */78+export class DraftFailed extends Schema.TaggedError<DraftFailed>()(79+ "DraftFailed",80+ {81+ reason: Schema.Literals([82+ "unparseable",83+ "schema",84+ "rate-limited",85+ "model-error",86+ ]),87+ }88+) {}added:packages/drafting/src/drafter.ts+19 added
1+/**2+ * The `Drafter` port: the platform's agent that drafts an ask from a want.3+ * Adapters: `/memory` (a scripted queue, for tests and the web's dev world)4+ * and `/binding` (Workers AI through the `AI` binding).5+ */6+import { Context } from "effect";7+import type { Effect } from "effect";8+9+import type { DraftFailed, DraftedAsk, DraftInput } from "./drafted.ts";10+11+export class Drafter extends Context.Service<12+ Drafter,13+ {14+ /** One attempt: the drafted ask's fields, or why the model gave none. */15+ readonly draft: (16+ input: DraftInput17+ ) => Effect.Effect<DraftedAsk, DraftFailed>;18+ }19+>()("drafting/Drafter") {}added:packages/drafting/test/memory.test.ts+57 added
1+import { describe, expect, it } from "@effect/vitest";2+import { AskId, LandedSha, ProjectName, RepoPath } from "@repo/protocol/ids";3+import { Effect } from "effect";4+5+import { DraftFailed } from "../src/drafted.ts";6+import type { DraftedAsk, DraftInput } from "../src/drafted.ts";7+import { Drafter } from "../src/drafter.ts";8+import { DrafterMemory, DraftsAsked } from "../src/drafter/memory.ts";9+10+const drafted: DraftedAsk = {11+ id: AskId.make("iso-week"),12+ kind: "fix",13+ rationale: "The parser has no week dates.",14+ territory: [RepoPath.make("src/parse.ts")],15+ test: {16+ path: RepoPath.make("test/iso-week.test.ts"),17+ source: 'it("parses", () => expect(parse("2026-W01")).toBe(1));\n',18+ },19+ want: "An ISO week date parses to the Monday of that week.",20+};21+22+const input = (attempt: number): DraftInput => ({23+ attempt,24+ context: {25+ at: LandedSha.make("4".repeat(40)),26+ files: [],27+ policy: "kinds: fix",28+ project: ProjectName.make("datekit"),29+ },30+ want: "Parse ISO week dates.",31+});32+33+describe("the memory drafter", () => {34+ it.effect(35+ "answers its script in order, failures too, and keeps every input",36+ () =>37+ Effect.gen(function* () {38+ const drafter = yield* Drafter;39+ const failed = new DraftFailed({ reason: "schema" });40+41+ const first = yield* Effect.flip(drafter.draft(input(1)));42+ const second = yield* drafter.draft(input(2));43+44+ expect(first).toStrictEqual(failed);45+ expect(second).toStrictEqual(drafted);46+ expect(47+ (yield* DraftsAsked.use(({ inputs }) => inputs)).map(48+ ({ attempt }) => attempt49+ )50+ ).toStrictEqual([1, 2]);51+ }).pipe(52+ Effect.provide(53+ DrafterMemory([new DraftFailed({ reason: "schema" }), drafted])54+ )55+ )56+ );57+});added:packages/drafting/package.json+28 added
1+{2+ "name": "@repo/drafting",3+ "private": true,4+ "type": "module",5+ "exports": {6+ "./*": "./src/*.ts"7+ },8+ "scripts": {9+ "typecheck": "tsc --noEmit -p tsconfig.json",10+ "test": "vitest run"11+ },12+ "dependencies": {13+ "@repo/artifacts": "workspace:*",14+ "@repo/brand": "workspace:*",15+ "@repo/project": "workspace:*",16+ "@repo/protocol": "workspace:*",17+ "effect": "catalog:"18+ },19+ "devDependencies": {20+ "@cloudflare/workers-types": "5.20261006.1",21+ "@effect/vitest": "catalog:",22+ "@repo/config": "workspace:*",23+ "@repo/rules": "workspace:*",24+ "@repo/testkit": "workspace:*",25+ "typescript": "catalog:",26+ "vitest": "catalog:"27+ }28+}added:packages/drafting/tsconfig.json+8 added
1+{2+ "extends": "../../tsconfig.base.json",3+ "compilerOptions": {4+ "allowImportingTsExtensions": true,5+ "types": ["@cloudflare/workers-types"]6+ },7+ "include": ["src/**/*.ts", "test/**/*.ts", "*.config.ts"]8+}added:packages/drafting/vitest.config.ts+1 added
1+export { preset as default } from "@repo/config/vitest";added:packages/project/src/code/cache.ts+24 added
1+/**2+ * The code reads' cache: what an object id names never changes, so a read3+ * keyed by `<repo>:<kind>:<object id>` (a tree, a blob, a commit, a commit's4+ * diff, a blame at a commit) is read once. A `Context.Reference` whose5+ * default caches nothing, so every host composes before one is given; the6+ * platform gives one held in a layer (no module-level state, principle 6).7+ * `main` is never a key: it resolves through the project's record on every8+ * call.9+ */10+import { Context } from "effect";11+import type { Effect } from "effect";12+13+/** The code reads, each kept by its key once read. */14+export interface CodeReads {15+ /** `read`, or what it gave before for `key`. */16+ readonly through: <A, E, R>(17+ key: string,18+ read: Effect.Effect<A, E, R>19+ ) => Effect.Effect<A, E, R>;20+}21+22+export const CodeCache = Context.Reference<CodeReads>("project/CodeCache", {23+ defaultValue: () => ({ through: (_key, read) => read }),24+});modified:packages/project/src/projection-d1/projection.ts+1 added
177 unmodified lines178 sql`UPDATE projects SET posture = ${entry.to}179 WHERE project = ${project} AND ${next}`,180 ]181 : [],182+ ProposalDrafted: () => [],183 ProposalOpened: () => [],184 Pushed: () => [],185 Released: ({ ask }) => [claims(ask, -1)],186 Warned: () => [],78 unmodified linesadded:packages/project/src/code.ts+122 added
1+/**2+ * A project's code as its readers browse it, read from its canonical repo3+ * only (no payload names a repo, so no fork or layer can be named, principle4+ * 7): refs, trees, every path, files, the first-parent log, a commit's diff5+ * and why each line is there. Host-free: both the platform's handlers and6+ * the web's dev world call these with the `RepoHost` they run on, and7+ * consult the project's record only for main's landed commit, its landings8+ * and its forks (`CodeProject`). Reads by object id go through `CodeCache`.9+ *10+ * Stubs until 903 (every read but `whyOf`) and 912 (`whyOf`) land; the11+ * signatures are final.12+ */13+import type { RepoHost } from "@repo/artifacts/repo-host";14+import type {15+ CommitDiff,16+ CommitView,17+ ForkRef,18+ PathList,19+ RefsView,20+ Rev,21+ FileView,22+ TreeListing,23+ WhyView,24+} from "@repo/protocol/domain/code";25+import type { LandingView } from "@repo/protocol/domain/landing";26+import { RepoName } from "@repo/protocol/ids";27+import type {28+ CommitSha,29+ LandedSha,30+ ProjectName,31+ RepoPath,32+} from "@repo/protocol/ids";33+import type {34+ UnknownCommit,35+ UnknownPath,36+ UnknownRevision,37+} from "@repo/protocol/refusal";38+import { Effect, Option } from "effect";39+40+import type { ProjectApi } from "./project.ts";41+42+/** What the code reads take from a project's record, beside its canonical repo. */43+export interface CodeProject {44+ /** The project's canonical repo: never a fork's or a layer's. */45+ readonly repo: RepoName;46+ /** Main's landed commit; none before the first push. */47+ readonly head: Effect.Effect<Option.Option<LandedSha>>;48+ /** The landings among `shas`, so a forged trailer never reads as one. */49+ readonly landings: (50+ shas: readonly CommitSha[]51+ ) => Effect.Effect<readonly LandingView[]>;52+ readonly forks: Effect.Effect<readonly ForkRef[]>;53+}54+55+/** The code reads' view of `project`, through its `ProjectApi`. */56+export const codeProjectOf = (57+ api: ProjectApi,58+ project: ProjectName59+): CodeProject => ({60+ forks: api.forks(),61+ head: Effect.map(api.head(), ({ landed }) => Option.fromUndefinedOr(landed)),62+ landings: api.landings,63+ repo: RepoName.make(project),64+});65+66+const notBuilt = (issue: string) => Effect.die(`not built: ${issue}`);67+68+/** Main's landed commit, its tags peeled and sorted newest first, and its forks. */69+export const refsOf = (70+ _project: CodeProject71+): Effect.Effect<RefsView, never, RepoHost> => notBuilt("903");72+73+/** One folder at `at` (main when none), folders first, with its README. */74+export const treeOf = (75+ _project: CodeProject,76+ _at: Option.Option<Rev>,77+ _path: Option.Option<RepoPath>78+): Effect.Effect<TreeListing, UnknownRevision | UnknownPath, RepoHost> =>79+ notBuilt("903");80+81+/** Every file path at `at`, up to the cap. */82+export const pathsOf = (83+ _project: CodeProject,84+ _at: Option.Option<Rev>85+): Effect.Effect<PathList, UnknownRevision, RepoHost> => notBuilt("903");86+87+/** One file at `at`: its text, or that it is binary or too large. */88+export const fileOf = (89+ _project: CodeProject,90+ _at: Option.Option<Rev>,91+ _path: RepoPath92+): Effect.Effect<FileView, UnknownRevision | UnknownPath, RepoHost> =>93+ notBuilt("903");94+95+/** A page of first-parent commits from `at`, each landing with its record. */96+export const logOf = (97+ _project: CodeProject,98+ _input: {99+ readonly at: Option.Option<Rev>;100+ readonly path: Option.Option<RepoPath>;101+ readonly from: number;102+ readonly limit: number;103+ }104+): Effect.Effect<105+ { readonly commits: readonly CommitView[]; readonly next?: number },106+ UnknownRevision,107+ RepoHost108+> => notBuilt("903");109+110+/** One commit and the files it changed against its first parent. */111+export const commitOf = (112+ _project: CodeProject,113+ _sha: CommitSha114+): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> => notBuilt("903");115+116+/** Why each line of a file at `at` is there. */117+export const whyOf = (118+ _project: CodeProject,119+ _at: Option.Option<Rev>,120+ _path: RepoPath121+): Effect.Effect<WhyView, UnknownRevision | UnknownPath, RepoHost> =>122+ notBuilt("912");modified:packages/project/src/deciders.ts+2 added
227 unmodified lines228 /** A proposal for a new ask, and the decision that puts it to its deciders. */229 readonly proposeAsk: (230 caller: Person,231 input: {232+ /** Have the platform's agent draft the ask's files. */233+ readonly draft?: true;234 readonly files?: Array.NonEmptyReadonlyArray<ComposedFile>;235 readonly sealed?: { readonly head: CommitSha };236 readonly territory?: string;237 readonly want: string;1850 unmodified linesmodified:packages/project/src/project.ts+155 added-11 removed
61 unmodified lines62 import {63 Claim as ClaimContract,64 Credits,65 Decide,66+ DraftAsk,67 EnvSchemaOf,68 EvidenceOf,69 Finish,70 FlagAsk,7 unmodified lines78 ProposeAsk,79 Release,80 SetEnv,81 ShowAsk,82+ ShowProposal,83 Status,84 SubmitAnswer,85 TodayOf,86 VerdictOf,7 unmodified lines94 import type { AnswerView, LaneResult } from "@repo/protocol/domain/answer";95 import type { Ask, AskListing } from "@repo/protocol/domain/ask";96 import { CheckSpec } from "@repo/protocol/domain/check";97 import type { ClaimView } from "@repo/protocol/domain/claim";98+import { ForkRef } from "@repo/protocol/domain/code";99 import { RefNameText } from "@repo/protocol/domain/common";97-import type { Evidence } from "@repo/protocol/domain/common";100+import type { ConfigFile, Evidence } from "@repo/protocol/domain/common";101 import type { AgentTrailer, Credit } from "@repo/protocol/domain/credit";102 import { DecisionSubject } from "@repo/protocol/domain/decision";103 import type { Choice, Decision } from "@repo/protocol/domain/decision";104 import { ProjectEvent } from "@repo/protocol/domain/event";105 import type { AskKind } from "@repo/protocol/domain/kind";103-import type { LandingView } from "@repo/protocol/domain/landing";106+import { LandingView } from "@repo/protocol/domain/landing";107 import { Outcome } from "@repo/protocol/domain/outcome";108 import type { StageName } from "@repo/protocol/domain/outcome";106-import { Policy } from "@repo/protocol/domain/policy";109+import { Policy, PublicPolicy } from "@repo/protocol/domain/policy";110 import type { Proposal } from "@repo/protocol/domain/proposal";111 import {112 AskId,113 CommitSha,114 EnvKey,115 Handle,116 LandedSha,117 LayerName,118+ ProposalId,119 RepoName,120 RepoPath,121 RequestId,122 TreeSha,123 sameHandle,124 } from "@repo/protocol/ids";121-import type {122- DecisionId,123- LaneName,124- ProjectName,125- ProposalId,126-} from "@repo/protocol/ids";125+import type { DecisionId, LaneName, ProjectName } from "@repo/protocol/ids";126 import { Person, Principal } from "@repo/protocol/principal";127 import {128 AskFull,129 DirectPush,16 unmodified lines146 AskBlocked,147 CapReached,148 ClaimLapsed,149 Denounced,150+ DraftInProgress,151+ ProposalClosed,152+ UnknownProposal,153 OutOfScope,154 PrivatePathInPublicTree,155 ReachedInternals,156 RepoBusy,226 unmodified lines383 readonly landing: (384 caller: Principal,385 sha: CommitSha386 ) => Effect.Effect<{ readonly landing: LandingView }, UnknownCommit>;387+ /** Where main has landed: none before the first push. */388+ readonly head: () => Effect.Effect<{ readonly landed?: LandedSha }>;389 /**390+ * The landings among `shas` (at most `MAX_LANDINGS`), in their order: a391+ * commit the platform did not land, imported history among them, has none.392+ */393+ readonly landings: (394+ shas: readonly CommitSha[]395+ ) => Effect.Effect<readonly LandingView[]>;396+ /** Every claim's fork, with its ask, claimant and the claim's state. */397+ readonly forks: () => Effect.Effect<readonly ForkRef[]>;398+ /**399+ * The policy at the landed commit as anyone may read it (no layers, no400+ * function-valued rules, no asks); none until it has evaluated.401+ */402+ readonly policy: () => Effect.Effect<Option.Option<PublicPolicy>>;403+ /**404+ * The public face of a proposal: its state, its draft's, and the files it405+ * holds until a decider accepts it.406+ */407+ readonly showProposal: (408+ caller: Principal,409+ proposal: ProposalId410+ ) => Effect.Effect<411+ { readonly files: readonly ConfigFile[]; readonly proposal: Proposal },412+ UnknownProposal413+ >;414+ /**415+ * Has the platform's agent draft an open proposal's ask, or draft it416+ * again with a note, for its proposer or a decider of its paths.417+ */418+ readonly draftAsk: (419+ caller: Person,420+ input: { readonly note?: string; readonly proposal: ProposalId }421+ ) => Effect.Effect<422+ { readonly proposal: Proposal },423+ UnknownProposal | ProposalClosed | NotDecider | DraftInProgress | CapReached424+ >;425+ /**426 * The log a failing lane left, by the name its verdict gives it427 * (`LaneResult.logRef`), for the project's deciders and the claimant428 * of the answer the name points at. A name `logRefOf` never makes, or one429 * that points at another project, is `UnknownProject` for anyone; past154 unmodified lines584 input: { readonly text: string } | { readonly blob: Uint8Array }585 ) => Effect.Effect<Option.Option<EnvKey>>;586 }587 588+/** The most commits one `landings` call looks up: a log page's, or a blame's batch. */589+export const MAX_LANDINGS = 100;590+591 /** The schemas one method's arguments (in order), success and failure cross a boundary with. */592 export interface MethodSchema {593 readonly args: readonly Schema.Top[];594 readonly error: Schema.Top;41 unmodified lines636 args: [Person, Decide.payloadSchema.mapFields(Struct.omit(["project"]))],637 error: Decide.errorSchema,638 success: Decide.successSchema,639 },640+ draftAsk: {641+ args: [Person, DraftAsk.payloadSchema.mapFields(Struct.omit(["project"]))],642+ error: DraftAsk.errorSchema,643+ success: DraftAsk.successSchema,644+ },645 events: {646 args: [Schema.Int, Schema.Int],647 error: Schema.Never,648 success: Schema.Array(24 unmodified lines673 args: [Person],674 error: Fork.errorSchema,675 success: Fork.successSchema,676 },677+ forks: { args: [], error: Schema.Never, success: Schema.Array(ForkRef) },678+ head: {679+ args: [],680+ error: Schema.Never,681+ success: Schema.Struct({ landed: Schema.optionalKey(LandedSha) }),682+ },683 heldBackJob: {684 args: [RequestId],685 error: Schema.Never,686 success: Schema.Option(HeldBackJob),15 unmodified lines702 args: [Principal, CommitSha],703 error: LandingOf.errorSchema,704 success: LandingOf.successSchema,705 },706+ landings: {707+ args: [Schema.Array(CommitSha).check(Schema.isMaxLength(MAX_LANDINGS))],708+ error: Schema.Never,709+ success: Schema.Array(LandingView),710+ },711 layerAccess: {712 args: [Principal, LayerName],713 error: Schema.Never,714 success: Schema.Option(LayerAccess),21 unmodified lines736 ],737 error: OpenAsk.errorSchema,738 success: OpenAsk.successSchema,739 },740+ policy: {741+ args: [],742+ error: Schema.Never,743+ success: Schema.Option(PublicPolicy),744+ },745 proposeAsk: {746 args: [747 Person,748+ // The check reads only `draft`, `files` and `sealed`, which it keeps.684- ProposeAsk.payloadSchema.mapFields(Struct.omit(["project"])),749+ ProposeAsk.payloadSchema.mapFields(Struct.omit(["project"]), {750+ unsafePreserveChecks: true,751+ }),752 ],753 error: ProposeAsk.errorSchema,754 success: ProposeAsk.successSchema,755 },54 unmodified lines810 args: [Principal, AskId],811 error: ShowAsk.errorSchema,812 success: ShowAsk.successSchema,813 },814+ showProposal: {815+ args: [Principal, ProposalId],816+ error: ShowProposal.errorSchema,817+ success: ShowProposal.successSchema,818+ },819 status: {820 args: [Person],821 error: Status.errorSchema,822 // The contract adds the caller's handle at the platform's edge; a project120 unmodified lines943 Effect.orDie(Schema.encodeUnknownEffect(schemas.success)(value))944 )945 );946 947+/** A policy as anyone may read it: without its layers, function-valued rules and asks. */948+const publicPolicy = (policy: Policy): PublicPolicy =>949+ Struct.omit(policy, ["asks", "functions", "visibility"]);950+951+/** A claim's fork, as the refs page lists it. */952+const listedFork = (claim: Live, state: ClaimView["state"]) =>953+ Option.some<ForkRef>({954+ ask: claim.ask,955+ handle: claim.claimant,956+ kind: "claim",957+ repo: claim.fork,958+ state,959+ });960+961+/** Where a claim stands, as its fork's listing says it; an open ask has no fork. */962+const forkOf = (state: ClaimState): Option.Option<ForkRef> =>963+ ClaimState.match(state, {964+ Answered: (claim) => listedFork(claim, "answered"),965+ Lapsed: (claim) => listedFork(claim, "lapsed"),966+ Live: (claim) => listedFork(claim, "live"),967+ Open: () => Option.none(),968+ Released: (claim) => listedFork(claim, "released"),969+ Warned: (claim) => listedFork(claim, "warned"),970+ });971+972+/** What a stub answers until the issue that builds it lands. */973+const notBuilt = (issue: string) => Effect.die(`not built: ${issue}`);974+975 /** The most of a lane's log `evidence` gives back: its last 256 KiB. */976 const EVIDENCE_TAIL = 256 * 1024;977 978 /** Whether a UTF-8 byte starts a character: it is no continuation byte (`10xxxxxx`). */4034 unmodified lines5013 MethodSchemas.decide,5014 [caller, input],5015 decided.decide(api, caller, input)5016 ),5017+ draftAsk: (caller, input) =>5018+ checked(MethodSchemas.draftAsk, [caller, input], notBuilt("909")),5019 events: (since, limit) =>5020 checked(5021 MethodSchemas.events,5022 [since, limit],28 unmodified lines5051 decided.flagAsk(api, caller, input)5052 ),5053 fork: (caller) =>5054 checked(MethodSchemas.fork, [caller], decided.fork(api, caller)),5055+ forks: () =>5056+ checked(5057+ MethodSchemas.forks,5058+ [],5059+ Effect.map(hydrate, (h) =>5060+ Array.getSomes(h.claims.map(({ state }) => forkOf(state)))5061+ )5062+ ),5063+ head: () =>5064+ checked(5065+ MethodSchemas.head,5066+ [],5067+ Effect.map(hydrate, (h) =>5068+ Option.match(5069+ Option.flatMapNullishOr(h.project, ({ landed }) => landed),5070+ { onNone: () => ({}), onSome: (landed) => ({ landed }) }5071+ )5072+ )5073+ ),5074 heldBackJob: (requestId) =>5075 checked(5076 MethodSchemas.heldBackJob,5077 [requestId],21 unmodified lines5099 onSome: (landing) => Effect.succeed({ landing }),5100 })5101 )5102 ),5103+ landings: (shas) =>5104+ checked(5105+ MethodSchemas.landings,5106+ [shas],5107+ Effect.map(5108+ Effect.forEach(Array.dedupe(shas), (sha) => store.landing(sha)),5109+ Array.getSomes5110+ )5111+ ),5112 layerAccess: (caller, layer) =>5113 checked(5114 MethodSchemas.layerAccess,5115 [caller, layer],25 unmodified lines5141 MethodSchemas.openAsk,5142 [caller, input],5143 write(api, openBody(caller, input))5144 ),5145+ policy: () =>5146+ checked(5147+ MethodSchemas.policy,5148+ [],5149+ Effect.map(hydrate, (h) => Option.map(h.policy, publicPolicy))5150+ ),5151 proposeAsk: (caller, input) =>5152 checked(5153 MethodSchemas.proposeAsk,5154 [caller, input],5155+ input.draft === true5156+ ? notBuilt("909")5019- decided.proposeAsk(api, caller, input)5157+ : decided.proposeAsk(api, caller, input)5158 ),5159 recordAdmission: (input) =>5160 checked(5161 MethodSchemas.recordAdmission,77 unmodified lines5239 onSome: (ask) => Effect.succeed({ ask, brief: briefOf(ask) }),5240 })5241 )5242 ),5243+ showProposal: (caller, proposal) =>5244+ checked(5245+ MethodSchemas.showProposal,5246+ [caller, proposal],5247+ notBuilt("909")5248+ ),5249 status: (caller) =>5250 checked(MethodSchemas.status, [caller], statusOf(caller)),5251 submitAnswer: (caller, input) =>5252 checked(18 unmodified linesadded:packages/project/src/repo-names.ts+87 added
1+/**2+ * What a repo's name says it is: a project's canonical repo3+ * `<project>`, a claim's fork `<project>--<ask>--<handle>`, or a person's4+ * working fork `<project>--me--<handle>`, each handle in lowercase. `--`5+ * occurs in no project or ask name, so a name splits back into its parts.6+ * Pure: the platform's gateway, handlers and OnPush read names with it, and7+ * a project lists its forks by it.8+ */9+import { AskId, Handle, ProjectName, RepoName } from "@repo/protocol/ids";10+import { Data, Option, Schema } from "effect";11+12+import { forkName } from "./claim.ts";13+14+/** What a repo is, read from its name alone. */15+export type RepoKind =16+ | { readonly _tag: "Canonical"; readonly project: ProjectName }17+ | {18+ readonly _tag: "ClaimFork";19+ readonly project: ProjectName;20+ readonly ask: AskId;21+ /** As the name spells it: in lowercase. */22+ readonly handle: Handle;23+ }24+ | {25+ readonly _tag: "WorkingFork";26+ readonly project: ProjectName;27+ /** As the name spells it: in lowercase. */28+ readonly handle: Handle;29+ }30+ | { readonly _tag: "Unknown" };31+32+export const RepoKind = Data.taggedEnum<RepoKind>();33+34+const asProject = Schema.decodeOption(ProjectName);35+36+const asAsk = Schema.decodeOption(AskId);37+38+const asHandle = Schema.decodeOption(Handle);39+40+/** The word that names a working fork where a claim's fork names its ask. */41+const WORKING = "me";42+43+/** What `name` says it is; `Unknown` for any name the platform never makes. */44+export const repoKind = (name: RepoName): RepoKind => {45+ const [first = "", second, third, ...rest] = name.split("--");46+47+ const kind = Option.flatMap(48+ asProject(first),49+ (project): Option.Option<RepoKind> => {50+ if (second === undefined) {51+ return Option.some(RepoKind.Canonical({ project }));52+ }53+54+ if (third === undefined || rest.length > 0) {55+ return Option.none();56+ }57+58+ const handle = Option.filter(59+ asHandle(third),60+ (spelled) => spelled === spelled.toLowerCase()61+ );62+63+ return second === WORKING64+ ? Option.map(handle, (owner) =>65+ RepoKind.WorkingFork({ handle: owner, project })66+ )67+ : Option.map(68+ Option.all({ ask: asAsk(second), handle }),69+ ({ ask, handle: claimant }) =>70+ RepoKind.ClaimFork({ ask, handle: claimant, project })71+ );72+ }73+ );74+75+ return Option.getOrElse(kind, () => RepoKind.Unknown());76+};77+78+/** A claim's fork: `<project>--<ask>--<handle in lowercase>`. */79+export const claimForkName: (80+ project: ProjectName,81+ ask: AskId,82+ handle: Handle83+) => RepoName = forkName;84+85+/** A person's working fork: `<project>--me--<handle in lowercase>`. */86+export const workingForkName = (project: ProjectName, handle: Handle) =>87+ RepoName.make(`${project}--${WORKING}--${handle.toLowerCase()}`);added:packages/project/test/code-facade.test.ts+110 added
1+/**2+ * The code façade both handler files call: a project's code read from its3+ * canonical repo alone, with main resolved through the project's record.4+ * Until 903 and 912 land, each read names the issue that builds it.5+ */6+import { describe, expect, it } from "@effect/vitest";7+import { RepoHost } from "@repo/artifacts/repo-host";8+import type { ProjectApi } from "@repo/project/project";9+import {10+ CommitSha,11+ LandedSha,12+ ProjectName,13+ RepoPath,14+} from "@repo/protocol/ids";15+import { untouchable } from "@repo/testkit/untouchable";16+import { Cause, Effect, Exit, Option } from "effect";17+18+import {19+ codeProjectOf,20+ commitOf,21+ fileOf,22+ logOf,23+ pathsOf,24+ refsOf,25+ treeOf,26+ whyOf,27+} from "../src/code.ts";28+import { CodeCache } from "../src/code/cache.ts";29+30+const project = ProjectName.make("datekit");31+32+const landed = LandedSha.make("4".repeat(40));33+34+const sha = CommitSha.make("4".repeat(40));35+36+const path = RepoPath.make("README.md");37+38+/** A project's record, as the façade reads it: only these three. */39+const api = untouchable<ProjectApi>("ProjectApi", {40+ forks: () => Effect.succeed([]),41+ head: () => Effect.succeed({ landed }),42+ landings: () => Effect.succeed([]),43+});44+45+const code = codeProjectOf(api, project);46+47+/** What a stub died with, as text; none when it did not die. */48+const diedWith = <A, E>(effect: Effect.Effect<A, E, RepoHost>) =>49+ Effect.map(50+ Effect.exit(51+ Effect.provideService(52+ effect,53+ RepoHost,54+ untouchable<RepoHost["Service"]>("RepoHost")55+ )56+ ),57+ (exit) =>58+ Exit.isFailure(exit) && Cause.hasDies(exit.cause)59+ ? Option.some(String(Cause.squash(exit.cause)))60+ : Option.none()61+ );62+63+describe("a project's code, read through the façade", () => {64+ it.effect(65+ "reads the canonical repo, with main from the project's record",66+ () =>67+ Effect.gen(function* () {68+ expect(code.repo).toBe(project);69+ expect(yield* code.head).toStrictEqual(Option.some(landed));70+ expect(yield* code.forks).toStrictEqual([]);71+ })72+ );73+74+ it.effect("caches nothing until a cache is given", () =>75+ Effect.gen(function* () {76+ const cache = yield* CodeCache;77+ let reads = 0;78+79+ const read = Effect.sync(() => {80+ reads += 1;81+82+ return reads;83+ });84+85+ expect(yield* cache.through("datekit:tree:x", read)).toBe(1);86+ expect(yield* cache.through("datekit:tree:x", read)).toBe(2);87+ })88+ );89+90+ it.effect("names the issue that builds each read", () =>91+ Effect.gen(function* () {92+ const none = Option.none();93+94+ expect(95+ yield* Effect.all([96+ diedWith(refsOf(code)),97+ diedWith(treeOf(code, none, none)),98+ diedWith(pathsOf(code, none)),99+ diedWith(fileOf(code, none, path)),100+ diedWith(logOf(code, { at: none, from: 0, limit: 30, path: none })),101+ diedWith(commitOf(code, sha)),102+ diedWith(whyOf(code, none, path)),103+ ])104+ ).toStrictEqual([105+ ...Array.from({ length: 6 }, () => Option.some("not built: 903")),106+ Option.some("not built: 912"),107+ ]);108+ })109+ );110+});added:packages/project/test/do-reads.test.ts+151 added
1+/**2+ * The four small reads the code browser and the people page take from a3+ * project's record: where main has landed, which commits are landings,4+ * which forks exist, and the policy as anyone may read it.5+ */6+import { describe, expect, it } from "@effect/vitest";7+import { Brand } from "@repo/brand";8+import { CheckSpec } from "@repo/protocol/domain/check";9+import { CommitSha, LaneName, RepoName, RepoPath } from "@repo/protocol/ids";10+import { Person } from "@repo/protocol/principal";11+import { advanceTo } from "@repo/testkit/clock";12+import type { Files } from "@repo/testkit/git-client";13+import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";14+import { Array, Effect, Layer, Option } from "effect";15+16+import { NoEnv } from "../src/env-port.ts";17+import { projectService } from "../src/project.ts";18+import { NoVisibility } from "../src/visibility-port.ts";19+import { CheckScript, composedAt, Pusher, worldOf } from "./world.ts";20+21+const scenario = aProject({ people: ["bob"] }).pipe(22+ withVouches(["bob"]),23+ withAsk({ id: "parse-iso", territory: "packages/parser" })24+);25+26+const { project } = scenario;27+28+const repo = RepoName.make(project);29+30+const alice = Person.make({ handle: scenario.initializer });31+32+const bob = Person.make({33+ handle: scenario.people.get("bob") ?? scenario.initializer,34+});35+36+const start: Files = [37+ ["package.json", '{ "name": "datekit", "workspaces": ["packages/*"] }\n'],38+ ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],39+];40+41+const parseIso = Option.getOrThrow(42+ Array.findFirst(scenario.policy.asks, (ask) => ask.id === "parse-iso")43+);44+45+const askFiles = Array.make(46+ { content: 'export default "parse-iso";\n', path: parseIso.file },47+ {48+ content: [49+ 'import { expect, it } from "vitest";',50+ 'import { parser } from "../src/parser.ts";',51+ "",52+ 'it("parse-iso", () => {',53+ ' expect(parser(" 2026 ")).toStrictEqual("2026");',54+ "});",55+ "",56+ ].join("\n"),57+ path: CheckSpec.guards.RedThenGreen(parseIso.check)58+ ? parseIso.check.path59+ : RepoPath.make(`${Brand.configDir}/checks/parse-iso.test.ts`),60+ }61+);62+63+/** A commit that is no landing: imported history, say. */64+const imported = CommitSha.make("b".repeat(40));65+66+const read = Effect.gen(function* () {67+ yield* advanceTo("2026-10-07T12:00:00Z");68+69+ const api = yield* projectService(project);70+71+ yield* api.initProject(alice, {});72+73+ const before = {74+ forks: yield* api.forks(),75+ head: yield* api.head(),76+ policy: yield* api.policy(),77+ };78+79+ const first = yield* Pusher.use((pusher) =>80+ pusher.push(repo, Option.none(), start, "Start")81+ );82+83+ const { landed: adopted } = yield* api.recordFirstPush(alice, first);84+ const composed = yield* composedAt(repo, adopted, askFiles);85+86+ yield* CheckScript.use((checker) =>87+ checker.script(composed, LaneName.make("redThenGreen"), [88+ "failed",89+ "failed",90+ ])91+ );92+93+ const { landed } = yield* api.openAsk(alice, {94+ ask: parseIso.id,95+ files: askFiles,96+ });97+98+ const { claim } = yield* api.claim(bob, parseIso.id);99+100+ return {101+ adopted,102+ after: {103+ forks: yield* api.forks(),104+ head: yield* api.head(),105+ landings: yield* api.landings([landed, imported]),106+ policy: yield* api.policy(),107+ },108+ before,109+ claim,110+ landed,111+ };112+});113+114+const world = Layer.mergeAll(worldOf(scenario, "memory"), NoVisibility, NoEnv);115+116+describe("a project's reads for its code and its people", () => {117+ it.effect(118+ "say where main landed, which commits are landings, the forks and the public policy",119+ () =>120+ Effect.map(read.pipe(Effect.provide(world)), (got) => {121+ expect(got.before).toStrictEqual({122+ forks: [],123+ head: {},124+ policy: Option.none(),125+ });126+ expect(got.after.head).toStrictEqual({ landed: got.landed });127+ // The ask's opening landed on the adoption; the other commit is none.128+ expect(129+ got.after.landings.map(({ parent, sha }) => ({ parent, sha }))130+ ).toStrictEqual([{ parent: got.adopted, sha: got.landed }]);131+ expect(got.after.forks).toStrictEqual([132+ {133+ ask: parseIso.id,134+ handle: bob.handle,135+ kind: "claim",136+ repo: got.claim.fork,137+ state: "live",138+ },139+ ]);140+141+ const policy = Option.getOrThrow(got.after.policy);142+143+ expect({144+ deciders: policy.deciders,145+ hidden: ["asks", "functions", "visibility"].filter(146+ (key) => key in policy147+ ),148+ }).toStrictEqual({ deciders: scenario.policy.deciders, hidden: [] });149+ })150+ );151+});added:packages/protocol/src/domain/code.ts+192 added
1+/**2+ * A project's code as its readers browse it: refs, trees, files, commits3+ * and "why" per line, each read from the project's canonical repo only (no4+ * payload names a repo). Every read names the 40-hex commit it resolved5+ * to (`at`), so any page can become a permalink.6+ */7+import { Schema } from "effect";8+9+import {10+ AskId,11+ BlobSha,12+ CommitSha,13+ Handle,14+ LandedSha,15+ ProjectName,16+ RepoName,17+ RepoPath,18+ TreeSha,19+} from "../ids.ts";20+import { ClaimState } from "./claim.ts";21+import { LandingView } from "./landing.ts";22+23+/** A tag's name, as `refs/tags/<name>` spells it: `v1.2.0`, `@changesets/cli@2.27.1`. */24+export const TagName = Schema.NonEmptyString.check(25+ Schema.isMaxLength(255)26+).pipe(Schema.brand("TagName"));27+28+export type TagName = typeof TagName.Type;29+30+/**31+ * A revision as a reader names it: `main` (the landed commit), a full32+ * 40-hex commit id, or a tag's name. Decoded into one of the three where33+ * it is read; anything else is `UnknownRevision`.34+ */35+export const Rev = Schema.String.check(36+ Schema.isMinLength(1),37+ Schema.isMaxLength(255)38+);39+40+export type Rev = typeof Rev.Type;41+42+/** One tag, peeled to the commit it names. */43+export const TagRef = Schema.Struct({ name: TagName, sha: CommitSha });44+45+export type TagRef = typeof TagRef.Type;46+47+/**48+ * One fork of the project: a claim's (`<project>--<ask>--<handle>`), with49+ * its ask and the claim's state, or a person's working fork.50+ */51+export const ForkRef = Schema.Struct({52+ ask: Schema.optionalKey(AskId),53+ handle: Handle,54+ kind: Schema.Literals(["claim", "working"]),55+ repo: RepoName,56+ state: Schema.optionalKey(ClaimState),57+});58+59+export type ForkRef = typeof ForkRef.Type;60+61+/** A project's refs as a reader sees them: main's landed commit, its tags and its forks. */62+export const RefsView = Schema.Struct({63+ forks: Schema.Array(ForkRef),64+ landed: Schema.optionalKey(LandedSha),65+ project: ProjectName,66+ tags: Schema.Array(TagRef),67+});68+69+export type RefsView = typeof RefsView.Type;70+71+/** One entry of a directory. */72+export const CodeEntry = Schema.Struct({73+ mode: Schema.String,74+ name: Schema.NonEmptyString,75+ path: RepoPath,76+ sha: Schema.String,77+ type: Schema.Literals(["blob", "tree", "submodule", "symlink"]),78+});79+80+export type CodeEntry = typeof CodeEntry.Type;81+82+/** One directory at one commit: folders first, then by name, and its README when it has one. */83+export const TreeListing = Schema.Struct({84+ at: CommitSha,85+ entries: Schema.Array(CodeEntry),86+ /** Absent for the root. */87+ path: Schema.optionalKey(RepoPath),88+ readme: Schema.optionalKey(Schema.Struct({ path: RepoPath, sha: BlobSha })),89+});90+91+export type TreeListing = typeof TreeListing.Type;92+93+/** Every file path at one commit, for a file tree; `truncated` past the cap. */94+export const PathList = Schema.Struct({95+ at: CommitSha,96+ paths: Schema.Array(RepoPath),97+ truncated: Schema.Boolean,98+});99+100+export type PathList = typeof PathList.Type;101+102+/**103+ * One file at one commit. `text` is absent for a binary file and for one104+ * past the size cap (`truncated`).105+ */106+export const FileView = Schema.Struct({107+ at: CommitSha,108+ binary: Schema.Boolean,109+ path: RepoPath,110+ sha: BlobSha,111+ size: Schema.Int,112+ text: Schema.optionalKey(Schema.String),113+ truncated: Schema.Boolean,114+});115+116+export type FileView = typeof FileView.Type;117+118+/** Who wrote or committed a commit, and when. */119+export const Signature = Schema.Struct({120+ at: Schema.DateTimeUtcFromString,121+ email: Schema.String,122+ name: Schema.String,123+});124+125+export type Signature = typeof Signature.Type;126+127+/**128+ * One commit as a reader sees it. `landing` is the platform's own record of129+ * it, when it is a landing: a trailer in an imported commit never makes one.130+ */131+export const CommitView = Schema.Struct({132+ author: Signature,133+ body: Schema.String,134+ committer: Signature,135+ landing: Schema.optionalKey(LandingView),136+ parents: Schema.Array(CommitSha),137+ sha: CommitSha,138+ subject: Schema.String,139+ trailers: Schema.Array(140+ Schema.Struct({ key: Schema.String, value: Schema.String })141+ ),142+ tree: TreeSha,143+});144+145+export type CommitView = typeof CommitView.Type;146+147+/** One file a commit changed, against its first parent. */148+export const ChangedFile = Schema.Struct({149+ after: Schema.optionalKey(BlobSha),150+ before: Schema.optionalKey(BlobSha),151+ binary: Schema.Boolean,152+ newText: Schema.optionalKey(Schema.String),153+ oldText: Schema.optionalKey(Schema.String),154+ path: RepoPath,155+ status: Schema.Literals(["added", "modified", "deleted"]),156+});157+158+export type ChangedFile = typeof ChangedFile.Type;159+160+/** A commit and what it changed; past the caps, paths only and `truncated`. */161+export const CommitDiff = Schema.Struct({162+ commit: CommitView,163+ files: Schema.Array(ChangedFile),164+ truncated: Schema.Boolean,165+});166+167+export type CommitDiff = typeof CommitDiff.Type;168+169+/** Lines `start` to `end` (1-based, inclusive) came in with commit `sha`. */170+export const WhyRange = Schema.Struct({171+ end: Schema.Int,172+ sha: CommitSha,173+ start: Schema.Int,174+});175+176+export type WhyRange = typeof WhyRange.Type;177+178+/**179+ * Why each line of a file is there: the first-parent commit that brought180+ * it, and that commit's landing when it is one. Lines older than the walk181+ * reached go to `stoppedAt`.182+ */183+export const WhyView = Schema.Struct({184+ at: CommitSha,185+ commits: Schema.Array(CommitView),186+ landings: Schema.Array(LandingView),187+ path: RepoPath,188+ ranges: Schema.Array(WhyRange),189+ stoppedAt: Schema.optionalKey(CommitSha),190+});191+192+export type WhyView = typeof WhyView.Type;modified:packages/protocol/src/domain/event.ts+2 added
28 unmodified lines29 Landed: { ...stamp, landing: LandingView },30 /** A claim lapsed: no push for too long. */31 Lapsed: { ...stamp, ask: AskId },32 LedgerAppended: { ...stamp, entry: LedgerEntry },33+ /** A proposal's draft settled: ready for a decider, or failed. */34+ ProposalDrafted: { ...stamp, proposal: ProposalId, ready: Schema.Boolean },35 ProposalOpened: { ...stamp, proposal: ProposalId },36 Pushed: { ...stamp, ask: AskId, head: CommitSha },37 /** A claim was released. */38 Released: { ...stamp, ask: AskId },5 unmodified linesmodified:packages/protocol/src/domain/policy.ts+11 added
108 unmodified lines109 110 export type Policy = typeof Policy.Type;111 112 /**113+ * A policy as anyone may read it: the evaluated config folder without its114+ * layers (the ledger shows those, and keeps the cartridge removable), its115+ * function-valued rules and its asks (`listAsks` lists them).116+ */117+export const PublicPolicy = Policy.mapFields(118+ Struct.omit(["asks", "functions", "visibility"])119+);120+121+export type PublicPolicy = typeof PublicPolicy.Type;122+123+/**124 * An ask as its file in the config folder states it: the platform adds its125 * project, when and in which landing it opened, and its state.126 */127 export const AskInput = Ask.mapFields(70 unmodified linesmodified:packages/protocol/src/domain/proposal.ts+27 added
2 unmodified lines3 import {4 AskId,5 CommitSha,6 Handle,7+ LaneName,8 ProjectName,9 ProposalId,10 RepoName,11 RepoPath,12 } from "../ids.ts";13+import { AtLeastOne } from "./common.ts";14 15 /** Where a proposal stands; an open one expires unless a decider accepts it. */16 export const ProposalState = Schema.Literals([17 "open",4 unmodified lines22 23 export type ProposalState = typeof ProposalState.Type;24 25 /**26+ * Where the platform's draft of a proposal's ask stands: drafting, ready27+ * (its check failed on main red first, in `lane`, the way `signature`28+ * says), or failed after its attempts, with the last refusal's tag.29+ */30+export const DraftState = Schema.TaggedUnion({31+ Drafting: { round: AtLeastOne, startedAt: Schema.DateTimeUtcFromString },32+ Failed: {33+ attempts: AtLeastOne,34+ model: Schema.NonEmptyString,35+ refusal: Schema.NonEmptyString,36+ round: AtLeastOne,37+ },38+ Ready: {39+ attempts: AtLeastOne,40+ model: Schema.NonEmptyString,41+ red: Schema.Struct({ lane: LaneName, signature: Schema.NonEmptyString }),42+ round: AtLeastOne,43+ },44+});45+46+export type DraftState = typeof DraftState.Type;47+48+/**49 * A proposal: a request to open an ask, from anyone not denounced, that50 * expires unless a decider accepts it. It may carry a sealed answer, judged51 * after the ask opens without the decider reading its diff.52 */53 export const Proposal = Schema.Struct({54+ /** The platform's draft of its ask, when the proposer asked for one. */55+ draft: Schema.optionalKey(DraftState),56 expiresAt: Schema.DateTimeUtcFromString,57 /** The proposed ask file and its check, held until the proposal is accepted. */58 files: Schema.Array(RepoPath),59 /** The existing ask this proposal flags, instead of a new one. */14 unmodified linesmodified:packages/protocol/src/cli.ts+23 added-3 removed
173 unmodified lines174 }175 176 interface FieldSpec {177 readonly description: string | undefined;178- readonly kind: "string" | "number" | "boolean" | "literals" | "json";178+ readonly kind:179+ | "string"180+ | "number"181+ | "boolean"182+ | "switch"183+ | "literals"184+ | "json";185 readonly literals: readonly string[];186 readonly optional: boolean;187 }188 42 unmodified lines231 return { description, kind: "json", literals: [], optional };232 }233 }234 235+ // A field that is `true` or absent is a switch: named, it is on.236+ if (SchemaAST.isLiteral(ast) && ast.literal === true) {237+ return { description, kind: "switch", literals: [], optional };238+ }239+240 const literal = literalOf(ast);241 242 if (literal !== undefined) {243 return { description, kind: "literals", literals: [literal], optional };18 unmodified lines262 : [];263 264 /** Whether a person must give the field: a switch is off unless named. */265 const isRequired = (spec: FieldSpec) =>255- !spec.optional && spec.kind !== "boolean";266+ !spec.optional && spec.kind !== "boolean" && spec.kind !== "switch";267 268 const jsonFlag = (name: string, field: Plain) =>269 Flag.String(name).pipe(270 Flag.withSchema(Schema.fromJsonString(field)),7 unmodified lines278 number: (name) => Flag.Finite(name),279 // The field's own schema checks the text, so a malformed value is refused280 // by the parser, naming its flag, before anything is called.281 string: (name, field) => Flag.String(name).pipe(Flag.withSchema(field)),282+ // On when named; left out of the payload otherwise.283+ switch: (name) =>284+ Flag.Boolean(name).pipe(285+ Flag.withDefault(false),286+ Flag.map((on) => (on ? true : undefined))287+ ),288 } satisfies Record<289 FieldSpec["kind"],290 (name: string, field: Plain, spec: FieldSpec) => Flag.Flag<unknown>291 >;24 unmodified lines316 317 const described =318 help === undefined ? base : base.pipe(Flag.withDescription(help));319 303- return (spec.optional || fallback !== undefined) && spec.kind !== "boolean"320+ return (spec.optional || fallback !== undefined) &&321+ spec.kind !== "boolean" &&322+ spec.kind !== "switch"323 ? described.pipe(Flag.optional, Flag.map(Option.getOrUndefined))324 : described;325 };326 8 unmodified lines335 json: (name, field) => schemaArgument(name, field, "JSON"),336 literals: (name, _field, spec) => Argument.Literals(name, spec.literals),337 number: (name) => Argument.Finite(name),338 string: (name) => Argument.String(name),339+ switch: (name, field) => schemaArgument(name, field, "true"),340 } satisfies Record<341 FieldSpec["kind"],342 (name: string, field: Plain, spec: FieldSpec) => Argument.Argument<unknown>343 >;342 unmodified linesmodified:packages/protocol/src/contracts.ts+283 added-3 removed
20 unmodified lines21 Verdict,22 } from "./domain/answer.ts";23 import { Ask, AskListing, Reserve } from "./domain/ask.ts";24 import { ClaimView } from "./domain/claim.ts";25+import {26+ CommitDiff,27+ CommitView,28+ PathList,29+ RefsView,30+ Rev,31+ FileView,32+ TreeListing,33+ WhyView,34+} from "./domain/code.ts";25-import { ConfigFile } from "./domain/common.ts";35+import { ConfigFile, NoneOrMore } from "./domain/common.ts";36 import { Choice, Decision, Today } from "./domain/decision.ts";37 import { EnvSchemaView } from "./domain/env.ts";38 import { ProjectEvent } from "./domain/event.ts";39 import { FrontPageEntry, ProjectListing } from "./domain/front-page.ts";40 import { LandingView } from "./domain/landing.ts";41+import { PublicPolicy } from "./domain/policy.ts";42 import { Proposal } from "./domain/proposal.ts";43 import { CreditSummary } from "./domain/record.ts";44 import { Ledger } from "./domain/visibility.ts";45 import {5 unmodified lines51 KindName,52 LandedSha,53 LaneName,54 ProjectName,55+ ProposalId,56 RepoName,57+ RepoPath,58 RequestId,59 } from "./ids.ts";60 import { Authenticated } from "./principal.ts";61 import {2 unmodified lines64 CapReached,65 ClaimLapsed,66 DecisionClosed,67 Denounced,68+ DraftInProgress,69 ImportFailed,70 IncompleteBrief,71 NotClaimed,72 NotDecider,2 unmodified lines75 NotVouched,76 OutOfScope,77 PrivatePathInPublicTree,78 ProjectExists,79+ ProposalClosed,80 ReachedInternals,81 RepoBusy,82 StaleBase,83 TouchedJudge,84 UnknownAsk,85 UnknownCommit,86 UnknownDecision,87 UnknownEnvItem,88+ UnknownPath,89 UnknownProject,90+ UnknownProposal,91+ UnknownRevision,92 ValueTooShort,93 VerifierBlocked,94 WeakCheck,95 Weakened,27 unmodified lines123 const servedOn = {124 claim: ["rpc", "mcp", "cli"],125 credits: SurfaceName.literals,126 decide: SurfaceName.literals,127+ draftAsk: SurfaceName.literals,128 [envSchemaTag]: SurfaceName.literals,129 // A log may hold text an agent's transcript should not carry: never MCP.130 evidence: ["rpc", "cli"],131 finish: ["rpc", "mcp", "cli"],4 unmodified lines136 land: ["rpc", "mcp", "cli"],137 landing: SurfaceName.literals,138 ledger: SurfaceName.literals,139 listAsks: SurfaceName.literals,140+ // The code reads: git already reads code locally, so no command or tool.141+ listPaths: ["rpc", "web"],142 listProjects: SurfaceName.literals,143+ listRefs: ["rpc", "web"],144+ log: ["rpc", "web"],145 openAsk: ["rpc", "mcp", "cli"],146+ projectPolicy: SurfaceName.literals,147 proposeAsk: SurfaceName.literals,148+ readFile: ["rpc", "web"],149+ readTree: ["rpc", "web"],150 release: ["rpc", "mcp", "cli"],151 // A value must never pass through an agent's transcript, so never MCP.152 setEnv: ["rpc", "cli"],153 showAsk: SurfaceName.literals,154+ showCommit: ["rpc", "web"],155+ showProposal: SurfaceName.literals,156 status: SurfaceName.literals,157 submitAnswer: ["rpc", "mcp", "cli"],158 today: SurfaceName.literals,159 verdict: SurfaceName.literals,160 vouch: ["rpc", "mcp", "cli"],161 // A stream has no tool or command form.162 watch: ["rpc", "web"],163+ why: ["rpc", "web"],164 } as const satisfies Record<string, readonly SurfaceName[]>;165 166 /**167 * The payload of a contract that takes nothing: an object with no keys. An236 unmodified lines404 .annotate(Destructive, false)405 .annotate(NeedsApproval, false)406 .annotate(Surfaces, servedOn.watch) {}407 408+// --- Code reads (the canonical repo only; git reads it locally too) --------409+410+export class ListRefs extends Rpc.make("listRefs", {411+ error: UnknownProject,412+ payload: { project: ProjectName },413+ success: RefsView,414+})415+ .annotate(416+ Description,417+ "List a project's refs: main's landed commit, its tags peeled to their commits, and its forks."418+ )419+ .annotate(Audience, "public")420+ .annotate(Visibility, "public")421+ .annotate(ReadOnly, true)422+ .annotate(Idempotent, true)423+ .annotate(Destructive, false)424+ .annotate(NeedsApproval, false)425+ .annotate(Surfaces, servedOn.listRefs) {}426+427+export class ReadTree extends Rpc.make("readTree", {428+ error: Schema.Union([UnknownProject, UnknownRevision, UnknownPath]),429+ payload: {430+ /** `main`, a commit or a tag; main's landed commit when absent. */431+ at: Schema.optionalKey(Rev),432+ /** The folder; the root when absent. */433+ path: Schema.optionalKey(RepoPath),434+ project: ProjectName,435+ },436+ success: TreeListing,437+})438+ .annotate(439+ Description,440+ "List one folder of a project at a revision, folders first, with its README when it has one."441+ )442+ .annotate(Audience, "public")443+ .annotate(Visibility, "public")444+ .annotate(ReadOnly, true)445+ .annotate(Idempotent, true)446+ .annotate(Destructive, false)447+ .annotate(NeedsApproval, false)448+ .annotate(Surfaces, servedOn.readTree) {}449+450+export class ListPaths extends Rpc.make("listPaths", {451+ error: Schema.Union([UnknownProject, UnknownRevision]),452+ payload: { at: Schema.optionalKey(Rev), project: ProjectName },453+ success: PathList,454+})455+ .annotate(456+ Description,457+ "List every file path in a project at a revision, up to a cap."458+ )459+ .annotate(Audience, "public")460+ .annotate(Visibility, "public")461+ .annotate(ReadOnly, true)462+ .annotate(Idempotent, true)463+ .annotate(Destructive, false)464+ .annotate(NeedsApproval, false)465+ .annotate(Surfaces, servedOn.listPaths) {}466+467+export class ReadFile extends Rpc.make("readFile", {468+ error: Schema.Union([UnknownProject, UnknownRevision, UnknownPath]),469+ payload: {470+ at: Schema.optionalKey(Rev),471+ path: RepoPath,472+ project: ProjectName,473+ },474+ success: FileView,475+})476+ .annotate(477+ Description,478+ "Read one file of a project at a revision: its text, or that it is binary or too large to show."479+ )480+ .annotate(Audience, "public")481+ .annotate(Visibility, "public")482+ .annotate(ReadOnly, true)483+ .annotate(Idempotent, true)484+ .annotate(Destructive, false)485+ .annotate(NeedsApproval, false)486+ .annotate(Surfaces, servedOn.readFile) {}487+488+export class LogOf extends Rpc.make("log", {489+ error: Schema.Union([UnknownProject, UnknownRevision]),490+ payload: {491+ at: Schema.optionalKey(Rev),492+ /** How many commits to skip: a page's `next`. */493+ from: Schema.optionalKey(NoneOrMore),494+ /** 30 when absent. */495+ limit: Schema.optionalKey(496+ Schema.Int.check(Schema.isBetween({ maximum: 100, minimum: 1 }))497+ ),498+ /** Only the commits that changed this path. */499+ path: Schema.optionalKey(RepoPath),500+ project: ProjectName,501+ },502+ success: Schema.Struct({503+ commits: Schema.Array(CommitView),504+ /** Where the next page starts; absent on the last. */505+ next: Schema.optionalKey(NoneOrMore),506+ }),507+})508+ .annotate(509+ Description,510+ "List a project's commits along first parents from a revision, newest first, each landing with its ask, people and verdict."511+ )512+ .annotate(Audience, "public")513+ .annotate(Visibility, "public")514+ .annotate(ReadOnly, true)515+ .annotate(Idempotent, true)516+ .annotate(Destructive, false)517+ .annotate(NeedsApproval, false)518+ .annotate(Surfaces, servedOn.log) {}519+520+export class ShowCommit extends Rpc.make("showCommit", {521+ error: Schema.Union([UnknownProject, UnknownCommit]),522+ payload: { project: ProjectName, sha: CommitSha },523+ success: CommitDiff,524+})525+ .annotate(526+ Description,527+ "Show one commit of a project and the files it changed against its first parent."528+ )529+ .annotate(Audience, "public")530+ .annotate(Visibility, "public")531+ .annotate(ReadOnly, true)532+ .annotate(Idempotent, true)533+ .annotate(Destructive, false)534+ .annotate(NeedsApproval, false)535+ .annotate(Surfaces, servedOn.showCommit) {}536+537+export class WhyOf extends Rpc.make("why", {538+ error: Schema.Union([UnknownProject, UnknownRevision, UnknownPath]),539+ payload: {540+ at: Schema.optionalKey(Rev),541+ path: RepoPath,542+ project: ProjectName,543+ },544+ success: WhyView,545+})546+ .annotate(547+ Description,548+ "Say why each line of a file is there: the commit that brought it, and the landing, ask and people behind that commit."549+ )550+ .annotate(Audience, "public")551+ .annotate(Visibility, "public")552+ .annotate(ReadOnly, true)553+ .annotate(Idempotent, true)554+ .annotate(Destructive, false)555+ .annotate(NeedsApproval, false)556+ .annotate(Surfaces, servedOn.why) {}557+558+export class PolicyOf extends Rpc.make("projectPolicy", {559+ error: UnknownProject,560+ payload: { project: ProjectName },561+ success: Schema.Struct({562+ /** Absent while the config folder at the landed commit has not evaluated. */563+ policy: Schema.optionalKey(PublicPolicy),564+ }),565+})566+ .annotate(567+ Description,568+ "Show a project's evaluated config folder at its landed commit: who decides which paths, its vouches, caps, budget and claim timing."569+ )570+ .annotate(Audience, "public")571+ .annotate(Visibility, "public")572+ .annotate(ReadOnly, true)573+ .annotate(Idempotent, true)574+ .annotate(Destructive, false)575+ .annotate(NeedsApproval, false)576+ .annotate(Cli, { name: "policy" })577+ .annotate(Surfaces, servedOn.projectPolicy) {}578+579+export class ShowProposal extends Rpc.make("showProposal", {580+ error: Schema.Union([UnknownProject, UnknownProposal]),581+ payload: { project: ProjectName, proposal: ProposalId },582+ success: Schema.Struct({583+ /** The files the proposal holds until a decider accepts it. */584+ files: Schema.Array(ConfigFile),585+ proposal: Proposal,586+ }),587+})588+ .annotate(589+ Description,590+ "Show one proposal, its draft's state and the ask files it holds."591+ )592+ .annotate(Audience, "public")593+ .annotate(Visibility, "public")594+ .annotate(ReadOnly, true)595+ .annotate(Idempotent, true)596+ .annotate(Destructive, false)597+ .annotate(NeedsApproval, false)598+ .annotate(Cli, { name: "proposal", positional: ["proposal"] })599+ .annotate(Surfaces, servedOn.showProposal) {}600+601 // --- Writes -----------------------------------------------------------------602 603 export class InitProject extends Rpc.make("initProject", {604 error: Schema.Union([ProjectExists, ImportFailed]),59 unmodified lines664 .annotate(NeedsApproval, true)665 .annotate(Cli, { name: "ask open", positional: ["ask"] })666 .annotate(Surfaces, servedOn.openAsk) {}667 668+/**669+ * A drafted proposal brings no files and no sealed answer: the platform's670+ * agent writes the ask's files.671+ */672+const draftsAlone = Schema.makeFilter(673+ (payload: {674+ readonly draft?: true;675+ readonly files?: unknown;676+ readonly sealed?: unknown;677+ }) =>678+ payload.draft === undefined ||679+ (payload.files === undefined && payload.sealed === undefined)680+ ? true681+ : "a drafted proposal carries neither files nor a sealed answer"682+);683+684 export class ProposeAsk extends Rpc.make("proposeAsk", {685 // `NotVouched` under the `all` mode, or for a sealed answer from someone686 // unvouched under `forCode` (a vouch admits sealed answers).687 error: Schema.Union([UnknownProject, Denounced, CapReached, NotVouched]),450- payload: {688+ payload: Schema.Struct({689+ /** Have the platform's agent draft the ask's files from the want. */690+ draft: Schema.optionalKey(Schema.Literal(true)),691 files: Schema.optionalKey(Schema.NonEmptyArray(ConfigFile)),692 project: ProjectName,693 /** A sealed answer: the commit in the caller's working fork that answers it. */694 sealed: Schema.optionalKey(Schema.Struct({ head: CommitSha })),695 territory: Schema.optionalKey(Schema.NonEmptyString),696 want: Schema.NonEmptyString,457- },697+ }).check(draftsAlone),698 success: Schema.Struct({ proposal: Proposal }),699 })700 .annotate(701 Description,7 unmodified lines709 .annotate(NeedsApproval, false)710 .annotate(Cli, { name: "propose" })711 .annotate(Surfaces, servedOn.proposeAsk) {}712 713+export class DraftAsk extends Rpc.make("draftAsk", {714+ error: Schema.Union([715+ UnknownProject,716+ UnknownProposal,717+ ProposalClosed,718+ NotDecider,719+ DraftInProgress,720+ CapReached,721+ ]),722+ payload: {723+ /** What the draft should do differently, for the agent to read. */724+ note: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(2000))),725+ project: ProjectName,726+ proposal: ProposalId,727+ },728+ success: Schema.Struct({ proposal: Proposal }),729+})730+ .annotate(731+ Description,732+ "Have the platform's agent draft, or draft again, an open proposal's ask and its failing check; the proposer or a decider may ask."733+ )734+ .annotate(Audience, "signedIn")735+ .annotate(Visibility, "public")736+ .annotate(ReadOnly, false)737+ .annotate(Idempotent, false)738+ .annotate(Destructive, false)739+ .annotate(NeedsApproval, false)740+ .annotate(Cli, { name: "ask draft", positional: ["proposal"] })741+ .annotate(Surfaces, servedOn.draftAsk) {}742+743 export class FlagAsk extends Rpc.make("flagAsk", {744 error: Schema.Union([UnknownProject, UnknownAsk, Denounced, CapReached]),745 payload: {746 ask: AskId,308 unmodified lines1055 TodayOf,1056 LedgerOf,1057 EnvSchemaOf,1058 Watch,1059+ ListRefs,1060+ ReadTree,1061+ ListPaths,1062+ ReadFile,1063+ LogOf,1064+ ShowCommit,1065+ WhyOf,1066+ PolicyOf,1067+ ShowProposal,1068 InitProject,1069 OpenAsk,1070 ProposeAsk,1071+ DraftAsk,1072 FlagAsk,1073 Decide,1074 Claim,1075 Release,70 unmodified linesmodified:packages/protocol/src/refusal.ts+47 added-1 removed
6 unmodified lines7 CommitSha,8 DecisionId,9 EnvKey,10 ProjectName,11+ ProposalId,12 RepoPath,13 } from "./ids.ts";14 import { Posture } from "./posture.ts";15 299 unmodified lines315 "DecisionClosed",316 { ...Final, ...nextIs(cli("today")), decision: DecisionId }317 ) {}318 319+/** The proposal was accepted, declined or expired, so nothing more is drafted for it. */320+export class ProposalClosed extends Schema.TaggedError<ProposalClosed>()(321+ "ProposalClosed",322+ { ...Final, ...nextIs(cli("today")), proposal: ProposalId }323+) {}324+325+/** The platform is drafting this proposal's ask already; its page says when it settles. */326+export class DraftInProgress extends Schema.TaggedError<DraftInProgress>()(327+ "DraftInProgress",328+ { ...Retryable, proposal: ProposalId }329+) {330+ static readonly of = (proposal: ProposalId) =>331+ new DraftInProgress({ next: cli("proposal", proposal), proposal });332+}333+334 // Lookup335 336 /** No project has this name. */337 export class UnknownProject extends Schema.TaggedError<UnknownProject>()(19 unmodified lines357 "UnknownDecision",358 { ...Final, ...nextIs(cli("today")), decision: DecisionId }359 ) {}360 361+/**362+ * The project has no file or folder at this path at this commit. The363+ * commit is `commit`: `at` points at a line, as on every refusal.364+ */365+export class UnknownPath extends Schema.TaggedError<UnknownPath>()(366+ "UnknownPath",367+ { ...Final, ...nextIs("git ls-tree"), commit: CommitSha, path: RepoPath }368+) {}369+370+/** Neither `main`, a commit the project holds, nor one of its tags. */371+export class UnknownRevision extends Schema.TaggedError<UnknownRevision>()(372+ "UnknownRevision",373+ { ...Final, ...nextIs("git ls-remote"), rev: Schema.String }374+) {}375+376+/** The project has no proposal with this id. */377+export class UnknownProposal extends Schema.TaggedError<UnknownProposal>()(378+ "UnknownProposal",379+ { ...Final, ...nextIs(cli("today")), proposal: ProposalId }380+) {}381+382 // Setup383 384 /** A project with this name already exists. */385 export class ProjectExists extends Schema.TaggedError<ProjectExists>()(76 unmodified lines462 SecretInOutput,463 UnstatedRequirement,464 ] as const;465 429-const decision = [PostureChange, NotDecider, DecisionClosed] as const;466+const decision = [467+ PostureChange,468+ NotDecider,469+ DecisionClosed,470+ ProposalClosed,471+ DraftInProgress,472+] as const;473 474 const lookup = [475 UnknownProject,476 UnknownAsk,477 UnknownCommit,478 UnknownDecision,479+ UnknownPath,480+ UnknownRevision,481+ UnknownProposal,482 ] as const;483 484 const setup = [ProjectExists, ImportFailed] as const;485 36 unmodified linesmodified:packages/protocol/src/render.ts+9 added
31 unmodified lines32 Denounced: () =>33 "this project's vouch file denounces you, so it takes no claims or proposals from you",34 DirectPush: ({ ref }) =>35 `main moves only by a landing, so ${ref} takes no direct push; push your answer to your claim's fork`,36+ DraftInProgress: ({ proposal }) =>37+ `the platform is already drafting ${proposal}'s ask`,38 Flake: ({ lane }) =>39 `the ${lane} checks failed, then passed on the same tree; the platform will run them again`,40 HeldBackFailed: ({ area, suite }) =>41 `a held-back check failed in ${area}, suite ${suite}`,15 unmodified lines57 `landing would change the posture from ${from} to ${to}, which takes a decider`,58 PrivatePathInPublicTree: ({ paths }) =>59 `would put held-back paths in a public tree: ${list(paths)}; those paths belong to a layer, so remove them from the answer`,60 ProjectExists: ({ project }) => `a project named ${project} already exists`,61+ ProposalClosed: ({ proposal }) =>62+ `${proposal} was already accepted, declined or expired`,63 ReachedInternals: ({ from, to }) =>64 `${from} reaches into ${to}, which its module does not export; import it through that module's public exports instead`,65 RepoBusy: () => "the repo was busy with another push",66 SecretInOutput: ({ item, where }) =>9 unmodified lines76 UnknownAsk: ({ ask }) => `this project has no ask named ${ask}`,77 UnknownCommit: ({ sha }) => `this project has no commit ${sha}`,78 UnknownDecision: ({ decision }) => `this project has no decision ${decision}`,79 UnknownEnvItem: ({ key }) => `the env shape has no item ${key}`,80+ UnknownPath: ({ commit, path }) =>81+ `${short(commit)} has no file or folder at ${path}`,82 UnknownProject: ({ project }) => `no project is named ${project}`,83+ UnknownProposal: ({ proposal }) => `this project has no proposal ${proposal}`,84+ UnknownRevision: ({ rev }) =>85+ `${rev} is neither main, a commit this project holds, nor one of its tags`,86 UnstatedRequirement: ({ area }) =>87 `a held-back check in ${area} enforces something no public clause states`,88 ValueTooShort: ({ key, minimum }) =>89 `the value for ${key} is shorter than the ${minimum} characters it needs`,69 unmodified linesmodified:packages/protocol/src/testing.ts+10 added
31 unmodified lines32 export const unanswered = Contracts.toLayer({33 claim: uncalled,34 credits: uncalled,35 decide: uncalled,36+ draftAsk: uncalled,37 // Keyed by the class: lint keeps "shape" out of code names.38 [EnvSchemaOf._tag]: uncalled,39 evidence: uncalled,40 finish: uncalled,4 unmodified lines45 land: uncalled,46 landing: uncalled,47 ledger: uncalled,48 listAsks: uncalled,49+ listPaths: uncalled,50 listProjects: uncalled,51+ listRefs: uncalled,52+ log: uncalled,53 openAsk: uncalled,54+ projectPolicy: uncalled,55 proposeAsk: uncalled,56+ readFile: uncalled,57+ readTree: uncalled,58 release: uncalled,59 setEnv: uncalled,60 showAsk: uncalled,61+ showCommit: uncalled,62+ showProposal: uncalled,63 status: uncalled,64 submitAnswer: uncalled,65 today: uncalled,66 verdict: uncalled,67 vouch: uncalled,68 watch: uncalled,69+ why: uncalled,70 });modified:packages/protocol/test/fixtures/contracts.jsonnot shown
Its text is not shown, modified.
modified:packages/protocol/test/cli.test.ts+42 added-1 removed
20 unmodified lines21 Decide,22 ListAsks,23 ListProjects,24 OpenAsk,25+ ProposeAsk,26 ShowAsk,27 SubmitAnswer,28 } from "../src/contracts.ts";29 import { Outcome } from "../src/domain/outcome.ts";4 unmodified lines34 KindName,35 ProjectName,36 RequestId,37 } from "../src/ids.ts";37-import { AskFull, DecisionClosed, StaleBase } from "../src/refusal.ts";38+import {39+ AskFull,40+ CapReached,41+ DecisionClosed,42+ StaleBase,43+} from "../src/refusal.ts";44 import { asTester, unanswered } from "../src/testing.ts";45 import { ask, base, main, path } from "./examples.ts";46 47 const head = CommitSha.make("3333333333333333333333333333333333333333");283 unmodified lines331 ]);332 })333 );334 335+ // A field that is `true` or absent takes a bare switch: `--draft`.336+ it.effect(337+ "takes a switch as on when named, and leaves it out otherwise",338+ () =>339+ Effect.gen(function* () {340+ const proposed = yield* Ref.make<readonly unknown[]>([]);341+342+ const propose = (args: readonly string[]) =>343+ run(344+ Layer.mergeAll(345+ unanswered,346+ Contracts.toLayerHandler("proposeAsk", (payload) =>347+ Ref.update(proposed, (all) => [...all, payload]).pipe(348+ Effect.andThen(Effect.fail(new CapReached({ cap: 2 })))349+ )350+ )351+ ),352+ (output) =>353+ toCommand(ProposeAsk, Effect.service(Client), { output }),354+ ["--project", project, "--want", "Parse ISO weeks.", ...args]355+ );356+357+ yield* propose(["--draft"]);358+ yield* propose([]);359+360+ expect(yield* Ref.get(proposed)).toStrictEqual([361+ { draft: true, project, want: "Parse ISO weeks." },362+ { project, want: "Parse ISO weeks." },363+ ]);364+ })365+ );366+367 it("takes the last word of a two-word name as its own", () => {368 const output = Effect.succeed<CommandOutput>({369 plan: () => Effect.void,370 refused: () => Effect.void,226 unmodified lines597 "credits",598 "today",599 "ledger",600 "env shape",601+ "policy",602+ "proposal",603 "ask open",604 "propose",605+ "ask draft",606 "ask flag",607 "decide",608 "claim",609 "release",23 unmodified linesmodified:packages/protocol/test/contracts.test.ts+122 added-2 removed
16 unmodified lines17 } from "../src/annotations.ts";18 import {19 Contracts,20 partsOf,21+ ProposeAsk,22 SetEnv,23 surfaced,24 Watch,25 } from "../src/contracts.ts";106 unmodified lines132 on: "RW",133 tag: "watch",134 },135 {136+ audience: "public",137+ cli: "none",138+ errors: ["UnknownProject"],139+ flags: "RI",140+ on: "RW",141+ tag: "listRefs",142+ },143+ {144+ audience: "public",145+ cli: "none",146+ errors: ["UnknownProject", "UnknownRevision", "UnknownPath"],147+ flags: "RI",148+ on: "RW",149+ tag: "readTree",150+ },151+ {152+ audience: "public",153+ cli: "none",154+ errors: ["UnknownProject", "UnknownRevision"],155+ flags: "RI",156+ on: "RW",157+ tag: "listPaths",158+ },159+ {160+ audience: "public",161+ cli: "none",162+ errors: ["UnknownProject", "UnknownRevision", "UnknownPath"],163+ flags: "RI",164+ on: "RW",165+ tag: "readFile",166+ },167+ {168+ audience: "public",169+ cli: "none",170+ errors: ["UnknownProject", "UnknownRevision"],171+ flags: "RI",172+ on: "RW",173+ tag: "log",174+ },175+ {176+ audience: "public",177+ cli: "none",178+ errors: ["UnknownProject", "UnknownCommit"],179+ flags: "RI",180+ on: "RW",181+ tag: "showCommit",182+ },183+ {184+ audience: "public",185+ cli: "none",186+ errors: ["UnknownProject", "UnknownRevision", "UnknownPath"],187+ flags: "RI",188+ on: "RW",189+ tag: "why",190+ },191+ {192+ audience: "public",193+ cli: "policy",194+ errors: ["UnknownProject"],195+ flags: "RI",196+ on: "RMCW",197+ tag: "projectPolicy",198+ },199+ {200+ audience: "public",201+ cli: "proposal <proposal>",202+ errors: ["UnknownProject", "UnknownProposal"],203+ flags: "RI",204+ on: "RMCW",205+ tag: "showProposal",206+ },207+ {208 audience: "signedIn",209 cli: "init",210 errors: ["ProjectExists", "ImportFailed"],211 flags: "A",26 unmodified lines238 tag: "proposeAsk",239 },240 {241 audience: "signedIn",242+ cli: "ask draft <proposal>",243+ errors: [244+ "UnknownProject",245+ "UnknownProposal",246+ "ProposalClosed",247+ "NotDecider",248+ "DraftInProgress",249+ "CapReached",250+ ],251+ flags: "",252+ on: "RMCW",253+ tag: "draftAsk",254+ },255+ {256+ audience: "signedIn",257 cli: "ask flag <ask>",258 errors: ["UnknownProject", "UnknownAsk", "Denounced", "CapReached"],259 flags: "",260 on: "RMC",118 unmodified lines379 tag: "setEnv",380 },381 ] as const;382 383+/** Whether `proposeAsk` takes `payload`: `Some` when it decodes. */384+const decodes = (payload: typeof Schema.Json.Type) =>385+ Schema.decodeUnknownOption(ProposeAsk.payloadSchema)(payload)._tag;386+387+/** The code reads: on RPC and the web only (git reads code locally). */388+type CodeRead =389+ | "listPaths"390+ | "listRefs"391+ | "log"392+ | "readFile"393+ | "readTree"394+ | "showCommit"395+ | "why";396+397 /** Each surface's letter in the table's Surfaces column. */398 const letterOf = {399 cli: "C",400 mcp: "M",177 unmodified lines578 expect(JSON.stringify(decoded)).toContain('"value":"<redacted>"');579 expect(JSON.stringify(decoded)).not.toContain(encoded.value);580 });581 582+ // The platform's agent writes a drafted proposal's files, so one that583+ // brings its own, or a sealed answer, is refused at the boundary.584+ it("takes a drafted proposal with no files and no sealed answer", () => {585+ const want = { project: "datekit", want: "Parse ISO weeks." };586+587+ const files = [{ content: "x", path: "config/asks/a.ask.ts" }];588+589+ const sealed = { head: "3".repeat(40) };590+591+ expect([592+ decodes({ ...want, draft: true }),593+ decodes({ ...want, draft: true, files }),594+ decodes({ ...want, draft: true, sealed }),595+ decodes({ ...want, files }),596+ decodes({ ...want, draft: false }),597+ ]).toStrictEqual(["Some", "None", "None", "Some", "None"]);598+ });599+600 it("streams a project's events from watch", () => {601 expect(RpcSchema.isStreamSchema(Watch.successSchema)).toBeTruthy();602 expect(Watch.successSchema.success).toBe(ProjectEvent);603 });15 unmodified lines619 // annotations come from, so a tool or command the type names exists.620 it("types each surface's group as the contracts on it", () => {621 expectTypeOf<TagOn<"rpc">>().toEqualTypeOf<Contract["_tag"]>();622 expectTypeOf<TagOn<"mcp">>().toEqualTypeOf<503- Exclude<Contract["_tag"], "evidence" | "setEnv" | "watch">623+ Exclude<Contract["_tag"], CodeRead | "evidence" | "setEnv" | "watch">624 >();625 expectTypeOf<TagOn<"cli">>().toEqualTypeOf<506- Exclude<Contract["_tag"], "watch">626+ Exclude<Contract["_tag"], CodeRead | "watch">627 >();628 });629 630 it("never gives MCP a stream, a contract that carries a write-only value, or a lane's log", () => {11 unmodified linesmodified:packages/protocol/test/examples.ts+13 added
4 unmodified lines5 CommitSha,6 DecisionId,7 EnvKey,8 ProjectName,9+ ProposalId,10 RepoPath,11 } from "../src/ids.ts";12 import {13 AskBlocked,4 unmodified lines18 ClaimLapsed,19 DecisionClosed,20 Denounced,21 DirectPush,22+ DraftInProgress,23 Flake,24 HeldBackFailed,25 ImportFailed,26 IncompleteBrief,7 unmodified lines34 OutOfScope,35 PostureChange,36 PrivatePathInPublicTree,37 ProjectExists,38+ ProposalClosed,39 ReachedInternals,40 RepoBusy,41 SecretInOutput,42 StaleBase,2 unmodified lines45 UnknownAsk,46 UnknownCommit,47 UnknownDecision,48 UnknownEnvItem,49+ UnknownPath,50 UnknownProject,51+ UnknownProposal,52+ UnknownRevision,53 UnstatedRequirement,54 ValueTooShort,55 VerifierBlocked,56 WeakCheck,14 unmodified lines71 const decision = DecisionId.make("dec-000001");72 73 const key = EnvKey.make("PAYMENTS_KEY");74 75+const proposal = ProposalId.make("prop-000001");76+77 // One of each member, in the union's order.78 export const examples: readonly Refusal[] = [79 NotClaimed.of(ask),80 ClaimLapsed.of(ask),39 unmodified lines120 new UnstatedRequirement({ area: "parser" }),121 new PostureChange({ from: "open", to: "openCore" }),122 new NotDecider({}),123 new DecisionClosed({ decision }),124+ new ProposalClosed({ proposal }),125+ DraftInProgress.of(proposal),126 new UnknownProject({ project }),127 new UnknownAsk({ ask }),128 new UnknownCommit({ sha: main }),129 new UnknownDecision({ decision }),130+ new UnknownPath({ commit: main, path }),131+ new UnknownRevision({ rev: "v9.9.9" }),132+ new UnknownProposal({ proposal }),133 new ProjectExists({ project }),134 new ImportFailed({ reason: "the repo needs a sign-in to read" }),135 new UnknownEnvItem({ key }),136 new NotSensitive({ key }),2 unmodified linesmodified:packages/protocol/test/refusal.test.tsnot shown
Its text is not shown, modified.
modified:packages/protocol/test/render.test.tsnot shown
Its text is not shown, modified.
modified:packages/testkit/src/fake-artifacts-binding.tsnot shown
Its text is not shown, modified.
modified:packages/testkit/test/fake-artifacts-binding.test.tsnot shown
Its text is not shown, modified.
modified:scripts/lib/swarm/views/counter.tsnot shown
Its text is not shown, modified.
added:scripts/import-examples.tsnot shown
Its text is not shown, added.
modified:scripts/startup-budget.tsnot shown
Its text is not shown, modified.
modified:AGENTS.md+1 added
64 unmodified lines65 - `bootstrap -- --stage <stage>`: makes a stage's Cloudflare resources; a second run creates nothing, and `--dry-run` only prints the plan.66 - `deploy -- --stage <stage>`: the one way to deploy. It runs `verify`, deploys the three Workers with Wrangler, reads the push trigger back, then runs `smoke`.67 - `smoke -- --stage <stage>`: read-only probes against a live stage. `--loop` then runs the whole core loop on a throwaway project, `smoke-<run>`, through the CLI and git, and refuses `demo`.68 - `seed`: puts the two example projects on a platform (`--world node` on this machine, or `--stage <stage>`); a second run changes nothing. `--only <example> --as <name>` seeds a fresh copy under another name, and refuses a taken one.69+- `import-examples -- --stage <stage>`: imports the open-source repos the code browser is previewed on, one at a time, onto a stage other than `demo`, each recorded in the ledger as kept. Until its body lands it says so and exits 1.70 - `swarm -- --stage <stage> --project <name>`: plans six fictional contributors, on four harnesses, against one split family on a stage, claims each one's ask, prepares a workspace with a clone of its fork outside the checkout, starts each harness headless on the brief and sends every refusal back into the same session, at most three times, then writes the run's summary; `--view herdr` runs them in herdr panes beside a counter, and `--dry-run` only prints the plan.71 - `release -- --build | --upload --stage <stage> | --publish`: builds the CLI's npm package and two binaries, uploads a release to the stage's own bucket, which the platform serves, and leaves `npm publish` to a person: under an agent it prints the command instead.72 73 ## Nouns73 unmodified linesmodified:bun.lock+23 added
59 unmodified lines60 "@repo/agent-kit": "workspace:*",61 "@repo/artifacts": "workspace:*",62 "@repo/brand": "workspace:*",63 "@repo/checks": "workspace:*",64+ "@repo/drafting": "workspace:*",65 "@repo/gate": "workspace:*",66 "@repo/git": "workspace:*",67 "@repo/project": "workspace:*",68 "@repo/protocol": "workspace:*",64 unmodified lines133 "@playwright/test": "1.63.0",134 "@repo/artifacts": "workspace:*",135 "@repo/checks": "workspace:*",136 "@repo/config": "workspace:*",137+ "@repo/drafting": "workspace:*",138 "@repo/git": "workspace:*",139 "@repo/project": "workspace:*",140 "@repo/rules": "workspace:*",141 "@repo/testkit": "workspace:*",83 unmodified lines225 "typescript": "catalog:",226 "vitest": "catalog:",227 },228 },229+ "packages/drafting": {230+ "name": "@repo/drafting",231+ "dependencies": {232+ "@repo/artifacts": "workspace:*",233+ "@repo/brand": "workspace:*",234+ "@repo/project": "workspace:*",235+ "@repo/protocol": "workspace:*",236+ "effect": "catalog:",237+ },238+ "devDependencies": {239+ "@cloudflare/workers-types": "5.20261006.1",240+ "@effect/vitest": "catalog:",241+ "@repo/config": "workspace:*",242+ "@repo/rules": "workspace:*",243+ "@repo/testkit": "workspace:*",244+ "typescript": "catalog:",245+ "vitest": "catalog:",246+ },247+ },248 "packages/gate": {249 "name": "@repo/gate",250 "dependencies": {251 "@repo/protocol": "workspace:*",648 unmodified lines900 "@repo/cli": ["@repo/cli@workspace:apps/cli"],901 902 "@repo/config": ["@repo/config@workspace:packages/config"],903 904+ "@repo/drafting": ["@repo/drafting@workspace:packages/drafting"],905+906 "@repo/gate": ["@repo/gate@workspace:packages/gate"],907 908 "@repo/git": ["@repo/git@workspace:packages/git"],909 1535 unmodified linesmodified:package.json+1 added
29 unmodified lines30 "bootstrap": "varlock run --path infra/ -- bun infra/bootstrap.ts",31 "deploy": "bun infra/deploy.ts",32 "smoke": "bun scripts/smoke.ts",33 "seed": "bun scripts/seed.ts",34+ "import-examples": "bun scripts/import-examples.ts",35 "swarm": "bun scripts/swarm.ts",36 "release": "bun scripts/release.ts",37 "verify": "bun run lockfile:check && bun run check && bun run typecheck && bun run test && bun run brand:check && bun run bytes:check"38 },20 unmodified linesmodified:tsconfig.base.jsonnot shown
Its text is not shown, modified.