Skip to content
Myr

Merge project/drop-proposals into main

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents d2cc800, 0aebc3f · Browse files · 249 files+984 added−4422 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

249 files+984 added−4422 removed

  • tests:+211 added−1405 removed
  • other:+773 added−3017 removed

249 files+984 added−4422 removed

This commit is too large to show whole: its files are listed by path, without their changes.

modified:apps/cli/src/entries/rules.ts-3 removed
24 unmodified lines
25 functionsOf,26 kind,27 type KindBuilder,28 type KindDefinition,29 type KindFunctions,29 type KindHandle,30 kinds,31 layer,32 type LayerConfig,
2 unmodified lines
35 layerManifest,36 type LayerManifestDefinition,37 type MembersInput,38 type ModulesInput,40 type OpensAlone,39 packageDir,40 personal,41 project,42 type ProjectConfig,43 type ProjectDefinition,44 type ProjectFunctions,47 ProposalFacts,45 type RatchetEntry,46 type RatchetMeasure,47 run,48 type RunBlockInput,
18 unmodified lines
modified:apps/cli/src/local/ask-open.ts+13 added-2 removed
2 unmodified lines
3import { Brand } from "@repo/brand";4import { ApprovalNeeded } from "@repo/protocol/cli";5import { Client, OpenAsk } from "@repo/protocol/contracts";6import { ConfigFile } from "@repo/protocol/domain/common";7import { AskId, ProjectName } from "@repo/protocol/ids";7import { AskId, DiscussionId, ProjectName } from "@repo/protocol/ids";8import { Effect, FileSystem, Option, Path, Schema } from "effect";9import { Argument, Command, Flag } from "effect/cli";1011import { Output } from "../output.ts";
69 unmodified lines
81 ask: Argument.String("ask").pipe(82 Argument.withSchema(AskId),83 Argument.withDescription("The ask to open: its file is asks/<ask>.ask.ts")84 ),85 discussion: Flag.String("discussion").pipe(86 Flag.withSchema(DiscussionId),87 Flag.optional,88 Flag.withDescription(89 "The discussion this ask comes from; opening it marks the thread asked"90 )91 ),92 dryRun: Flag.Boolean("dry-run").pipe(93 Flag.withDefault(false),94 Flag.withDescription("Print the payload it would send, and send nothing")95 ),
54 unmodified lines
150 const payload: Payload = yield* decodePayload({151 ask,152 files,153 project,154 ...Option.match(flags.discussion, {155 onNone: () => ({}),156 onSome: (discussion) => ({ discussion }),157 }),158 }).pipe(Effect.catch((error) => usage(String(error))));159160 const output = yield* Output;161
16 unmodified lines
178 });179 }).pipe(reportRefusals(COMMAND, flags.json))180).pipe(181 Command.withDescription(171 `Open an ask by landing its file and its check, read from the ask's own file under ${Brand.configDir}/asks/ and the path it names unless --files gives them, once the check fails on main by an assertion, twice in the same way.`182 `Open an ask by landing its file and its check, read from the ask's own file under ${Brand.configDir}/asks/ and the path it names unless --files gives them, once the check fails on main by an assertion, twice in the same way; --discussion names the thread it comes from, and marks it asked.`183 )184);
modified:apps/cli/src/local/init.ts+1 added-1 removed
31 unmodified lines
32const SUBJECT = `Add ${CONFIG}: the run block ${Brand.cli} ${COMMAND} found`;3334const PENDING = { origin: "<platform>", remote: "<remote>" } as const;3536const NEXT = `Next: write an ask in ${Brand.configDir}/asks/<ask>.ask.ts, with its failing test under ${ASKS_DIR}/, then ${Brand.cli} ask open <ask>; or ${Brand.cli} propose --want "<what should be true>" --draft.`;36const NEXT = `Next: write an ask in ${Brand.configDir}/asks/<ask>.ask.ts, with its failing test under ${ASKS_DIR}/, then ${Brand.cli} ask open <ask>.`;3738/** The CLI knows the platform's address alone; the web shows the project at the same path. */39const pageLine = (project: string, remote: string) =>40 Option.match(parseRemote(remote), {
493 unmodified lines
modified:apps/cli/src/tui/today.ts-1 removed
78 unmodified lines
7980export const choicesFor = (decision: Decision): readonly ChoiceKey[] =>81 DecisionSubject.match(decision.subject, {82 Finish: () => yesOrNo,83 OpenProposal: () => yesOrNo,83 PostureChange: () => yesOrNo,84 ProxyWidened: () => yesOrNo,85 RaiseRatchet: () => yesOrNo,86 SecretInTree: () => yesOrNo,
118 unmodified lines
modified:apps/cli/src/tui/view.ts-1 removed
14 unmodified lines
15const refWords = (ref: string) => ref.replace(/^refs\/heads\//u, "");1617const about = DecisionSubject.match({18 Finish: ({ ask, head }) => `finish the answer to ${ask} at ${short(head)}`,19 OpenProposal: ({ proposal }) => `open the ask ${proposal} proposes`,19 PostureChange: ({ from, to }) => `change the posture from ${from} to ${to}`,20 ProxyWidened: ({ hosts, item }) =>21 `let ${item} reach ${hosts.join(", ")} through the platform's proxy`,22 RaiseRatchet: ({ after, ask, before, ratchet, territory }) =>
156 unmodified lines
modified:apps/cli/src/render.ts+11 added-19 removed
133 unmodified lines
134135const subjectText = (subject: DecisionSubject) =>136 DecisionSubject.match(subject, {137 Finish: ({ ask, head }) => `finish the answer to ${ask} at ${short(head)}`,138 OpenProposal: ({ proposal }) =>139 `open the ask proposal ${proposal} asks for`,138 PostureChange: ({ from, to }) => `change the posture from ${from} to ${to}`,139 ProxyWidened: ({ hosts, item }) =>140 `let ${item}'s placeholder reach ${hosts.join(", ")}`,141 RaiseRatchet: ({ after, before, ratchet, territory }) =>
59 unmodified lines
201202const ask = viewOf(ShowAsk.successSchema, ({ brief }) => prose(brief));203204const discussionStates = {205 asked: "became the ask",206 closed: "closed",207 open: "open",209 proposed: "became a proposal",208} as const satisfies Record<Discussion["state"], string>;209210const discussions = viewOf(211 ListDiscussions.successSchema,
1 unmodified line
213 joined(214 table(215 ["discussion", "title", "opener", "posts", "last post", "state"],216 listed.map(219 ({ id, lastPostAt, opener, posts, proposal, state, title }) => [217 ({ ask: became, id, lastPostAt, opener, posts, state, title }) => [218 id,219 title,220 opener,221 String(posts),222 when(lastPostAt),225 proposal === undefined223 became === undefined224 ? discussionStates[state]227 : `${discussionStates[state]} ${proposal}`,225 : `${discussionStates[state]} ${became}`,226 ]227 ),228 "No discussions yet."229 ),
7 unmodified lines
237 if (discussion.state === "open") {238 return `Reply with \`${Brand.cli} discussion post ${discussion.id} --body "<post>"\`.`;239 }240243 return discussion.proposal === undefined241 return discussion.ask === undefined242 ? "This discussion is closed."245 : `This discussion became ${discussion.proposal}: read it with \`${Brand.cli} proposal ${discussion.proposal}\`.`;243 : `This discussion became the ask ${discussion.ask}: read it with \`${Brand.cli} ask ${discussion.ask}\`.`;244};245246const thread = (discussion: Discussion): View =>247 joined(
2 unmodified lines
250 ["Discussion", discussion.id],251 ["Opened by", `${discussion.opener} at ${when(discussion.openedAt)}`],252 [253 "State",256 discussion.proposal === undefined254 discussion.ask === undefined255 ? discussionStates[discussion.state]258 : `${discussionStates[discussion.state]} ${discussion.proposal}`,256 : `${discussionStates[discussion.state]} ${discussion.ask}`,257 ],258 ]),259 ...discussion.posts.map(({ at, body, by }) =>260 prose(`**${by}** at ${when(at)}\n\n${body}`)
203 unmodified lines
464465const PROJECT_FILE = `${Brand.configDir}/project.ts`;466467const vouchModes = {470 all: "For everything: claiming an ask, offering a sealed answer and proposing an ask all need a vouch.",468 all: "For everything, which today gates what for code does: claiming an ask needs a vouch; anyone not denounced may post in a discussion.",469 bansOnly:472 "Bans only: nobody needs a vouch, but a denounced person still may not claim, push or propose.",470 "Bans only: nobody needs a vouch, but a denounced person still may not claim, push or post.",471 forCode:474 "For code: claiming an ask or offering a sealed answer needs a vouch; anyone not denounced may propose an ask.",472 "For code: claiming an ask needs a vouch; anyone not denounced may post in discussions.",473} as const satisfies Record<PublicPolicy["vouch"]["mode"], string>;474475const evaluated = (policy: PublicPolicy) => {476 const { agents, caps, claims, decisions, record, vouch, vouches } = policy;
21 unmodified lines
498 "Claims",499 `${plural(caps.claimsPerPerson, "claim", "claims")} at once for a person nobody has vouched for; a vouched person and a maintainer are never held`,500 ],501 [504 "Proposals",505 caps.proposalsPerPerson === 0506 ? "Proposals are off"507 : `${plural(caps.proposalsPerPerson, "proposal", "proposals")} open at once for a person nobody has vouched for`,508 ],509 [502 "Decisions",503 `an undecided one takes its default after ${plural(decisions.expireDays, "day", "days")}`,504 ],505 [
162 unmodified lines
modified:apps/cli/test/fixtures/check/policy.json+1 added-1 removed
13 unmodified lines
14 "territory": { "module": "a", "paths": ["{dir}/**"] }15 }16 ],17 "deciders": [{ "handles": "owners", "paths": "**" }],18 "functions": { "admit": false, "opensAlone": false },18 "functions": { "admit": false },19 "kinds": [20 {21 "checkKind": "redThenGreen",22 "claimers": "anyone",
16 unmodified lines
modified:apps/cli/test/local/ask-open.test.ts+30 added
222 unmodified lines
223 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),224 { timeout: 30_000 }225 );226227 it.live(228 "sends the discussion --discussion names, so the thread it came from is marked asked",229 () =>230 Effect.gen(function* () {231 const repo = yield* aRepo({});232 const platform = yield* aPlatform(Effect.succeed(opened));233234 const given = [{ content: "given", path: ASK_FILE }];235236 const ran = yield* cli(repo, platform.layer, [237 ...argv,238 "--files",239 JSON.stringify(given),240 "--discussion",241 "disc-000001",242 ]);243244 expect(ran.code).toBe(0);245 expect(yield* platform.calls).toStrictEqual([246 {247 ask: ASK,248 discussion: "disc-000001",249 files: given,250 project: PROJECT,251 },252 ]);253 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),254 { timeout: 30_000 }255 );256257 it.live.each([258 {259 files: {},260 names: ASK_FILE,
69 unmodified lines
modified:apps/cli/test/tui/fixture.ts+7 added-6 removed
1import { RefNameText } from "@repo/protocol/domain/common";2import { DecisionSubject } from "@repo/protocol/domain/decision";3import type { Decision, Today } from "@repo/protocol/domain/decision";4import {5 AskId,6 CommitSha,7 DecisionId,8 Handle,9 ProjectName,9 ProposalId,10} from "@repo/protocol/ids";11import { DateTime } from "effect";1213const at = (iso: string) => DateTime.makeUnsafe(iso);
3 unmodified lines
17export const okonkwo = Handle.make("okonkwo");1819export const datekit = ProjectName.make("oscabriel/datekit");2021/** An ask proposed for datekit, expiring tomorrow: last in expiry order. */22export const proposal: Decision = {21/** A passing answer to finish in datekit, expiring tomorrow: last in expiry order. */22export const finish: Decision = {23 deciders: [okonkwo],24 default: "accept",25 evidence: [{ label: "territory", value: "src/week" }],26 expiresAt: at("2026-10-09T09:00:00Z"),27 id: DecisionId.make("dec-000001"),28 openedAt: at("2026-10-07T09:00:00Z"),29 project: datekit,30 subject: DecisionSubject.cases.OpenProposal.make({31 proposal: ProposalId.make("prop-000001"),30 subject: DecisionSubject.cases.Finish.make({31 ask: AskId.make("week-start"),32 head: sha("c"),33 }),34};3536/** A stray push to datekit's main, expiring within the day: first. */
25 unmodified lines
62};6364export const today: Today = {65 decider: okonkwo,65 decisions: [proposal, vouch, stray],66 decisions: [finish, vouch, stray],67 expiringSoon: [stray.id],68 newcomers: [Handle.make("ada"), Handle.make("grace")],69 unattended: [],70};
modified:apps/cli/test/tui/today.test.ts+5 added-5 removed
35 unmodified lines
36import { reduce, start } from "../../src/tui/today.ts";37import type { DecideCall, TodayViewState } from "../../src/tui/today.ts";38import { TodayView } from "../../src/tui/view.ts";39import { runProgram } from "../remote-server.ts";40import { datekit, okonkwo, proposal, stray, today, vouch } from "./fixture.ts";40import { datekit, finish, okonkwo, stray, today, vouch } from "./fixture.ts";4142const press = (state: TodayViewState, keys: readonly string[]) => {43 const calls: DecideCall[] = [];44 let now = state;
171 unmodified lines
216 12217 );218219 expect(rows.filter((row) => row.startsWith(">"))).toStrictEqual([220 "> oscabriel/datekit/dec-000001 open the ask prop-000001 proposes",220 "> oscabriel/datekit/dec-000001 finish the answer to week-start at ccccccc",221 ]);222 expect(rowsWith(rows, "above")).toStrictEqual([223 "2 decisions above; up to read them",224 ]);
219 unmodified lines
444 "Sending decline on oscabriel/datekit/dec-000003…",445 ]);446 expect([last?.notice, ids(last), last?.cursor]).toStrictEqual([447 ["Decided: decline on oscabriel/datekit/dec-000003"],448 [proposal.id, stray.id],448 [finish.id, stray.id],449 1,450 ]);451 })452 );
3 unmodified lines
456 () =>457 Effect.gen(function* () {458 const { client, decided } = yield* platform(new Set());459460 // y accepts the vouch; the second a would accept the proposal that461 // takes its place, at once, since accept is the proposal's default.460 // y accepts the vouch; the second a would accept the finish that461 // takes its place, at once, since accept is the finish's default.462 const { screen } = yield* scripted(["down", "a", "y", "a"]);463464 yield* atTerminal(465 client,
226 unmodified lines
modified:apps/cli/test/hook.test.ts+2 added-2 removed
381 unmodified lines
382 const policy = Schema.decodeSync(Policy)({383 agents: "trailer",384 asks: [askWire],385 at: landedSha,386 caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },386 caps: { claimsPerPerson: 3 },387 claims: { lapseAfterMs: 86_400_000, warnAfterMs: 7_200_000 },388 deciders: [{ handles: ["bob"], paths: "**" }],389 decisions: { expireDays: 14 },390 functions: { admit: false, opensAlone: false },390 functions: { admit: false },391 judge: judgeClosure(392 Schema.decodeSync(RunBlock)({393 checks: { lint: "bun run lint" },394 test: "bun test {path}",
798 unmodified lines
modified:apps/cli/test/policy-view.test.ts+2 added-5 removed
14 unmodified lines
1516const datekitPolicy = {17 agents: "trailer",18 at: sha,19 caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },19 caps: { claimsPerPerson: 3 },20 claims: { lapseAfterMs: 86_400_000, warnAfterMs: 7_200_000 },21 deciders: [22 { handles: ["ines-v"], paths: "**" },23 { handles: ["okonkwo", "bram"], paths: "src/tz.ts" },
67 unmodified lines
9192 it("states the vouch rule in words, with how many are vouched for and denounced", () => {93 const text = textOf(datekit);9495 expect(text).toContain("For code: claiming an ask needs a vouch");96 expect(text).toContain(96 "For code: claiming an ask or offering a sealed answer needs a vouch"97 );98 expect(text).toContain(97 `${Brand.configDir}/vouched.td vouches for 2 and denounces 1`98 );99 });100
11 unmodified lines
112 const lines = linesOf(textOf(datekit));113114 for (const line of [115 "Claims 3 claims at once for a person nobody has vouched for; a vouched person and a maintainer are never held",118 "Proposals 2 proposals open at once for a person nobody has vouched for",116 "Decisions an undecided one takes its default after 14 days",117 "Claim timing warned after 2 hours without a push; lapses after 24 hours",118 "Record a landing counts once it has stood 30 days, for 365 days",119 ]) {
110 unmodified lines
modified:apps/cli/test/surfaces.test.ts+2 added-3 removed
194 unmodified lines
195 expect.arrayContaining([196 "asks",197 "ask",198 "ask open",199 "ask flag",199 "env shape",200 "env set",201 "init",202 "schema",203 ])204 );205 });206208 it("puts ask open, ask draft and ask flag under ask, and env shape beside env set", () => {209 expect(subcommandsOf(top("ask"))).toStrictEqual(["draft", "flag", "open"]);207 it("puts ask open under ask, and env shape beside env set", () => {208 expect(subcommandsOf(top("ask"))).toStrictEqual(["open"]);209 expect(subcommandsOf(top("env"))).toStrictEqual(["shape", "set"]);210 });211212 it("leaves init and env set to their local commands", () => {
413 unmodified lines
modified:apps/platform/src/adapters/do-projects.ts-10 removed
70 unmodified lines
71 answer: (requestId) => on("answer", [requestId]),72 claim: (caller, ask) => assumingMade(on("claim", [caller, ask])),73 credits: (caller, handle) => on("credits", [caller, handle]),74 decide: (caller, input) => assumingMade(on("decide", [caller, input])),75 draftAsk: (caller, input) => assumingMade(on("draftAsk", [caller, input])),76 draftContext: (proposal, round) => on("draftContext", [proposal, round]),77 draftSettled: (proposal, round, result) =>78 on("draftSettled", [proposal, round, result]),75 events: (since, limit) => on("events", [since, limit]),76 // A name pointing at another project is the service's own77 // `UnknownProject`, so it crosses as the refusal it is.78 evidence: (caller, ref) => on("evidence", [caller, ref]),79 finish: (caller, input) => assumingMade(on("finish", [caller, input])),80 firstPusher: () => on("firstPusher", []),85 flagAsk: (caller, input) => assumingMade(on("flagAsk", [caller, input])),81 fork: (caller) => assumingMade(on("fork", [caller])),82 forks: () => on("forks", []),83 head: () => on("head", []),84 heldBackJob: (requestId) => on("heldBackJob", [requestId]),
11 unmodified lines
96 openAsk: (caller, input) => assumingMade(on("openAsk", [caller, input])),97 policy: () => on("policy", []),98 postDiscussion: (caller, input) =>99 assumingMade(on("postDiscussion", [caller, input])),105 proposeAsk: (caller, input) =>106 assumingMade(on("proposeAsk", [caller, input])),100 recordAdmission: (input) => on("recordAdmission", [input]),101 recordFirstPush: (caller, head) => on("recordFirstPush", [caller, head]),102 recordHeldBack: (requestId, results) =>103 on("recordHeldBack", [requestId, results]),104 recordLayerPush: (caller, input) => on("recordLayerPush", [caller, input]),105 recordLayerRead: (caller, input) => on("recordLayerRead", [caller, input]),106 recordPush: (input) => on("recordPush", [input]),114 rehearseOpen: (files) => on("rehearseOpen", [files]),107 release: (caller, ask) => assumingMade(on("release", [caller, ask])),108 scanForValues: (input) => on("scanForValues", [input]),109 setEnv: (caller, input) => assumingMade(on("setEnv", [caller, input])),110 showAsk: (caller, ask) => assumingMade(on("showAsk", [caller, ask])),111 showDiscussion: (caller, discussion) =>112 assumingMade(on("showDiscussion", [caller, discussion])),121 showProposal: (caller, proposal) =>122 assumingMade(on("showProposal", [caller, proposal])),113 standing: () => on("standing", []),114 status: (caller) => assumingMade(on("status", [caller])),115 submitAnswer: (caller, input) =>116 assumingMade(on("submitAnswer", [caller, input])),
81 unmodified lines
deleted:apps/platform/src/adapters/draft-runs-workflow.ts-56 removed
1import { DraftRuns } from "@repo/project/draft-runs";2import { Effect, Layer, Schema } from "effect";34import { DraftParams, draftId } from "../answer-runs.ts";56export interface DraftInstance {7 readonly id: string;8 readonly restart: () => Promise<void>;9 readonly status: () => Promise<{ readonly status: InstanceStatus["status"] }>;10}1112export interface DraftWorkflow {13 readonly create: (options: {14 readonly id: string;15 readonly params: typeof DraftParams.Encoded;16 }) => Promise<{ readonly id: string }>;17 readonly get: (id: string) => Promise<DraftInstance>;18}1920const encodeParams = Schema.encodeEffect(DraftParams);2122// A complete round is left alone: running it again would ask the model again.23const failed: ReadonlySet<InstanceStatus["status"]> = new Set([24 "errored",25 "terminated",26]);2728const runAgain = (instance: DraftInstance) =>29 Effect.gen(function* () {30 const { status } = yield* Effect.tryPromise(() => instance.status());3132 if (failed.has(status)) {33 yield* Effect.tryPromise(() => instance.restart());34 }35 });3637export const DraftRunsWorkflow = (38 workflow: DraftWorkflow39): Layer.Layer<never> =>40 Layer.succeed(DraftRuns, {41 start: (round) =>42 Effect.gen(function* () {43 const params = yield* encodeParams(DraftParams.make(round));44 const id = draftId(round);4546 yield* Effect.tryPromise(() => workflow.create({ id, params })).pipe(47 // The id is taken: the round was started before.48 Effect.catch((error) =>49 Effect.tryPromise(() => workflow.get(id)).pipe(50 Effect.mapError(() => error),51 Effect.flatMap(runAgain)52 )53 )54 );55 }).pipe(Effect.orDie),56 });
modified:apps/platform/src/adapters/rate-limits.ts+6 added-21 removed
4 unmodified lines
56import { RateLimits } from "../rate-limits.ts";7import type { Limited } from "../rate-limits.ts";89export interface Limits {10 readonly claim: number;11 readonly draft: number;12 readonly post: number;13 readonly proposal: number;14}9export type Limits = Readonly<Record<Limited, number>>;1011// Mirrors each binding's `simple.limit` in wrangler.jsonc: a binding can't say its own limit.17export const WorkerCaps = {18 claim: 10,19 draft: 2,20 post: 5,21 proposal: 5,22} as const satisfies Limits;12export const WorkerCaps = { claim: 10, post: 5 } as const satisfies Limits;1314const LIMIT_OF = {15 claim: "claims",26 draft: "drafts",16 post: "discussions",28 proposal: "proposals",17} as const satisfies Record<Limited, CapReached["limit"]>;1819// A binding can't say when its window resets, so the whole 60 s period is the honest upper bound.20const WINDOW_SECONDS = 60;
5 unmodified lines
26 retryAfter: WINDOW_SECONDS,27 });2829// A binding that fails is a defect: a call it could not count is not let through.42export const WorkerRateLimits = (bindings: {43 readonly claim: RateLimit;44 readonly draft: RateLimit;45 readonly proposal: RateLimit;46}): Layer.Layer<RateLimits> =>30export const WorkerRateLimits = (31 bindings: Readonly<Record<Limited, RateLimit>>32): Layer.Layer<RateLimits> =>33 Layer.succeed(34 RateLimits,35 RateLimits.of({36 check: (kind, handle) =>37 Effect.tryPromise(() =>52 // A post is counted by the proposal binding, under its own cap.53 bindings[kind === "post" ? "proposal" : kind].limit({38 bindings[kind].limit({39 key: handle.toLowerCase(),40 })41 ).pipe(42 Effect.orDie,
34 unmodified lines
modified:apps/platform/src/auth/pages.ts+1 added-1 removed
177 unmodified lines
178<summary>What it can do</summary>179<ul class="may">180<li>Read what you can read: projects, asks, code, verdicts, and any layer whose audience you are in</li>181<li>Claim, release and answer asks, and push to your forks</li>182<li>Make projects, and propose and flag asks</li>182<li>Make projects, and post in their discussions</li>183<li>Open asks, take decisions, finish answers, land changes, vouch for or denounce people, and set write-only values where you are a maintainer; nobody can read a value back</li>184</ul>185<p>It never sees your password.</p>186</details>`;
306 unmodified lines
modified:apps/platform/src/workflows/answer.ts+5 added-48 removed
1// The class name is frozen. Params tagged `Admission` or `Draft` run admissions and2// draft rounds on this same Workflow, so neither adds a Workflow binding.3import type { RepoHost } from "@repo/artifacts/repo-host";4import type { Drafter } from "@repo/drafting/drafter";5import type { Projects } from "@repo/project/projects";1// The class name is frozen. Params tagged `Admission` run admissions on this2// same Workflow, so they add no Workflow binding.3import { Outcome } from "@repo/protocol/domain/outcome";4import { annotateInvocation, refusedWith } from "@repo/telemetry/spans";5import type { InvocationIds } from "@repo/telemetry/spans";6import { WorkflowEntrypoint } from "cloudflare:workers";7import type { WorkflowEvent } from "cloudflare:workers";8import { Effect, Layer, Schema } from "effect";910import type { WorkflowParams } from "../answer-runs.ts";14import { AdmissionParams, AnswerParams, DraftParams } from "../answer-runs.ts";11import { AdmissionParams, AnswerParams } from "../answer-runs.ts";12import { decodeEnv } from "../platform.ts";16import { draftPorts, telemetryOf, workerPorts } from "../ports.ts";13import { telemetryOf, workerPorts } from "../ports.ts";14import { admissionSteps } from "./admission-steps.ts";15import { runAnswer } from "./answer/program.ts";16import type { AnswerPorts } from "./answer/program.ts";20import { draftSteps, timedSteps } from "./draft-steps.ts";21import type { EngineSteps } from "./draft-steps.ts";17import { instance, invocation } from "./instance.ts";18import { workflowSteps } from "./step.ts";19import type { StepRunner, WorkflowSteps } from "./step.ts";20
52 unmodified lines
73 Effect.orDie74 )75 );7682export const runDraftWorkflow = <E>(83 ports: Layer.Layer<Projects | Drafter | RepoHost, E>,84 payload: typeof DraftParams.Encoded,85 steps: EngineSteps86): Promise<null> =>87 Effect.runPromise(88 Effect.gen(function* () {89 const params = yield* Schema.decodeEffect(DraftParams)(payload);9091 return yield* draftSteps(params).pipe(92 Effect.as(null),93 invocation({ project: params.project })94 );95 }).pipe(96 instance("Draft.run"),97 Effect.provide(Layer.merge(ports, workflowSteps(timedSteps(steps)))),98 Effect.orDie99 )100 );10177const admits = Schema.is(Schema.toEncoded(AdmissionParams));78104const drafts = Schema.is(Schema.toEncoded(DraftParams));10579export class Answer extends WorkflowEntrypoint<80 Env,81 typeof WorkflowParams.Encoded82> {83 override run(84 event: Readonly<WorkflowEvent<typeof WorkflowParams.Encoded>>,112 step: EngineSteps85 step: WorkflowSteps86 ): Promise<OutcomeEncoded | null> {87 const config = decodeEnv(this.env);88 const { payload } = event;89117 if (drafts(payload)) {118 return runDraftWorkflow(119 Layer.unwrap(120 Effect.map(config, (decoded) =>121 Layer.mergeAll(122 workerPorts(decoded),123 draftPorts(decoded),124 telemetryOf(decoded)125 )126 )127 ),128 payload,129 step130 );131 }13290 const ports = Layer.unwrap(91 Effect.map(config, (decoded) =>92 Layer.merge(workerPorts(decoded), telemetryOf(decoded))93 )
7 unmodified lines
deleted:apps/platform/src/workflows/draft-steps.ts-33 removed
1import type { RepoHost } from "@repo/artifacts/repo-host";2import type { Drafter } from "@repo/drafting/drafter";3import { runDraft } from "@repo/drafting/run";4import type { Projects } from "@repo/project/projects";5import type { WorkflowTimeoutDuration } from "cloudflare:workers";6import type { Effect, Schema } from "effect";78import type { DraftParams } from "../answer-runs.ts";9import { StepRunner } from "./step.ts";10import type { WorkflowStepRetries, WorkflowSteps } from "./step.ts";1112export const DRAFT_STEP_TIMEOUT = "10 minutes";1314export interface EngineSteps {15 readonly do: (16 name: string,17 config: {18 readonly retries?: WorkflowStepRetries;19 readonly timeout?: WorkflowTimeoutDuration;20 },21 body: () => Promise<Schema.Json>22 ) => Promise<Schema.Json>;23}2425export const timedSteps = (engine: EngineSteps): WorkflowSteps => ({26 do: (name, config, body) =>27 engine.do(name, { ...config, timeout: DRAFT_STEP_TIMEOUT }, body),28});2930export const draftSteps = (31 params: DraftParams32): Effect.Effect<void, never, StepRunner | Projects | Drafter | RepoHost> =>33 StepRunner.use((runner) => runDraft(params, { step: runner.step }));
modified:apps/platform/src/answer-runs.ts+1 added-18 removed
1import { DraftParams as DraftRun } from "@repo/project/draft-runs";1import {2 CommitSha,3 keyOf,4 LayerName,
16 unmodified lines
21});2223export type AdmissionParams = typeof AdmissionParams.Type;2426export const DraftParams = Schema.TaggedStruct("Draft", DraftRun.fields);25export const WorkflowParams = Schema.Union([AdmissionParams, AnswerParams]);2628export type DraftParams = typeof DraftParams.Type;2930export const WorkflowParams = Schema.Union([31 AdmissionParams,32 DraftParams,33 AnswerParams,34]);3527export type WorkflowParams = typeof WorkflowParams.Type;2829const ID_LENGTH = 100;30
27 unmodified lines
58 instanceId(59 `admit-${keyOf(params.project)}-${params.layer}`,60 `-${params.head}`61 );7172export const draftId = (73 params: Pick<DraftParams, "project" | "proposal" | "round">74) =>75 instanceId(76 `draft-${keyOf(params.project)}`,77 `-${params.proposal}-r${params.round}`78 );
modified:apps/platform/src/handlers.ts-33 removed
186 unmodified lines
187 decide: ({ project, ...input }) =>188 Effect.flatMap(person, (who) =>189 on(project, (api) => api.decide(who, input))190 ),191 draftAsk: ({ project, ...input }) =>192 Effect.gen(function* () {193 const who = yield* person;194195 yield* rateLimits.check("draft", who.handle);196197 return yield* on(project, (api) => api.draftAsk(who, input));198 }),191 evidence: ({ project, ref }) =>192 Effect.flatMap(person, (who) =>193 on(project, (api) =>194 api
8 unmodified lines
203 finish: ({ project, ...input }) =>204 Effect.flatMap(person, (who) =>205 on(project, (api) => api.finish(who, input))206 ),215 flagAsk: ({ project, ...input }) =>216 Effect.gen(function* () {217 const who = yield* person;218219 yield* rateLimits.check("proposal", who.handle);220221 return yield* on(project, (api) => api.flagAsk(who, input));222 }),207 fork: ({ project }) =>208 Effect.gen(function* () {209 const who = yield* person;210 const { fork } = yield* on(project, (api) => api.fork(who));
75 unmodified lines
286287 return yield* on(project, (api) => api.postDiscussion(who, input));288 }),289 projectPolicy: ({ project }) => on(project, (api) => api.policy()),306 proposeAsk: ({ project, ...input }) =>307 Effect.gen(function* () {308 const who = yield* person;309310 // A draft spends the draft limit first, then the proposal limit.311 if (input.draft === true) {312 yield* rateLimits.check("draft", who.handle);313 }314315 yield* rateLimits.check("proposal", who.handle);316317 return yield* on(project, (api) => api.proposeAsk(who, input));318 }),290 readFile: ({ at, path, project }) =>291 code(project, (of) => fileOf(of, Option.fromUndefinedOr(at), path)),292 readTree: ({ at, path, project }) =>293 code(project, (of) =>
19 unmodified lines
313 showDiscussion: ({ discussion, project }) =>314 Effect.flatMap(caller, (who) =>315 on(project, (api) => api.showDiscussion(who, discussion))316 ),346 showProposal: ({ project, proposal }) =>347 Effect.flatMap(caller, (who) =>348 on(project, (api) => api.showProposal(who, proposal))349 ),317 status: ({ project }) =>318 Effect.gen(function* () {319 const who = yield* person;320
56 unmodified lines
modified:apps/platform/src/home.ts+3 added-8 removed
81 unmodified lines
82const homeHtml = (input: {83 readonly origin: string;84 readonly projects: readonly ProjectListing[];85 readonly webUrl: Option.Option<string>;86 readonly draftModel: string;86}) => {88 const { draftModel, origin, projects, webUrl } = input;87 const { origin, projects, webUrl } = input;8889 return page(90 "What this host serves",91 [
28 unmodified lines
120 `Sign up: ${link(`${origin}/signup`)}`,121 `Authorize a client: ${code(`${origin}/authorize`)}`,122 ])123 ),125 section(126 "Drafting",127 `<p>A member can ask the platform's agent to draft a proposed ask (Workers AI, ${code(draftModel)}); a maintainer accepts it, and only people are credited.</p>`128 ),124 section("Health", `<p>${link(`${origin}/health`)}</p>`),125 ].join("\n"),126 "document"127 );
2 unmodified lines
130export const homeResponse = (131 request: Request132): Effect.Effect<Response, never, FrontPage | HostInfo | Projects> =>133 Effect.gen(function* () {139 const { draftModel, webUrl } = yield* HostInfo;134 const { webUrl } = yield* HostInfo;135136 const projects = yield* FrontPage.use((frontPage) =>137 frontPage.projects()138 ).pipe(Effect.flatMap(withStandingPosture));
20 unmodified lines
159 }160 );161 }162168 return new Response(homeHtml({ draftModel, origin, projects, webUrl }), {163 return new Response(homeHtml({ origin, projects, webUrl }), {164 headers: {165 "cache-control": BRIEFLY,166 "content-security-policy":167 "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'",
6 unmodified lines
modified:apps/platform/src/host-info.ts+1 added-4 removed
1 unmodified line
2import type { Option } from "effect";34export class HostInfo extends Context.Service<5 HostInfo,6 {7 readonly webUrl: Option.Option<string>;8 readonly draftModel: string;9 }6 { readonly webUrl: Option.Option<string> }7>()("platform/HostInfo") {}
modified:apps/platform/src/platform.ts+2 added-8 removed
48 unmodified lines
4950export const LanderAdapter = Schema.Literals(["container", "isogit"]);5152export const PlatformBindings = Schema.Struct({53 AI: binding<Env["AI"]>("Workers AI"),53 ANSWER: binding<Env["ANSWER"]>("the Answer Workflow"),54 ARTIFACTS: binding<Env["ARTIFACTS"]>("an Artifacts namespace"),55 ARTIFACTS_PRIVATE: binding<Env["ARTIFACTS_PRIVATE"]>(56 "the private Artifacts namespace"57 ),58 CLAIM_LIMIT: binding<Env["CLAIM_LIMIT"]>("a rate limit"),59 CODE_CACHE: binding<Env["CODE_CACHE"]>("an R2 bucket"),61 DRAFT_LIMIT: binding<Env["DRAFT_LIMIT"]>("a rate limit"),60 EMAIL: binding<Env["EMAIL"]>("Email Service's send_email"),61 EVIDENCE: binding<Env["EVIDENCE"]>("an R2 bucket"),62 FRONT_PAGE: binding<Env["FRONT_PAGE"]>("a D1 database"),63 LOADER: binding<Env["LOADER"]>("a Worker Loader"),64 METRICS: binding<Env["METRICS"]>("an Analytics Engine dataset"),65 OAUTH_KV: binding<Env["OAUTH_KV"]>("a KV namespace"),66 ON_PUSH: binding<Env["ON_PUSH"]>("the OnPush Workflow"),67 POST_LIMIT: binding<Env["POST_LIMIT"]>("a rate limit"),68 PROJECT: binding<Env["PROJECT"]>("the Project Durable Object"),70 PROPOSAL_LIMIT: binding<Env["PROPOSAL_LIMIT"]>("a rate limit"),69 RELEASES: binding<Env["RELEASES"]>("an R2 bucket"),70 // The generated `Env` types this as a plain `Fetcher` (an app's types may not name71 // another app's entrypoint), so its methods are declared here by their wire.72 SANDBOX: binding<Env["SANDBOX"] & SandboxBinding>("the sandbox Worker"),73 SIGN_IN_LIMIT: binding<Env["SIGN_IN_LIMIT"]>("a rate limit"),74});7576export const PlatformVars = Schema.Struct({79 DRAFT_MODEL: Schema.NonEmptyString,77 LANDER_ADAPTER: LanderAdapter.pipe(78 Schema.withDecodingDefaultKey(Effect.succeed("container"))79 ),80 OPERATOR_HANDLE: Handle,
96 unmodified lines
177 ReleaseStoreBinding(config.RELEASES),178 Layer.succeed(Stage, Stage.of({ name: config.STAGE })),179 Layer.succeed(180 HostInfo,184 HostInfo.of({185 draftModel: config.DRAFT_MODEL,186 webUrl: Option.fromUndefinedOr(config.PUBLIC_WEB_URL),187 })181 HostInfo.of({ webUrl: Option.fromUndefinedOr(config.PUBLIC_WEB_URL) })182 )183 ).pipe(Layer.provideMerge(ports));184185export const platformOf = (config: PlatformConfig): Layer.Layer<Services> =>
4 unmodified lines
modified:apps/platform/src/ports.ts+2 added-18 removed
3 unmodified lines
4import { RepoHostBinding } from "@repo/artifacts/repo-host/binding";5import type { CheckRunner } from "@repo/checks/check-runner";6import type { EvidenceStore } from "@repo/checks/evidence-store";7import { EvidenceStoreR2 } from "@repo/checks/evidence-store/r2";8import type { Drafter } from "@repo/drafting/drafter";9import { DrafterWorkersAi } from "@repo/drafting/drafter/binding";10import { DraftModel } from "@repo/drafting/run";8import type { Upstream } from "@repo/git/upstream";9import { UpstreamRepoHost } from "@repo/git/upstream/repo-host";10import { CodeStoreR2 } from "@repo/project/code-store/binding";11import { CodeCacheLive } from "@repo/project/code/cache";
18 unmodified lines
30import { Layer, Option, Redacted } from "effect";3132import { CheckRunnerSandbox } from "./adapters/check-runner-sandbox.ts";33import { DoProjects } from "./adapters/do-projects.ts";37import { DraftRunsWorkflow } from "./adapters/draft-runs-workflow.ts";34import { WorkerFetch } from "./adapters/fetch.ts";35import { LanderSandbox } from "./adapters/lander-sandbox.ts";36import { WorkerRateLimits } from "./adapters/rate-limits.ts";37import * as cartridges from "./cartridges.ts";
70 unmodified lines
108 Layer.provide(FinishersFromChecks)109 ),110 DoProjects(config.PROJECT).pipe(Layer.provide(listed)),111 Layer.succeed(ProjectSockets, Option.some(config.PROJECT)),116 WorkerRateLimits({117 claim: config.CLAIM_LIMIT,118 draft: config.DRAFT_LIMIT,119 proposal: config.PROPOSAL_LIMIT,120 }),112 WorkerRateLimits({ claim: config.CLAIM_LIMIT, post: config.POST_LIMIT }),113 EvidenceStoreR2(config.EVIDENCE),114 CodeCacheLive(CODE_READS_KEPT.light, CODE_READS_KEPT.heavy),115 CodeStoreR2(config.CODE_CACHE, coloCache),124 MetricsBinding(config.METRICS),125 // Without this entry a draft proposal starts no run, and stays drafting.126 DraftRunsWorkflow(config.ANSWER)116 MetricsBinding(config.METRICS)117 ).pipe(118 Layer.provideMerge(RepoHostBinding.layer(config.ARTIFACTS)),119 Layer.provideMerge(WorkerFetch)120 );
21 unmodified lines
142// is kept by its name and frames alone: the visibility cartridge runs here,143// and a defect's text may name a layer's repo or quote a sealed path.144export const telemetryOf = (config: PlatformConfig): Layer.Layer<never> =>145 Telemetry({ defects: "name", secrets: secretsOf(config), tracing });156157export const draftPorts = (config: PlatformConfig): Layer.Layer<Drafter> =>158 Layer.merge(159 DrafterWorkersAi(config.AI, config.DRAFT_MODEL),160 Layer.succeed(DraftModel, config.DRAFT_MODEL)161 );
modified:apps/platform/src/project-calls.ts-7 removed
67 unmodified lines
68 claim: callOf(MethodSchemas.claim),69 credits: callOf(MethodSchemas.credits),70 [envSchemaMethod]: callOf(MethodSchemas[envSchemaMethod]),71 decide: callOf(MethodSchemas.decide),72 draftAsk: callOf(MethodSchemas.draftAsk),73 draftContext: callOf(MethodSchemas.draftContext),74 draftSettled: callOf(MethodSchemas.draftSettled),72 events: callOf(MethodSchemas.events),73 evidence: callOf(MethodSchemas.evidence),74 finish: callOf(MethodSchemas.finish),75 firstPusher: callOf(MethodSchemas.firstPusher),79 flagAsk: callOf(MethodSchemas.flagAsk),76 fork: callOf(MethodSchemas.fork),77 forks: callOf(MethodSchemas.forks),78 head: callOf(MethodSchemas.head),79 heldBackJob: callOf(MethodSchemas.heldBackJob),
10 unmodified lines
90 onAlarm: callOf(MethodSchemas.onAlarm),91 openAsk: callOf(MethodSchemas.openAsk),92 policy: callOf(MethodSchemas.policy),93 postDiscussion: callOf(MethodSchemas.postDiscussion),98 proposeAsk: callOf(MethodSchemas.proposeAsk),94 recordAdmission: callOf(MethodSchemas.recordAdmission),95 recordFirstPush: callOf(MethodSchemas.recordFirstPush),96 recordHeldBack: callOf(MethodSchemas.recordHeldBack),97 recordLayerPush: callOf(MethodSchemas.recordLayerPush),98 recordLayerRead: callOf(MethodSchemas.recordLayerRead),99 recordPush: callOf(MethodSchemas.recordPush),105 rehearseOpen: callOf(MethodSchemas.rehearseOpen),100 release: callOf(MethodSchemas.release),101 scanForValues: callOf(MethodSchemas.scanForValues),102 setEnv: callOf(MethodSchemas.setEnv),103 showAsk: callOf(MethodSchemas.showAsk),104 showDiscussion: callOf(MethodSchemas.showDiscussion),111 showProposal: callOf(MethodSchemas.showProposal),105 standing: callOf(MethodSchemas.standing),106 status: callOf(MethodSchemas.status),107 submitAnswer: callOf(MethodSchemas.submitAnswer),108 today: callOf(MethodSchemas.today),
58 unmodified lines
modified:apps/platform/src/rate-limits.ts+1 added-2 removed
1 unmodified line
2import type { CapReached } from "@repo/protocol/refusal";3import { Context } from "effect";4import type { Effect } from "effect";56/** A post shares the proposal binding's window: both are words put to a project's maintainers. */7export type Limited = "claim" | "proposal" | "draft" | "post";6export type Limited = "claim" | "post";78export class RateLimits extends Context.Service<9 RateLimits,10 {
6 unmodified lines
deleted:apps/platform/test/workflows/draft.test.ts-661 removed
1import { describe, expect, expectTypeOf, it } from "@effect/vitest";2import type { RepoHost } from "@repo/artifacts/repo-host";3import { CheckAt } from "@repo/checks/check-runner";4import { DraftFailed } from "@repo/drafting/drafted";5import type { DraftedAsk } from "@repo/drafting/drafted";6import type { Drafter } from "@repo/drafting/drafter";7import type { AiLike } from "@repo/drafting/drafter/binding";8import { DrafterMemory, DraftsAsked } from "@repo/drafting/drafter/memory";9import { draftedFiles } from "@repo/drafting/render";10import { DraftModel } from "@repo/drafting/run";11import { DraftRuns } from "@repo/project/draft-runs";12import { Lander } from "@repo/project/lander";13import type { ProjectApi } from "@repo/project/project";14import { Projects } from "@repo/project/projects";15import { DecisionSubject } from "@repo/protocol/domain/decision";16import { DraftState } from "@repo/protocol/domain/proposal";17import {18 AskId,19 LandedSha,20 LaneName,21 ProjectName,22 ProposalId,23 RepoName,24 keyOf,25 RepoPath,26} from "@repo/protocol/ids";27import { Anonymous, Person } from "@repo/protocol/principal";28import { CapReached } from "@repo/protocol/refusal";29import { advanceTo } from "@repo/testkit/clock";30import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";31import { Array, Context, Effect, Layer, Option, Ref, Schema } from "effect";3233import { DraftRunsWorkflow } from "../../src/adapters/draft-runs-workflow.ts";34import type { DraftWorkflow } from "../../src/adapters/draft-runs-workflow.ts";35import { DraftParams, draftId } from "../../src/answer-runs.ts";36import { Handlers } from "../../src/handlers.ts";37import type { PlatformConfig } from "../../src/platform.ts";38import { runDraftWorkflow } from "../../src/workflows/answer.ts";39import type { EngineSteps } from "../../src/workflows/draft-steps.ts";40import { draftSteps } from "../../src/workflows/draft-steps.ts";41import { memoSteps, StepRunner } from "../../src/workflows/step.ts";42import type { StepRetry } from "../../src/workflows/step.ts";43import { as, seeded, worldOf } from "../handlers.fixtures.ts";44import { Checker, Pusher, worldWith } from "./answer.fixtures.ts";4546type EngineConfig = Parameters<EngineSteps["do"]>[1];4748const scenario = aProject({ people: ["carol"] }).pipe(49 withVouches(["carol"]),50 withAsk({ id: "parse-week", territory: "." })51);5253const { policy, project } = scenario;5455const repo = RepoName.make(keyOf(project));5657const alice = Person.make({ handle: scenario.initializer });5859const carol = Person.make({60 handle: scenario.people.get("carol") ?? scenario.initializer,61});6263const redThenGreen = LaneName.make("redThenGreen");6465const model = "@cf/moonshotai/kimi-k2.7-code";6667const want = "Parse an ISO week date such as 2026-W41";6869const proposal = ProposalId.make("prop-000001");7071const params = DraftParams.make({ project, proposal, round: 1 });7273const start = [74 ["package.json", '{ "name": "alice/datekit", "type": "module" }\n'],75 ["src/parse.ts", "export const parse = (s) => ({});\n"],76] as const;7778const draftOf = (assertion: string, id = "parse-week"): DraftedAsk => ({79 id: AskId.make(id),80 kind: "fix",81 rationale: `${id}: parseWeek is missing, so its test fails by an assertion`,82 territory: [RepoPath.make("src/parse.ts")],83 test: {84 path: RepoPath.make(`test/${id}.test.ts`),85 source: [86 'import { expect, it } from "bun:test";',87 'import { parse } from "../src/parse.ts";',88 "",89 `it("${id}", () => {`,90 ` ${assertion}`,91 "});",92 "",93 ].join("\n"),94 },95 want,96});9798const passing = draftOf("expect(parse('2026-W41')).toStrictEqual({});");99100const passingToo = draftOf("expect(parse('2026-W42')).toStrictEqual({});");101102const red = draftOf("expect(parse('2026-W41').week).toBe(41);");103104const unstated = draftOf(105 "expect(parse('2026-W41').week).toBe(41);",106 "parse-month"107);108109const proposed = Effect.gen(function* () {110 yield* advanceTo("2026-10-08T12:00:00Z");111112 const api = yield* Projects.use((each) => each.create(project)).pipe(113 Effect.orDie114 );115116 yield* api.initProject(alice, {}).pipe(Effect.orDie);117118 const first = yield* Pusher.use((each) =>119 each.push(repo, Option.none(), start)120 );121122 yield* api.recordFirstPush(alice, first).pipe(Effect.orDie);123124 yield* api125 .proposeAsk(carol, { draft: true, territory: "src/parse.ts", want })126 .pipe(Effect.orDie);127128 return { api, main: LandedSha.make(first) };129});130131const scripted = (132 main: LandedSha,133 drafted: DraftedAsk,134 result: "passed" | "failed"135) =>136 Effect.gen(function* () {137 const { commit } = yield* Lander.use((lander) =>138 lander.compose({ files: draftedFiles(drafted), main, repo })139 ).pipe(Effect.orDie);140141 yield* Checker.use((script) =>142 script.script(CheckAt.cases.Commit.make({ commit }), redThenGreen, [143 result === "passed"144 ? { result }145 : { result, signature: "redThenGreen: expected 41, got undefined" },146 ])147 );148 });149150const draftOfProposal = (api: ProjectApi) =>151 Effect.map(152 Effect.orDie(api.showProposal(Anonymous.make({}), proposal)),153 ({ proposal: shown }) => shown.draft154 );155156const proposalDecisions = (api: ProjectApi) =>157 Effect.map(Effect.orDie(api.today(alice)), ({ decisions }) =>158 decisions.filter(({ subject }) =>159 DecisionSubject.guards.OpenProposal(subject)160 )161 );162163const asked = DraftsAsked.use(({ inputs }) => inputs);164165const worldDrafting = (script: Parameters<typeof DrafterMemory>[0]) =>166 Layer.mergeAll(167 worldWith(policy),168 DrafterMemory(script),169 Layer.succeed(DraftModel, model)170 );171172describe("a draft's run, over steps that replay", () => {173 it.effect(174 "feeds attempt 1's NotRedFirst into attempt 2, puts up one decision with the red-first evidence, and a replay asks the model nothing more",175 () =>176 Effect.gen(function* () {177 const { api, main } = yield* proposed;178179 yield* scripted(main, passing, "passed");180 yield* scripted(main, red, "failed");181182 const steps = yield* memoSteps();183184 yield* draftSteps(params).pipe(Effect.provide(steps));185186 const inputs = yield* asked;187 const decisions = yield* proposalDecisions(api);188189 expect({190 attempts: inputs.map(({ attempt }) => attempt),191 decisions: decisions.length,192 draft: yield* draftOfProposal(api),193 firstFeedback: inputs[0]?.feedback,194 redFirst: decisions[0]?.evidence.find(195 ({ label }) => label === "red first"196 )?.value,197 refusedWith: inputs[1]?.feedback?.split("\n")[0]?.split(":")[0],198 }).toStrictEqual({199 attempts: [1, 2],200 decisions: 1,201 draft: DraftState.cases.Ready.make({202 attempts: 2,203 model,204 red: {205 lane: redThenGreen,206 signature: "redThenGreen: expected 41, got undefined",207 },208 round: 1,209 }),210 firstFeedback: undefined,211 redFirst: `${redThenGreen}: redThenGreen: expected 41, got undefined`,212 refusedWith: "NotRedFirst",213 });214215 yield* draftSteps(params).pipe(Effect.provide(steps));216217 expect({218 asked: (yield* asked).length,219 decisions: (yield* proposalDecisions(api)).length,220 }).toStrictEqual({ asked: 2, decisions: 1 });221 }).pipe(Effect.provide(worldDrafting([passing, red])))222 );223224 it.effect(225 "settles Failed with the last refusal's tag once three attempts are refused",226 () =>227 Effect.gen(function* () {228 const { api, main } = yield* proposed;229230 yield* scripted(main, passing, "passed");231 yield* scripted(main, passingToo, "passed");232233 yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));234235 expect({236 asked: (yield* asked).length,237 decisions: (yield* proposalDecisions(api)).length,238 draft: yield* draftOfProposal(api),239 }).toStrictEqual({240 asked: 3,241 decisions: 1,242 draft: DraftState.cases.Failed.make({243 attempts: 3,244 model,245 refusal: "IncompleteBrief",246 round: 1,247 }),248 });249 }).pipe(Effect.provide(worldDrafting([passing, passingToo, unstated])))250 );251252 it.effect(253 "retries a rate-limited model as a step, without spending an attempt",254 () =>255 Effect.gen(function* () {256 const { api, main } = yield* proposed;257258 yield* scripted(main, red, "failed");259260 yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));261262 expect({263 asked: (yield* asked).map(({ attempt }) => attempt),264 draft: yield* draftOfProposal(api),265 }).toStrictEqual({266 asked: [1, 1],267 draft: DraftState.cases.Ready.make({268 attempts: 1,269 model,270 red: {271 lane: redThenGreen,272 signature: "redThenGreen: expected 41, got undefined",273 },274 round: 1,275 }),276 });277 }).pipe(278 Effect.provide(279 worldDrafting([new DraftFailed({ reason: "rate-limited" }), red])280 )281 )282 );283284 it.effect(285 "spends the attempt of a model still rate-limited once its step's retries are spent, and a replay ends the same way",286 () =>287 Effect.gen(function* () {288 const { api, main } = yield* proposed;289290 yield* scripted(main, red, "failed");291292 const steps = yield* memoSteps();293294 yield* draftSteps(params).pipe(Effect.provide(steps));295296 const settled = {297 asked: (yield* asked).map(({ attempt }) => attempt),298 draft: yield* draftOfProposal(api),299 feedback: (yield* asked)[5]?.feedback,300 };301302 yield* draftSteps(params).pipe(Effect.provide(steps));303304 expect({305 replayed: {306 asked: (yield* asked).length,307 draft: yield* draftOfProposal(api),308 },309 settled,310 }).toStrictEqual({311 replayed: { asked: 6, draft: settled.draft },312 settled: {313 asked: [1, 1, 1, 1, 1, 2],314 draft: DraftState.cases.Ready.make({315 attempts: 2,316 model,317 red: {318 lane: redThenGreen,319 signature: "redThenGreen: expected 41, got undefined",320 },321 round: 1,322 }),323 feedback:324 "Your reply gave no draft (rate-limited): answer with one JSON object that matches the schema, and nothing else.",325 },326 });327 }).pipe(328 Effect.provide(329 worldDrafting([330 ...Array.replicate(new DraftFailed({ reason: "rate-limited" }), 5),331 red,332 ])333 )334 )335 );336337 it.effect(338 "tells the next attempt the model erred, not that it was rate-limited, when the drafter dies",339 () =>340 Effect.gen(function* () {341 const { api } = yield* proposed;342343 yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));344345 const inputs = yield* asked;346347 expect({348 asked: inputs.map(({ attempt }) => attempt),349 draft: yield* draftOfProposal(api),350 feedback: inputs[1]?.feedback,351 }).toStrictEqual({352 asked: [1, 2, 3],353 draft: DraftState.cases.Failed.make({354 attempts: 3,355 model,356 refusal: "IncompleteBrief",357 round: 1,358 }),359 feedback:360 "Your reply gave no draft (model-error): answer with one JSON object that matches the schema, and nothing else.",361 });362 }).pipe(Effect.provide(worldDrafting([])))363 );364365 it.effect(366 "ends the round Failed with VerifierBlocked, asking no other draft, when the Checker stays blocked past the rehearsal's retries",367 () =>368 Effect.gen(function* () {369 const { api } = yield* proposed;370371 const steps = yield* memoSteps();372373 yield* draftSteps(params).pipe(Effect.provide(steps));374 yield* draftSteps(params).pipe(Effect.provide(steps));375376 expect({377 asked: (yield* asked).length,378 decisions: (yield* proposalDecisions(api)).length,379 draft: yield* draftOfProposal(api),380 }).toStrictEqual({381 asked: 1,382 decisions: 1,383 draft: DraftState.cases.Failed.make({384 attempts: 1,385 model,386 refusal: "VerifierBlocked",387 round: 1,388 }),389 });390 }).pipe(Effect.provide(worldDrafting([red])))391 );392393 it.effect(394 "stops after its context when the proposal is gone: no attempt, no settling",395 () =>396 Effect.gen(function* () {397 yield* proposed;398399 const names = yield* Ref.make<readonly string[]>([]);400401 const memo = Context.get(402 yield* Layer.build(yield* memoSteps()),403 StepRunner404 );405406 const logged = StepRunner.of({407 step: (name, schema, effect, retry?: StepRetry) =>408 Effect.andThen(409 Ref.update(names, (all) => [...all, name]),410 memo.step(name, schema, effect, retry)411 ),412 });413414 yield* draftSteps(415 DraftParams.make({416 project,417 proposal: ProposalId.make("prop-000009"),418 round: 1,419 })420 ).pipe(Effect.provideService(StepRunner, logged));421422 expect({423 asked: (yield* asked).length,424 names: yield* Ref.get(names),425 }).toStrictEqual({ asked: 0, names: ["context"] });426 }).pipe(Effect.provide(worldDrafting([])))427 );428});429430const fakeWorkflow = (status: InstanceStatus["status"]) => {431 const made: string[] = [];432 const restarted: string[] = [];433434 const workflow: DraftWorkflow = {435 create: ({ id }) => {436 if (made.includes(id)) {437 return Promise.reject(new Error(`instance ${id} already exists`));438 }439440 made.push(id);441442 return Promise.resolve({ id });443 },444 get: (id) =>445 Promise.resolve({446 id,447 restart: () => {448 restarted.push(id);449450 return Promise.resolve();451 },452 status: () => Promise.resolve({ status }),453 }),454 };455456 return { made, restarted, workflow };457};458459describe("the Workflow's draft runs", () => {460 it.effect(461 "starts one instance per round: a second start finds it, and a run still going is left alone",462 () =>463 Effect.gen(function* () {464 const fake = fakeWorkflow("running");465466 const starting = DraftRuns.pipe(467 Effect.flatMap((runs) =>468 runs.start({ note: "keep it small", project, proposal, round: 1 })469 ),470 Effect.provide(DraftRunsWorkflow(fake.workflow))471 );472473 yield* starting;474 yield* starting;475476 expect({477 made: fake.made,478 restarted: fake.restarted,479 }).toStrictEqual({480 made: [`draft-${keyOf(project)}-${proposal}-r1`],481 restarted: [],482 });483484 expect(draftId(params)).toBe(`draft-${keyOf(project)}-${proposal}-r1`);485 })486 );487488 it("keeps every round of a long-named project's proposals its own instance, within the engine's 100 characters", () => {489 const long = ProjectName.make(`alice/${"a-long-project-name".repeat(6)}x`);490491 const longToo = ProjectName.make(492 `alice/${"a-long-project-name".repeat(6)}y`493 );494495 const other = ProposalId.make("prop-000002");496497 const rounds = [498 { project: long, proposal, round: 1 },499 { project: long, proposal, round: 2 },500 { project: long, proposal: other, round: 1 },501 { project: longToo, proposal, round: 1 },502 ];503504 const ids = rounds.map(draftId);505506 expect({507 distinct: new Set(ids).size,508 fit: ids.every(509 (id) => id.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/u.test(id)510 ),511 named: rounds.every((round, at) =>512 (ids[at] ?? "").endsWith(`-${round.proposal}-r${round.round}`)513 ),514 }).toStrictEqual({ distinct: 4, fit: true, named: true });515 });516517 it.effect(518 "starts an errored round's instance again, and never a complete one, which would ask the model again",519 () =>520 Effect.gen(function* () {521 const errored = fakeWorkflow("errored");522 const complete = fakeWorkflow("complete");523524 const twice = (workflow: DraftWorkflow) =>525 DraftRuns.pipe(526 Effect.flatMap((runs) =>527 Effect.andThen(528 runs.start({ project, proposal, round: 1 }),529 runs.start({ project, proposal, round: 1 })530 )531 ),532 Effect.provide(DraftRunsWorkflow(workflow))533 );534535 yield* twice(errored.workflow);536 yield* twice(complete.workflow);537538 expect({539 complete: complete.restarted,540 errored: errored.restarted,541 }).toStrictEqual({542 complete: [],543 errored: [`draft-${keyOf(project)}-${proposal}-r1`],544 });545 })546 );547548 it.effect(549 "gives the engine a 10-minute timeout on each step, and the rate-limit retries on the model's",550 () =>551 Effect.gen(function* () {552 const { main } = yield* proposed;553554 yield* scripted(main, red, "failed");555556 const configs: (readonly [string, EngineConfig])[] = [];557 const kept = new Map<string, Schema.Json>();558559 const engine: EngineSteps = {560 do: (name, config, body) => {561 configs.push([name, config]);562563 const found = kept.get(name);564565 return found === undefined566 ? body().then((value) => {567 kept.set(name, value);568569 return value;570 })571 : Promise.resolve(found);572 },573 };574575 const ports = yield* Effect.context<Projects | Drafter | RepoHost>();576577 const payload = yield* Schema.encodeEffect(DraftParams)(params);578579 yield* Effect.promise(() =>580 runDraftWorkflow(Layer.succeedContext(ports), payload, engine)581 );582583 expect(configs.map(([name]) => name)).toStrictEqual([584 "context",585 "draft-1",586 "rehearse-1",587 "settle",588 ]);589590 expect({591 draft: new Map(configs).get("draft-1"),592 rehearse: new Map(configs).get("rehearse-1"),593 }).toStrictEqual({594 draft: {595 retries: { backoff: "exponential", delay: 15_000, limit: 4 },596 timeout: "10 minutes",597 },598 rehearse: {599 retries: { backoff: "exponential", delay: 60_000, limit: 3 },600 timeout: "10 minutes",601 },602 });603604 expect(605 configs.filter(([, config]) => config.timeout !== "10 minutes")606 ).toStrictEqual([]);607 }).pipe(Effect.provide(worldDrafting([red])))608 );609610 it("takes the Worker's bindings as the generated Env types them", () => {611 expectTypeOf<Env["ANSWER"]>().toExtend<612 Parameters<typeof DraftRunsWorkflow>[0]613 >();614 expectTypeOf<PlatformConfig["AI"]>().toExtend<AiLike>();615 });616});617618describe("proposing with a draft", () => {619 it.effect(620 "spends the person's draft limit first: past it, CapReached, while a proposal without a draft still goes through",621 () =>622 Effect.gen(function* () {623 yield* advanceTo("2026-10-08T12:00:00Z");624 yield* seeded(scenario);625626 const asCarol = yield* as("carol");627628 const drafted = yield* asCarol.proposeAsk({629 draft: true,630 project,631 want,632 });633634 const past = yield* Effect.flip(635 asCarol.proposeAsk({ draft: true, project, want })636 );637638 const plain = yield* asCarol.proposeAsk({ project, want });639640 expect({641 drafted: drafted.proposal.draft?._tag,642 past,643 plain: plain.proposal.draft,644 }).toStrictEqual({645 drafted: "Drafting",646 past: new CapReached({ cap: 1, limit: "drafts", retryAfter: 60 }),647 plain: undefined,648 });649 }).pipe(650 Effect.provide(651 Handlers.pipe(652 Layer.provideMerge(653 worldOf([scenario], {654 limits: { claim: 5, draft: 1, proposal: 5 },655 })656 )657 )658 )659 )660 );661});
modified:apps/platform/test/bindings.test.ts+51 added-73 removed
97 unmodified lines
9899const Named = Schema.Array(Schema.Struct({ name: Schema.String }));100101const BindingKinds = Schema.Struct({102 ai: Schema.optionalKey(Schema.Struct({ binding: Schema.String })),102 analytics_engine_datasets: Schema.optionalKey(Bound),103 artifacts: Schema.optionalKey(Bound),104 d1_databases: Schema.optionalKey(Bound),105 durable_objects: Schema.optionalKey(Schema.Struct({ bindings: Named })),
51 unmodified lines
157158const declaredIn = (raw: typeof Raw.Type) =>159 Effect.map(decodeBlock(raw), (block) => ({160 bindings: sorted([162 ...(block.ai === undefined ? [] : [block.ai.binding]),161 ...(block.analytics_engine_datasets ?? []).map(({ binding }) => binding),162 ...(block.artifacts ?? []).map(({ binding }) => binding),163 ...(block.d1_databases ?? []).map(({ binding }) => binding),164 ...(block.durable_objects?.bindings ?? []).map(({ name }) => name),
58 unmodified lines
223 ].flatMap(({ groups }) => (groups?.key === undefined ? [] : [groups.key]))224 )225);226229const draftLimit = (id: string) => ({230 name: "DRAFT_LIMIT",227const postLimit = (id: string) => ({228 name: "POST_LIMIT",229 namespace_id: id,232 simple: { limit: 2, period: 60 },230 simple: { limit: 5, period: 60 },231});232233describe("a wrangler.jsonc, read as data", () => {234 it.effect(
42 unmodified lines
277 });278 }).pipe(Effect.provide(NodeServices.layer))279 );280283 it.effect(284 "set the drafter's model, the web's address and the draft limit in every stage",285 () =>286 Effect.gen(function* () {287 const raw = yield* Effect.flatMap(288 fileText("wrangler.jsonc"),289 readJsonc290 );281 it.effect("set the web's address and the post limit in every stage", () =>282 Effect.gen(function* () {283 const raw = yield* Effect.flatMap(fileText("wrangler.jsonc"), readJsonc);284292 const { env = {} } = yield* Schema.decodeUnknownEffect(Staged)(raw);285 const { env = {} } = yield* Schema.decodeUnknownEffect(Staged)(raw);286294 const DraftBlock = Schema.Struct({295 ai: Schema.Struct({ binding: Schema.String }),296 ratelimits: Schema.Array(297 Schema.Struct({298 name: Schema.String,299 namespace_id: Schema.String,300 simple: Schema.Struct({301 limit: Schema.Int,302 period: Schema.Int,303 }),304 })305 ),306 vars: PlatformVars,307 });287 const StageBlock = Schema.Struct({288 ratelimits: Schema.Array(289 Schema.Struct({290 name: Schema.String,291 namespace_id: Schema.String,292 simple: Schema.Struct({293 limit: Schema.Int,294 period: Schema.Int,295 }),296 })297 ),298 vars: PlatformVars,299 });300309 const read = (block: typeof Raw.Type | undefined) =>310 Effect.map(311 Schema.decodeUnknownEffect(DraftBlock)(block),312 ({ ai, ratelimits, vars }) => ({313 ai: ai.binding,314 draftLimit: ratelimits.find(({ name }) => name === "DRAFT_LIMIT"),315 model: vars.DRAFT_MODEL,316 web: vars.PUBLIC_WEB_URL,317 })318 );301 const read = (block: typeof Raw.Type | undefined) =>302 Effect.map(303 Schema.decodeUnknownEffect(StageBlock)(block),304 ({ ratelimits, vars }) => ({305 postLimit: ratelimits.find(({ name }) => name === "POST_LIMIT"),306 web: vars.PUBLIC_WEB_URL,307 })308 );309320 const model = "@cf/moonshotai/kimi-k2.7-code";321322 expect({323 "dev-oscabriel": yield* read(env["dev-oscabriel"]),324 prod: yield* read(env.prod),325 top: yield* read(raw),326 }).toStrictEqual({327 "dev-oscabriel": {328 ai: "AI",329 draftLimit: draftLimit("1104"),330 model,331 web: "https://web-dev-oscabriel.oscargabriel.workers.dev",332 },333 prod: {334 ai: "AI",335 draftLimit: draftLimit("1304"),336 model,337 // A stand-in: on the brand's own domain, `infra/deploy.ts` passes338 // the web's address as a `--var` (`packages/config/test/deploy.test.ts`).339 web: "https://from-infra-deploy.invalid",340 },341 top: {342 ai: "AI",343 draftLimit: draftLimit("1004"),344 model,345 web: "http://localhost:5173",346 },347 });348 }).pipe(Effect.provide(NodeServices.layer))310 expect({311 "dev-oscabriel": yield* read(env["dev-oscabriel"]),312 prod: yield* read(env.prod),313 top: yield* read(raw),314 }).toStrictEqual({315 "dev-oscabriel": {316 postLimit: postLimit("1102"),317 web: "https://web-dev-oscabriel.oscargabriel.workers.dev",318 },319 prod: {320 postLimit: postLimit("1302"),321 // A stand-in: on the brand's own domain, `infra/deploy.ts` passes322 // the web's address as a `--var` (`packages/config/test/deploy.test.ts`).323 web: "https://from-infra-deploy.invalid",324 },325 top: {326 postLimit: postLimit("1002"),327 web: "http://localhost:5173",328 },329 });330 }).pipe(Effect.provide(NodeServices.layer))331 );332333 it.effect("keep code history in each block's own code-cache bucket", () =>334 Effect.gen(function* () {
96 unmodified lines
431 >();432 expectTypeOf<Env["CLAIM_LIMIT"]>().toExtend<433 Parameters<typeof WorkerRateLimits>[0]["claim"]434 >();453 expectTypeOf<Env["PROPOSAL_LIMIT"]>().toExtend<454 Parameters<typeof WorkerRateLimits>[0]["proposal"]435 expectTypeOf<Env["POST_LIMIT"]>().toExtend<436 Parameters<typeof WorkerRateLimits>[0]["post"]437 >();456 expectTypeOf<Env["DRAFT_LIMIT"]>().toExtend<457 Parameters<typeof WorkerRateLimits>[0]["draft"]458 >();459 expectTypeOf<PlatformConfig["AI"]>().toEqualTypeOf<Env["AI"]>();438 expectTypeOf<Env["FRONT_PAGE"]>().toExtend<439 Parameters<typeof D1Client.layer>[0]["db"]440 >();441 expectTypeOf<Env["OAUTH_KV"]>().toExtend<
57 unmodified lines
modified:apps/platform/test/core-loop.test.ts+1 added-141 removed
1import { describe, expect, it } from "@effect/vitest";2import type { RepoHost } from "@repo/artifacts/repo-host";2import { Brand } from "@repo/brand";3import { CheckAt } from "@repo/checks/check-runner";5import { draftRunsInline } from "@repo/drafting/draft-runs/inline";6import type { InlinePorts } from "@repo/drafting/draft-runs/inline";7import type { DraftedAsk } from "@repo/drafting/drafted";8import { DrafterMemory } from "@repo/drafting/drafter/memory";9import { draftedFiles } from "@repo/drafting/render";10import type { Projects } from "@repo/project/projects";11import { DecisionSubject } from "@repo/protocol/domain/decision";4import { Outcome } from "@repo/protocol/domain/outcome";5import {6 AskId,7 Handle,
10 unmodified lines
18 OutOfScope,19 StaleBase,20} from "@repo/protocol/refusal";21import { explain } from "@repo/protocol/render";30import { Array, Context, Deferred, Effect, Layer } from "effect";22import { Array, Effect } from "effect";2324import { pushRequestId } from "../src/adapters/custody.ts";25import { coreLoopWorld } from "./world.ts";26
428 unmodified lines
455 });456 }),457 60_000458 );467468 it.live(469 "a want proposed with a draft runs in process, goes to the maintainer with its red-first evidence, and opens on accept with Assisted-by beside the people's credits",470 () =>471 Effect.gen(function* () {472 const drafted: DraftedAsk = {473 id: AskId.make("parse-day"),474 kind: "fix",475 rationale: "parse reads no day, so the test fails by its assertion",476 territory: [RepoPath.make("src/parse.ts")],477 test: {478 path: RepoPath.make("test/parse-day.test.ts"),479 source: [480 'import { expect, it } from "bun:test";',481 'import { parse } from "../src/parse.ts";',482 "",483 'it("parse reads the day of an ISO date", () => {',484 ' expect(Reflect.get(parse("2026-10-07"), "day")).toBe(7);',485 "});",486 "",487 ].join("\n"),488 },489 want: "parse reads the day of an ISO date",490 };491492 const ready = yield* Deferred.make<Context.Context<InlinePorts>>();493 const drafter = yield* Layer.build(DrafterMemory([drafted]));494495 const world = yield* coreLoopWorld({496 plugIn: () => ({497 project: draftRunsInline(Deferred.await(ready)),498 worker: Layer.effectDiscard(499 Effect.gen(function* () {500 const ports = yield* Effect.context<Projects | RepoHost>();501502 yield* Deferred.succeed(ready, Context.merge(ports, drafter));503 })504 ),505 }),506 });507508 const dora = world.rpc("dora");509 const alice = world.rpc("alice");510 const doraGit = world.git("dora");511512 const made = yield* dora.initProject({ project });513 const home = yield* doraGit.clone(made.remote);514515 yield* doraGit.commit(home, "Start datekit", start);516 yield* doraGit.push(home);517518 yield* world.script(519 CheckAt.cases.Commit.make({520 commit: yield* world.composed(project, draftedFiles(drafted)),521 }),522 redThenGreen,523 ["failed", "failed"]524 );525526 const proposed = yield* alice.proposeAsk({527 draft: true,528 project,529 want: drafted.want,530 });531532 const { decisions } = yield* dora.today({ project });533534 const decision = yield* Effect.fromOption(535 Array.findFirst(536 decisions,537 ({ subject }) =>538 DecisionSubject.guards.OpenProposal(subject) &&539 subject.proposal === proposed.proposal.id540 )541 );542543 const shown = yield* alice.showProposal({544 project,545 proposal: proposed.proposal.id,546 });547548 yield* dora.decide({549 choice: "accept",550 decision: decision.id,551 project,552 });553554 const { asks } = yield* alice.listAsks({ project });555556 yield* doraGit.ok(home, "fetch", "--quiet", "origin");557558 expect({559 asks: asks.map(({ ask, claimed }) => ({ ask, claimed })),560 draft: shown.proposal.draft?._tag,561 files: yield* doraGit.ok(562 home,563 "show",564 "--format=",565 "--name-only",566 "origin/main"567 ),568 proposed: proposed.proposal.draft?._tag,569 redFirst: decision.evidence.some(570 ({ label, value }) =>571 label === "red first" && value.startsWith(`${redThenGreen}: `)572 ),573 trailers: (yield* doraGit.ok(574 home,575 "log",576 "-1",577 "--format=%(trailers:only)",578 "origin/main"579 ))580 .split("\n")581 .filter((line) => /^[A-Za-z-]+-by: /u.test(line)),582 }).toStrictEqual({583 asks: [{ ask: drafted.id, claimed: false }],584 draft: "Ready",585 files: draftedFiles(drafted)586 .map(({ path }) => path)587 .join("\n"),588 proposed: "Drafting",589 redFirst: true,590 trailers: [591 `Asked-by: ${credited("alice")}`,592 `Decided-by: ${credited("dora")}`,593 `Assisted-by: ${Brand.cli}-drafter:memory (verified)`,594 ],595 });596 }),597 60_000598 );459});
modified:apps/platform/test/do-projects.test.ts+1 added-40 removed
1import { describe, expect, expectTypeOf, it } from "@effect/vitest";2import { LogRef } from "@repo/checks/evidence-store";3import { envSchemaMethod } from "@repo/project/deciders";4import { DraftResult } from "@repo/project/draft-runs";4import { FrontPage } from "@repo/project/front-page";5import { FrontPageMemory } from "@repo/project/front-page/memory";6import { LandingCommand } from "@repo/project/landing";7import type { ProjectApi } from "@repo/project/project";
7 unmodified lines
15 keyOf,16 LandedSha,17 LayerName,18 ProjectName,20 ProposalId,19 RequestId,20} from "@repo/protocol/ids";23import {24 NotRedFirst,25 ProjectExists,26 UnknownProject,27} from "@repo/protocol/refusal";21import { ProjectExists, UnknownProject } from "@repo/protocol/refusal";22import { advanceTo } from "@repo/testkit/clock";23import { Effect, Fiber, Layer, Option, Redacted, Ref, Schema } from "effect";2425import { DoProjects } from "../src/adapters/do-projects.ts";
60 unmodified lines
86 choice: "accept",87 decision: DecisionId.make("dec-none0001"),88 })89 ),96 draftAsk: settled(97 "draftAsk",98 api.draftAsk(carol, { proposal: ProposalId.make("prop-000001") })99 ),100 draftContext: settled(101 "draftContext",102 api.draftContext(ProposalId.make("prop-000001"), 1)103 ),104 draftSettled: settled(105 "draftSettled",106 api.draftSettled(107 ProposalId.make("prop-000001"),108 1,109 DraftResult.cases.Failed.make({110 attempts: 1,111 model: "test-model",112 refusal: new NotRedFirst({}),113 })114 )115 ),90 [envSchemaMethod]: settled(envSchemaMethod, api[envSchemaMethod](anyone)),91 events: settled("events", api.events(0, 100)),92 evidence: settled(93 "evidence",
3 unmodified lines
97 "finish",98 api.finish(bob, { ask: parseIso, base: sha, head: sha, requestId })99 ),100 firstPusher: settled("firstPusher", api.firstPusher()),127 flagAsk: settled(128 "flagAsk",129 api.flagAsk(bob, { ask: parseIso, reason: "It names no format." })130 ),101 fork: settled("fork", api.fork(carol)),102 forks: settled("forks", api.forks()),103 head: settled("head", api.head()),104 heldBackJob: settled("heldBackJob", api.heldBackJob(requestId)),
19 unmodified lines
124 postDiscussion: settled(125 "postDiscussion",126 api.postDiscussion(carol, { title: "Which day starts a week?" })127 ),158 proposeAsk: settled(159 "proposeAsk",160 api.proposeAsk(carol, { want: "Parse ISO week dates." })161 ),128 recordAdmission: settled(129 "recordAdmission",130 api.recordAdmission({ head: sha, layer, results: [] })131 ),
20 unmodified lines
152 ref: "refs/heads/main",153 repo: forkOf(bob),154 })155 ),190 rehearseOpen: settled("rehearseOpen", api.rehearseOpen(askFiles())),156 release: settled("release", api.release(bob, parseIso)),157 scanForValues: settled(158 "scanForValues",159 api.scanForValues({ text: "a-value-long-enough-0123" })
9 unmodified lines
169 showDiscussion: settled(170 "showDiscussion",171 api.showDiscussion(anyone, DiscussionId.make("disc-000001"))172 ),208 showProposal: settled(209 "showProposal",210 api.showProposal(anyone, ProposalId.make("prop-000001"))211 ),173 standing: settled("standing", api.standing()),174 status: settled("status", api.status(bob)),175 submitAnswer: settled(176 "submitAnswer",
210 unmodified lines
modified:apps/platform/test/fake-env.ts+1 added-4 removed
117 unmodified lines
118 return namespace;119};120121export const fakeEnv = (): Env => ({122 AI: untouchable("AI"),122 ANSWER: untouchable("ANSWER"),123 ARTIFACTS: untouchable("ARTIFACTS"),124 ARTIFACTS_PRIVATE: untouchable("ARTIFACTS_PRIVATE"),125 CLAIM_LIMIT: untouchable("CLAIM_LIMIT"),126 CODE_CACHE: untouchable("CODE_CACHE"),127 COOKIE_KEY: cookieKey,129 DRAFT_LIMIT: untouchable("DRAFT_LIMIT"),130 DRAFT_MODEL: "@cf/moonshotai/kimi-k2.7-code",128 EMAIL: untouchable("EMAIL"),129 EVIDENCE: untouchable("EVIDENCE"),130 // Lists nothing: the Project DO adapter reads the listing before it probes a project.131 FRONT_PAGE: emptyFrontPage(),
5 unmodified lines
137 ON_PUSH: untouchable("ON_PUSH"),138 OPERATOR_HANDLE: "oscabriel",139 OPERATOR_TOKEN: operatorToken,140 PASSWORD_PEPPER: passwordPepper,141 POST_LIMIT: untouchable("POST_LIMIT"),142 PROJECT: fakeProjects(),145 PROPOSAL_LIMIT: untouchable("PROPOSAL_LIMIT"),143 PUBLIC_WEB_URL: "http://localhost:5173",144 RELEASES: untouchable("RELEASES"),145 SANDBOX: untouchable("SANDBOX"),146 SIGN_IN_LIMIT: untouchable("SIGN_IN_LIMIT"),
15 unmodified lines
modified:apps/platform/test/handlers.fixtures.ts+2 added-6 removed
43 unmodified lines
44 ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],45 ["packages/trim/src/trim.ts", "export const trim = (s) => s;\n"],46];4748const askFiles = ({ check, file, id, territory }: Ask) =>48export const askFiles = ({ check, file, id, territory }: Ask) =>49 Array.make(50 { content: `export default "${id}";\n`, path: file },51 {52 content: [
62 unmodified lines
115116export interface WorldOptions {117 readonly frontPage?: FrontPageSeed;118 readonly limits?: {119 readonly claim: number;120 readonly draft?: number;119 readonly claim?: number;120 readonly post?: number;122 readonly proposal: number;121 };122}123124const noFrontPage: FrontPageSeed = { credits: [], entries: [], projects: [] };
15 unmodified lines
140 ),141 FrontPageMemory.layer(options.frontPage ?? noFrontPage),142 MemoryRateLimits({143 claim: options.limits?.claim ?? 100,146 draft: options.limits?.draft ?? 100,144 post: options.limits?.post ?? 100,148 proposal: options.limits?.proposal ?? 100,145 }),146 EvidenceStoreMemory147 ).pipe(Layer.provideMerge(RepoHostMemory));148
29 unmodified lines
modified:apps/platform/test/handlers.test.ts+61 added-123 removed
2 unmodified lines
3import { Brand } from "@repo/brand";4import type { FrontPageSeed } from "@repo/project/front-page/memory";5import { Projects } from "@repo/project/projects";6import { Contracts } from "@repo/protocol/contracts";7import { DecisionSubject } from "@repo/protocol/domain/decision";7import type { Decision } from "@repo/protocol/domain/decision";8import type { FrontPageEntry } from "@repo/protocol/domain/front-page";10import type { Proposal } from "@repo/protocol/domain/proposal";9import {10 AskId,11 CommitSha,12 DiscussionId,13 EnvKey,14 Handle,15 KindName,16 ProjectName,17 RepoName,18 RepoPath,19 RequestId,20 keyOf,21} from "@repo/protocol/ids";22import {23 Anonymous,24 Authenticated,
20 unmodified lines
45 Effect,46 Exit,47 FileSystem,48 Layer,49 Option,50 Redacted,51 Result,52 Stream,53} from "effect";
2 unmodified lines
5657import { WorkerCaps, WorkerRateLimits } from "../src/adapters/rate-limits.ts";58import { Handlers } from "../src/handlers.ts";59import { RateLimits } from "../src/rate-limits.ts";59import { as, seeded, worldOf } from "./handlers.fixtures.ts";60import { as, askFiles, seeded, worldOf } from "./handlers.fixtures.ts";61import type { WorldOptions } from "./handlers.fixtures.ts";6263const people = ["bob", "carol"];64
40 unmodified lines
105 HttpServerRequest.HttpServerRequest,106 HttpServerRequest.fromWeb(new Request(url, { method: "POST" }))107 );108108const decisionOn = (109 decisions: readonly Decision[],110 proposal: Pick<Proposal, "id">111) =>112 Effect.fromOption(113 Array.findFirst(114 decisions,115 ({ subject }) =>116 DecisionSubject.guards.OpenProposal(subject) &&117 subject.proposal === proposal.id118 )119 );109// A push that deleted main, as OnPush reports it: a decision for the110// project's maintainers, and deciding it moves nothing.111const mainDeleted = (project: ProjectName, eventId: string) =>112 Effect.gen(function* () {113 const api = yield* Projects.use((projects) => projects.get(project));114 const { landed } = yield* api.head();115116 yield* api.recordPush({117 after: CommitSha.make("0".repeat(40)),118 before: Option.fromUndefinedOr(landed),119 eventId,120 pusher: Anonymous.make({}),121 ref: "refs/heads/main",122 repo: RepoName.make(keyOf(project)),123 });124 }).pipe(Effect.orDie);125126const firstOf = (decisions: readonly Decision[]) =>127 Effect.fromOption(Array.head(decisions));128129describe("project reads", () => {130 it.effect("list and show a project's asks, and know no other project", () =>131 Effect.gen(function* () {132 yield* made;
177 unmodified lines
310 expect(past).toStrictEqual(311 new CapReached({ cap: 1, limit: "claims", retryAfter: 60 })312 );313 expect(bobs.claim.claimant).toBe("bob");306 }).pipe(Effect.provide(platform({ limits: { claim: 1, proposal: 5 } })))314 }).pipe(Effect.provide(platform({ limits: { claim: 1 } })))315 );316});317310describe("proposals and flags", () => {311 it.effect("share one rate limit per person", () =>312 Effect.gen(function* () {313 yield* made;314315 const bob = yield* as("bob");316 const carol = yield* as("carol");317318 const proposed = yield* bob.proposeAsk({319 project: datekit.project,320 want: "Parse ISO week dates.",321 });322323 const flagged = yield* Effect.flip(324 bob.flagAsk({325 ask: parseIso,326 project: datekit.project,327 reason: "The want names a file.",328 })329 );330331 const carols = yield* carol.flagAsk({332 ask: parseIso,333 project: datekit.project,334 reason: "The want names a file.",335 });336337 expect(proposed.proposal.proposer).toBe("bob");338 expect(flagged).toStrictEqual(339 new CapReached({ cap: 1, limit: "proposals", retryAfter: 60 })340 );341 expect({342 flags: carols.proposal.flags,343 proposer: carols.proposal.proposer,344 }).toStrictEqual({ flags: "parse-iso", proposer: "carol" });345 }).pipe(Effect.provide(platform({ limits: { claim: 5, proposal: 1 } })))346 );347});348318describe("discussions", () => {319 it.effect(320 "take a thread and a reply from anyone not denounced, list and show them, and refuse the denounced",321 () =>
63 unmodified lines
385 }).pipe(Effect.provide(platform()))386 );387388 it.effect(420 "become a proposal by a maintainer alone, and then take no more posts",389 "become an ask by a maintainer alone, and then take no more posts",390 () =>391 Effect.gen(function* () {392 yield* made;393
1 unmodified line
395 const bob = yield* as("bob");396397 const { discussion } = yield* bob.postDiscussion({398 project: datekit.project,430 title: "Parse ISO week dates?",399 title: "Trim tabs too?",400 });401433 const bobProposes = yield* Effect.flip(434 bob.proposeAsk({435 discussion: discussion.id,436 project: datekit.project,437 want: "Parse ISO week dates.",438 })402 const ask = Option.getOrThrow(403 Array.findFirst(datekit.policy.asks, ({ id }) => id === trimInput)404 );405441 const { proposal } = yield* alice.proposeAsk({406 // trim-input is open already: opening it again lands nothing, and407 // names it as the ask the thread became.408 const asked = {409 ask: trimInput,410 discussion: discussion.id,411 files: askFiles(ask),412 project: datekit.project,444 want: "Parse ISO week dates.",445 });413 };414415 const bobAsks = yield* Effect.flip(bob.openAsk(asked));416 const opened = yield* alice.openAsk(asked);417418 const after = yield* bob.showDiscussion({419 discussion: discussion.id,420 project: datekit.project,421 });
5 unmodified lines
427 project: datekit.project,428 })429 );430460 expect(bobProposes).toStrictEqual(new NotDecider({}));431 expect(bobAsks).toStrictEqual(new NotDecider({}));432 expect(opened.ask.id).toBe(trimInput);433 expect(after.discussion).toMatchObject({462 proposal: proposal.id,463 state: "proposed",434 ask: trimInput,435 state: "asked",436 });437 expect(reply).toStrictEqual(438 new DiscussionClosed({ discussion: discussion.id })439 );
21 unmodified lines
461 expect(second).toStrictEqual(462 new CapReached({ cap: 1, limit: "discussions", retryAfter: 60 })463 );464 expect(carols.discussion.id).toBe(DiscussionId.make("disc-000002"));493 }).pipe(494 Effect.provide(platform({ limits: { claim: 5, post: 1, proposal: 5 } }))495 )465 }).pipe(Effect.provide(platform({ limits: { post: 1 } })))466 );467});468469describe("calls that name no project", () => {
45 unmodified lines
515 yield* made;516517 const alice = yield* as("alice");518 const bob = yield* as("bob");549 const carol = yield* as("carol");519520 yield* bob.claim({ ask: parseIso, project: datekit.project });521 yield* bob.claim({ ask: lexTokens, project: burrow.project });522554 const declined = yield* bob.proposeAsk({555 project: datekit.project,556 want: "Parse ISO week dates.",557 });558523 yield* mainDeleted(datekit.project, "evt-deleted-1");524 yield* advanceTo("2026-10-07T12:05:00Z");560 yield* carol.proposeAsk({561 project: datekit.project,562 want: "Trim tabs too.",563 });525 yield* mainDeleted(datekit.project, "evt-deleted-2");526 yield* advanceTo("2026-10-07T12:10:00Z");565 yield* bob.proposeAsk({566 project: burrow.project,567 want: "Lex comments.",568 });527 yield* mainDeleted(burrow.project, "evt-deleted-3");528529 const { decisions: inDatekit } = yield* alice.today({530 project: datekit.project,531 });532574 const first = yield* decisionOn(inDatekit, declined.proposal);533 const first = yield* firstOf(inDatekit);534535 yield* alice.decide({536 choice: "decline",537 decision: first.id,
183 unmodified lines
721 const alicesFork = yield* alice722 .fork({ project })723 .pipe(reachedAt("https://platform-dev.example.workers.dev/rpc"));724766 const { proposal } = yield* bob.proposeAsk({767 project,768 want: "Parse ISO week dates.",769 });725 yield* mainDeleted(project, "evt-deleted-1");726727 const today = yield* alice.today({ project });728773 const decision = yield* decisionOn(today.decisions, proposal);729 const decision = yield* firstOf(today.decisions);730731 const bobDecides = yield* Effect.flip(732 bob.decide({ choice: "decline", decision: decision.id, project })733 );
182 unmodified lines
916};917918describe("the Worker's rate limits", () => {919 it.effect(964 "count claims, proposals and drafts apart, per person whatever the case of their handle",920 "count claims and posts apart, per person whatever the case of their handle",921 () =>922 Effect.gen(function* () {923 const claims = fakeLimit(2);968 const proposals = fakeLimit(1);969 const drafts = fakeLimit(1);924 const posts = fakeLimit(1);925926 const spent = yield* RateLimits.use(({ check }) =>927 Effect.all([928 Effect.result(check("claim", Handle.make("Alice"))),929 Effect.result(check("claim", Handle.make("alice"))),930 Effect.result(check("claim", Handle.make("alice"))),931 Effect.result(check("claim", Handle.make("bob"))),977 Effect.result(check("proposal", Handle.make("alice"))),978 Effect.result(check("proposal", Handle.make("alice"))),979 Effect.result(check("draft", Handle.make("alice"))),980 Effect.result(check("draft", Handle.make("Alice"))),932 Effect.result(check("post", Handle.make("alice"))),933 Effect.result(check("post", Handle.make("Alice"))),934 ])935 ).pipe(936 Effect.provide(984 WorkerRateLimits({985 claim: claims.binding,986 draft: drafts.binding,987 proposal: proposals.binding,988 })937 WorkerRateLimits({ claim: claims.binding, post: posts.binding })938 )939 );940941 expect(spent).toStrictEqual([
9 unmodified lines
951 Result.void,952 Result.void,953 Result.fail(954 new CapReached({1006 cap: WorkerCaps.proposal,1007 limit: "proposals",955 cap: WorkerCaps.post,956 limit: "discussions",957 retryAfter: 60,958 })959 ),1011 Result.void,1012 Result.fail(1013 new CapReached({1014 cap: WorkerCaps.draft,1015 limit: "drafts",1016 retryAfter: 60,1017 })1018 ),960 ]);961 expect(claims.keys).toStrictEqual(["alice", "alice", "alice", "bob"]);1021 expect(proposals.keys).toStrictEqual(["alice", "alice"]);1022 expect(drafts.keys).toStrictEqual(["alice", "alice"]);962 expect(posts.keys).toStrictEqual(["alice", "alice"]);963 })964 );965966 it.effect("die when the binding fails, rather than let a call through", () =>
5 unmodified lines
972 const spent = yield* Effect.exit(973 RateLimits.use(({ check }) =>974 check("claim", Handle.make("alice"))975 ).pipe(1036 Effect.provide(1037 WorkerRateLimits({ claim: broken, draft: broken, proposal: broken })1038 )976 Effect.provide(WorkerRateLimits({ claim: broken, post: broken }))977 )978 );979980 expect(Exit.hasDies(spent)).toBeTruthy();
24 unmodified lines
1005 WorkerCaps.claim,1006 WorkerCaps.claim,1007 WorkerCaps.claim,1008 ]);1071 expect(limitsOf("PROPOSAL_LIMIT")).toStrictEqual([1072 WorkerCaps.proposal,1073 WorkerCaps.proposal,1074 WorkerCaps.proposal,1009 expect(limitsOf("POST_LIMIT")).toStrictEqual([1010 WorkerCaps.post,1011 WorkerCaps.post,1012 WorkerCaps.post,1013 ]);1014 }).pipe(Effect.provide(NodeServices.layer))1015 );1016});
modified:apps/platform/test/harness.ts+1 added-4 removed
129 unmodified lines
130 Layer.succeed(ReleaseStore, ReleaseStore.of({ get: unused("ReleaseStore") })),131 FrontPageMemory.layer({ credits: [], entries: [], projects: [] }),132 Layer.succeed(RepoHost, untouchable<RepoHost["Service"]>("RepoHost")),133 Layer.succeed(Stage, Stage.of({ name: "local" })),134 Layer.succeed(135 HostInfo,136 HostInfo.of({ draftModel: "test-model", webUrl: Option.none() })137 )134 Layer.succeed(HostInfo, HostInfo.of({ webUrl: Option.none() }))135);136137export const noProjects = Handlers.pipe(138 Layer.provide([
62 unmodified lines
modified:apps/platform/test/home.test.ts+2 added-9 removed
65 unmodified lines
66 made,67 noProjects,68 MemorySessions.layer({}),69 FrontPageMemory.layer({ credits: [], entries: [], projects: listed }),70 Layer.succeed(71 HostInfo,72 HostInfo.of({ draftModel: "@cf/test/drafter", webUrl: web })73 )70 Layer.succeed(HostInfo, HostInfo.of({ webUrl: web }))71 )72 );7374const home = (
36 unmodified lines
111 `${origin}/.well-known/oauth-protected-resource`,112 `${origin}/.well-known/oauth-authorization-server`,113 `${origin}/signup`,114 `${origin}/authorize`,118 "@cf/test/drafter",115 `${origin}/health`,116 `<a href="${webUrl}">Open the web app</a>`,117 ]) {118 expect(text).toContain(named);
133 unmodified lines
252 MemorySessions.layer({}),253 FrontPageMemory.layer({ credits: [], entries: [], projects }),254 Layer.succeed(255 HostInfo,260 HostInfo.of({261 draftModel: "@cf/test/drafter",262 webUrl: Option.some(webUrl),263 })256 HostInfo.of({ webUrl: Option.some(webUrl) })257 )258 )259 );260
84 unmodified lines
modified:apps/platform/test/mcp.test.ts-17 removed
15 unmodified lines
16 DiscussionId,17 Handle,18 LaneName,19 ProjectName,20 ProposalId,20 RepoPath,21 keyOf,22 RequestId,23} from "@repo/protocol/ids";
355 unmodified lines
379 [EnvSchemaOf._tag]: {380 args: { project: nowhere },381 refusal: new UnknownProject({ project: nowhere }),382 },384 draftAsk: {385 args: { project: nowhere, proposal: ProposalId.make("prop-000001") },386 refusal: new UnknownProject({ project: nowhere }),387 },383 finish: {384 args: { ask: fixWeek, base, head, project, requestId },385 refusal: new NotDecider({}),386 },392 flagAsk: {393 args: { ask: nope, project, reason: "the want names a file" },394 refusal: new UnknownAsk({ ask: nope }),395 },387 fork: {388 args: { project: nowhere },389 refusal: new UnknownProject({ project: nowhere }),390 },
46 unmodified lines
437 projectPolicy: {438 args: { project: nowhere },439 refusal: new UnknownProject({ project: nowhere }),440 },450 proposeAsk: {451 args: { project: nowhere, want },452 refusal: new UnknownProject({ project: nowhere }),453 },441 readFile: {442 args: { at: untagged, path: RepoPath.make("README.md"), project },443 refusal: new UnknownRevision({ rev: untagged }),444 },
14 unmodified lines
459 refusal: new UnknownDiscussion({460 discussion: DiscussionId.make("disc-000001"),461 }),462 },476 showProposal: {477 args: { project: nowhere, proposal: ProposalId.make("prop-000001") },478 refusal: new UnknownProject({ project: nowhere }),479 },463 status: {464 args: { project: nowhere },465 refusal: new UnknownProject({ project: nowhere }),466 },
531 unmodified lines
modified:apps/platform/test/pages.test.ts+1 added-4 removed
81 unmodified lines
82 })83 ),84 Layer.succeed(85 HostInfo,86 HostInfo.of({87 draftModel: "@cf/test/drafter",88 webUrl: Option.some("https://web.example"),89 })86 HostInfo.of({ webUrl: Option.some("https://web.example") })87 )88 )89 )90);
724 unmodified lines
modified:apps/platform/test/serve-world.ts+1 added-28 removed
4 unmodified lines
5import type { RepoHost } from "@repo/artifacts/repo-host";6import { CheckRunner, shaOf } from "@repo/checks/check-runner";7import type { CheckAt } from "@repo/checks/check-runner";8import { CheckRunnerLocal } from "@repo/checks/check-runner/local";9import { cannedDrafter } from "@repo/drafting/draft-runs/canned";10import { draftRunsInline } from "@repo/drafting/draft-runs/inline";11import type { InlinePorts } from "@repo/drafting/draft-runs/inline";12import type { Drafter } from "@repo/drafting/drafter";9import { Projects } from "@repo/project/projects";10import { VerifierBlocked } from "@repo/protocol/refusal";11import { git } from "@repo/testkit/git";12import { untouchable } from "@repo/testkit/untouchable";13import {14 Console,19 Context,20 Deferred,15 Duration,16 Effect,17 FileSystem,18 Layer,
100 unmodified lines
119 worker: all,120 };121 };122129const withDrafts = (130 plugIn: PlugIn,131 ready: Deferred.Deferred<Context.Context<InlinePorts>>,132 drafter: Context.Context<Drafter>133): PlugIn => ({134 project: Layer.merge(135 plugIn.project ?? Layer.empty,136 draftRunsInline(Deferred.await(ready))137 ),138 worker: Layer.merge(139 plugIn.worker ?? Layer.empty,140 Layer.effectDiscard(141 Effect.flatMap(Effect.context<Projects | RepoHost>(), (ports) =>142 Deferred.succeed(ready, Context.merge(drafter, ports))143 )144 )145 ),146});147123const CARRY_EVERY = Duration.millis(250);124125const serve = Effect.gen(function* () {126 yield* shimWorkers;
9 unmodified lines
136 const { decodeEnv } = yield* Effect.promise(137 () => import("../src/platform.ts")138 );139165 const drafter = yield* Layer.build(cannedDrafter);166 const ready = yield* Deferred.make<Context.Context<InlinePorts>>();140 const plugged = cartridgesOver(cartridges, decodeEnv);141142 const world = yield* coreLoopWorld({143 checker: localChecker,171 plugIn: (aside) => withDrafts(plugged(aside), ready, drafter),144 plugIn: plugged,145 sessions,146 });147148 yield* world.settle().pipe(
18 unmodified lines
modified:apps/platform/test/w9-contracts.test.ts+4 added-7 removed
1import { describe, expect, it } from "@effect/vitest";2import { Projects } from "@repo/project/projects";3import { AskId, Handle, ProposalId, RepoPath } from "@repo/protocol/ids";3import { AskId, Handle, RepoPath } from "@repo/protocol/ids";4import { Unauthenticated } from "@repo/protocol/principal";5import { advanceTo } from "@repo/testkit/clock";6import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";7import { Effect, Exit, Layer } from "effect";
25 unmodified lines
33 Layer.mergeAll(Handlers.pipe(Layer.provide(ports)), ports, sessions)34 );35});3637describe("the code, policy and drafting contracts over /rpc", () => {37describe("the code, policy and discussion contracts over /rpc", () => {38 it.effect("give anyone a project's policy, without its layers", () =>39 Effect.gen(function* () {40 const { handler } = yield* platform;41 const anyone = yield* rpcClient(handler);
48 unmodified lines
90 ).toStrictEqual([[first?.sha, "alice"]]);91 })92 );9394 it.effect("refuse a draft to anyone not signed in", () =>94 it.effect("refuse a post to anyone not signed in", () =>95 Effect.gen(function* () {96 const { handler } = yield* platform;97 const anyone = yield* rpcClient(handler);9899 expect(100 yield* Effect.exit(101 anyone.draftAsk({102 project,103 proposal: ProposalId.make("prop-000001"),104 })101 anyone.postDiscussion({ project, title: "ISO week dates" })102 )103 ).toStrictEqual(Exit.fail(new Unauthenticated()));104 })105 );
97 unmodified lines
modified:apps/platform/package.json-1 removed
13 unmodified lines
14 "@repo/agent-kit": "workspace:*",15 "@repo/artifacts": "workspace:*",16 "@repo/brand": "workspace:*",17 "@repo/checks": "workspace:*",18 "@repo/drafting": "workspace:*",18 "@repo/gate": "workspace:*",19 "@repo/git": "workspace:*",20 "@repo/project": "workspace:*",21 "@repo/protocol": "workspace:*",
18 unmodified lines
modified:apps/platform/worker-configuration.d.ts+5 added-14 removed
1/* eslint-disable */2// Generated by Wrangler by running `wrangler types --include-runtime=false --strict-vars=false` (hash: d86181b89e45aafbd21bd32eeae49b73)2// Generated by Wrangler by running `wrangler types --include-runtime=false --strict-vars=false` (hash: 04eea0cac6aa30010ef487d391f8719e)3interface __BaseEnv_Env {4 OAUTH_KV: KVNamespace;5 EVIDENCE: R2Bucket;6 RELEASES: R2Bucket;
3 unmodified lines
10 METRICS: AnalyticsEngineDataset;11 ARTIFACTS: Artifacts;12 ARTIFACTS_PRIVATE: Artifacts;13 CLAIM_LIMIT: RateLimit;14 PROPOSAL_LIMIT: RateLimit;14 POST_LIMIT: RateLimit;15 SIGN_IN_LIMIT: RateLimit;16 DRAFT_LIMIT: RateLimit;16 LOADER: WorkerLoader;18 AI: Ai;17 OPERATOR_HANDLE: string;18 STAGE: string;19 LANDER_ADAPTER: string;22 DRAFT_MODEL: string;20 PUBLIC_WEB_URL: string;21 OPERATOR_TOKEN: string;22 COOKIE_KEY: string;23 PASSWORD_PEPPER: string;
18 unmodified lines
42 METRICS: AnalyticsEngineDataset;43 ARTIFACTS: Artifacts;44 ARTIFACTS_PRIVATE: Artifacts;45 CLAIM_LIMIT: RateLimit;49 PROPOSAL_LIMIT: RateLimit;46 POST_LIMIT: RateLimit;47 SIGN_IN_LIMIT: RateLimit;51 DRAFT_LIMIT: RateLimit;48 LOADER: WorkerLoader;53 AI: Ai;49 OPERATOR_HANDLE: string;50 STAGE: string;51 LANDER_ADAPTER: string;57 DRAFT_MODEL: string;52 PUBLIC_WEB_URL: string;53 OPERATOR_TOKEN: string;54 COOKIE_KEY: string;55 PASSWORD_PEPPER: string;
13 unmodified lines
69 METRICS: AnalyticsEngineDataset;70 ARTIFACTS: Artifacts;71 ARTIFACTS_PRIVATE: Artifacts;72 CLAIM_LIMIT: RateLimit;79 PROPOSAL_LIMIT: RateLimit;73 POST_LIMIT: RateLimit;74 SIGN_IN_LIMIT: RateLimit;81 DRAFT_LIMIT: RateLimit;75 LOADER: WorkerLoader;83 AI: Ai;76 OPERATOR_HANDLE: string;77 STAGE: string;78 LANDER_ADAPTER: string;87 DRAFT_MODEL: string;79 PUBLIC_WEB_URL: string;80 OPERATOR_TOKEN: string;81 COOKIE_KEY: string;82 PASSWORD_PEPPER: string;
9 unmodified lines
92type StringifyValues<EnvType extends Record<string, unknown>> = {93 [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;94};95declare namespace NodeJS {105 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">> {}96 interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "OPERATOR_HANDLE" | "STAGE" | "LANDER_ADAPTER" | "PUBLIC_WEB_URL" | "OPERATOR_TOKEN" | "COOKIE_KEY" | "PASSWORD_PEPPER" | "MASTER_KEY">> {}97}
modified:apps/platform/wrangler.jsonc+4 added-28 removed
65 unmodified lines
66 "OPERATOR_HANDLE": "oscabriel",67 "STAGE": "local",68 // "container" (apps/sandbox) or "isogit" (in this Worker).69 "LANDER_ADAPTER": "container",70 // The Workers AI model that drafts asks; swap it here, no code change.71 "DRAFT_MODEL": "@cf/moonshotai/kimi-k2.7-code",70 // The web app, which `/` links to: `vite dev`'s URL locally.71 "PUBLIC_WEB_URL": "http://localhost:5173",72 },73 "secrets": {
44 unmodified lines
118 // Sign-in's mail (Cloudflare Email Service). `wrangler dev` only logs119 // each mail, code included, so no real mail leaves a local run.120 "send_email": [{ "name": "EMAIL" }],121 "worker_loaders": [{ "binding": "LOADER" }],124 // Workers AI, for the drafter (no key: the account's own).125 "ai": { "binding": "AI" },126 // Domain metrics (landings, refusals, lanes, waits, drafts) in Workers122 // Domain metrics (landings, refusals, lanes and waits) in Workers123 // Analytics Engine, one dataset per stage so no stage's counts mix with124 // another's. A dataset is made by its first write, so bootstrap makes none;125 // its name takes `_`, since SQL reads it as a table.126 "analytics_engine_datasets": [
8 unmodified lines
135 "namespace_id": "1001",136 "simple": { "limit": 10, "period": 60 },137 },138 {143 "name": "PROPOSAL_LIMIT",139 "name": "POST_LIMIT",140 "namespace_id": "1002",141 "simple": { "limit": 5, "period": 60 },142 },143 // Sign-in attempts per handle and per client address: the
2 unmodified lines
146 "name": "SIGN_IN_LIMIT",147 "namespace_id": "1003",148 "simple": { "limit": 5, "period": 60 },149 },154 // Drafts per person: each one is a model call and Checker runs.155 {156 "name": "DRAFT_LIMIT",157 "namespace_id": "1004",158 "simple": { "limit": 2, "period": 60 },159 },150 ],151 "triggers": {152 "events": [153 {
8 unmodified lines
162 "vars": {163 "OPERATOR_HANDLE": "oscabriel",164 "STAGE": "dev-oscabriel",165 "LANDER_ADAPTER": "container",176 "DRAFT_MODEL": "@cf/moonshotai/kimi-k2.7-code",166 "PUBLIC_WEB_URL": "https://web-dev-oscabriel.oscargabriel.workers.dev",167 },168 "secrets": {169 "required": [
40 unmodified lines
210 { "binding": "CODE_CACHE", "bucket_name": "code-cache-dev-oscabriel" },211 ],212 "send_email": [{ "name": "EMAIL" }],213 "worker_loaders": [{ "binding": "LOADER" }],225 "ai": { "binding": "AI" },214 "analytics_engine_datasets": [215 { "binding": "METRICS", "dataset": "metrics_dev_oscabriel" },216 ],217 "services": [
5 unmodified lines
223 "namespace_id": "1101",224 "simple": { "limit": 10, "period": 60 },225 },226 {239 "name": "PROPOSAL_LIMIT",227 "name": "POST_LIMIT",228 "namespace_id": "1102",229 "simple": { "limit": 5, "period": 60 },230 },231 {232 "name": "SIGN_IN_LIMIT",233 "namespace_id": "1103",234 "simple": { "limit": 5, "period": 60 },235 },248 {249 "name": "DRAFT_LIMIT",250 "namespace_id": "1104",251 "simple": { "limit": 2, "period": 60 },252 },236 ],237 "triggers": {238 "events": [239 {
15 unmodified lines
255 "vars": {256 "OPERATOR_HANDLE": "oscabriel",257 "STAGE": "prod",258 "LANDER_ADAPTER": "container",276 "DRAFT_MODEL": "@cf/moonshotai/kimi-k2.7-code",259 "PUBLIC_WEB_URL": "https://from-infra-deploy.invalid",260 },261 "secrets": {262 "required": [
36 unmodified lines
299 { "binding": "CODE_CACHE", "bucket_name": "code-cache-prod" },300 ],301 "send_email": [{ "name": "EMAIL" }],302 "worker_loaders": [{ "binding": "LOADER" }],321 "ai": { "binding": "AI" },303 "analytics_engine_datasets": [304 { "binding": "METRICS", "dataset": "metrics_prod" },305 ],306 "services": [{ "binding": "SANDBOX", "service": "sandbox-prod" }],
3 unmodified lines
310 "namespace_id": "1301",311 "simple": { "limit": 10, "period": 60 },312 },313 {333 "name": "PROPOSAL_LIMIT",314 "name": "POST_LIMIT",315 "namespace_id": "1302",316 "simple": { "limit": 5, "period": 60 },317 },318 {319 "name": "SIGN_IN_LIMIT",320 "namespace_id": "1303",321 "simple": { "limit": 5, "period": 60 },322 },342 {343 "name": "DRAFT_LIMIT",344 "namespace_id": "1304",345 "simple": { "limit": 2, "period": 60 },346 },323 ],324 "triggers": {325 "events": [326 {
11 unmodified lines
modified:apps/web/e2e/a11y.e2e.ts+3 added-9 removed
75 unmodified lines
76 name: "answer, unclaimed",77 path: `/${project}/answers/lint-heading-levels`,78 },79 { name: "visibility", path: `/${project}/visibility` },80 { name: "policy", path: `/${project}/people` },80 { name: "policy", path: `/${project}/policy` },81 { name: "asks", path: `/${project}/asks` },82 { name: "discussions", path: `/${project}/discussions` },83 { name: "refs", path: `/${project}/refs` },84 { name: "tree", path: `/${project}/tree/main` },85 { name: "folder", path: `/${project}/tree/main/packages/render/src` },86 { name: "blob", path: `/${project}/blob/main/packages/render/src/page.ts` },
9 unmodified lines
96 name: "decision, signed out",97 path: `/${project}/decisions/dec-000002`,98 },99 { name: "finish", path: `/${project}/decisions/dec-000004`, signedIn: true },98 { name: "proposal, ready", path: `/${project}/proposals/prop-000002` },99 { name: "proposal, failed", path: `/${project}/proposals/prop-000003` },100 {101 name: "propose",102 path: `/${project}/proposals/new`,103 signedIn: true,104 },105 { name: "propose, signed out", path: `/${project}/proposals/new` },100 { name: "person", path: `/people/${DECIDER}` },101 { name: "install", path: "/install" },102 { name: "unknown project", path: "/no-such-project", status: 404 },103 {
573 unmodified lines
modified:apps/web/e2e/imports.e2e.ts+3 added-3 removed
387 unmodified lines
388 texts: ["Landed at", "Tags"],389 })390 ));391392 test(`${project}'s people show ${evaluated ? "the defaults policy" : "that its policy is not evaluated"}`, ({392 test(`${project}'s policy page shows ${evaluated ? "the defaults policy" : "that its policy is not evaluated"}`, ({393 page: browser,394 }) =>395 Effect.runPromise(396 visit(397 browser,398 project,399 `${homeOf(project)}/people`,400 "people",399 `${homeOf(project)}/policy`,400 "policy",401 evaluated402 ? { selectors: ['[data-paths="**"]'] }403 : {404 texts: [
321 unmodified lines
modified:apps/web/e2e/people.e2e.ts+1 added-1 removed
34 unmodified lines
35 Effect.gen(function* () {36 const web = Option.getOrElse(settings.web, () => "");3738 const response = yield* Effect.promise(() =>39 browser.goto(`${web}/${project}/people`)39 browser.goto(`${web}/${project}/policy`)40 );4142 expect(response?.status()).toBe(200);43
30 unmodified lines
modified:apps/web/src/client/keys.ts+1 added-10 removed
1// Each key is one string: Reactivity treats every element of a key list as a key of its own.2import type {3 AskId,4 DiscussionId,5 ProjectName,6 ProposalId,7} from "@repo/protocol/ids";2import type { AskId, DiscussionId, ProjectName } from "@repo/protocol/ids";34export const keys = {5 ask: (project: ProjectName, ask: AskId): readonly string[] => [6 `ask:${project}/${ask}`,
15 unmodified lines
22 front: (): readonly string[] => ["front"],23 ledger: (project: ProjectName): readonly string[] => [`ledger:${project}`],24 policy: (project: ProjectName): readonly string[] => [`policy:${project}`],25 project: (project: ProjectName): readonly string[] => [`project:${project}`],31 proposal: (project: ProjectName, proposal: ProposalId): readonly string[] => [32 `proposal:${project}/${proposal}`,33 `project:${project}`,34 ],26 today: (): readonly string[] => ["today"],27};
deleted:apps/web/src/client/proposal.ts-46 removed
1import type { DraftAsk } from "@repo/protocol/contracts";2import type { ProjectName, ProposalId } from "@repo/protocol/ids";3import { Effect } from "effect";4import { Atom, Reactivity } from "effect/reactivity";56import { ContractsClient } from "../surfaces.ts";7import { keys } from "./keys.ts";89export const proposalAtom = Atom.family((project: ProjectName) =>10 Atom.family((proposal: ProposalId) =>11 Atom.withServerValueInitial(12 ContractsClient.query(13 "showProposal",14 { project, proposal },15 { reactivityKeys: keys.proposal(project, proposal) }16 )17 )18 )19);2021export const projectTodayAtom = Atom.family((project: ProjectName) =>22 Atom.withServerValueInitial(23 ContractsClient.query(24 "today",25 { project },26 { reactivityKeys: [...keys.today(), ...keys.project(project)] }27 )28 )29);3031// Reads again on `DraftInProgress` or `ProposalClosed` too, since then the page shows a stale state.32export const draftAtom = ContractsClient.runtime.fn<33 typeof DraftAsk.payloadSchema.Type34>()(35 Effect.fnUntraced(function* (input) {36 const client = yield* ContractsClient;37 const changed = keys.proposal(input.project, input.proposal);3839 return yield* client("draftAsk", input).pipe(40 Reactivity.mutation(changed),41 Effect.tapErrorTag(["DraftInProgress", "ProposalClosed"], () =>42 Reactivity.invalidate(changed)43 )44 );45 })46);
deleted:apps/web/src/client/propose.ts-57 removed
1import type { ProposeAsk } from "@repo/protocol/contracts";2import { RepoPath } from "@repo/protocol/ids";3import type { ProjectName, ProposalId } from "@repo/protocol/ids";4import { Array, Effect, Option, Order, Schema } from "effect";5import { AsyncResult, Atom, Reactivity } from "effect/reactivity";67import { ContractsClient } from "../surfaces.ts";8import { keys } from "./keys.ts";910const decodePath = Schema.decodeUnknownOption(RepoPath);1112export const topFolders = (paths: readonly RepoPath[]): readonly RepoPath[] => {13 const folders = paths.flatMap((path): readonly RepoPath[] => {14 const slash = path.indexOf("/");1516 return slash <= 0 || path.startsWith(".")17 ? []18 : Option.toArray(decodePath(path.slice(0, slash)));19 });2021 return Array.sort(Array.dedupe(folders), Order.String);22};2324export const modulesAtom = Atom.family((project: ProjectName) =>25 Atom.withServerValueInitial(26 ContractsClient.runtime.factory.withReactivity(keys.code(project))(27 ContractsClient.runtime.atom(28 Effect.gen(function* () {29 const client = yield* ContractsClient;30 const { paths } = yield* client("listPaths", { at: "main", project });3132 return topFolders(paths);33 })34 )35 )36 )37);3839// While a later send is on its way, or was refused, the atom still holds an earlier proposal; that names none here.40export const proposalMade = (41 result: AsyncResult.AsyncResult<typeof ProposeAsk.successSchema.Type, unknown>42): Option.Option<ProposalId> =>43 AsyncResult.isSuccess(result) && !result.waiting44 ? Option.some(result.value.proposal.id)45 : Option.none();4647export const proposeAtom = ContractsClient.runtime.fn<48 typeof ProposeAsk.payloadSchema.Type49>()(50 Effect.fnUntraced(function* (input) {51 const client = yield* ContractsClient;5253 return yield* client("proposeAsk", input).pipe(54 Reactivity.mutation(keys.project(input.project))55 );56 })57);
modified:apps/web/src/client/watch.ts+6 added-3 removed
47 unmodified lines
48 event: ProjectEvent49): readonly string[] =>50 ProjectEvent.match(event, {51 AskClosed: () => [...keys.project(project), ...keys.front()],52 AskOpened: () => [...keys.project(project), ...keys.front()],52 // An ask a maintainer opens from a discussion marks that thread asked.53 AskOpened: () => [54 ...keys.project(project),55 ...keys.front(),56 ...keys.discussions(project),57 ],58 Claimed: () => keys.project(project),59 Decided: () => keys.project(project),60 DiscussionPosted: ({ discussion }) => [61 ...keys.discussion(project, discussion),
7 unmodified lines
69 ...keys.policy(project),70 ],71 Lapsed: () => keys.project(project),72 LedgerAppended: () => keys.ledger(project),68 ProposalDrafted: ({ proposal }) => keys.proposal(project, proposal),69 ProposalOpened: () => keys.project(project),73 Pushed: ({ ask }) => keys.ask(project, ask),74 Released: () => keys.project(project),75 Warned: ({ ask }) => keys.ask(project, ask),76 });
65 unmodified lines
modified:apps/web/src/dev/fixtures/fillers.ts+4 added-3 removed
157 unmodified lines
158 `${configDir}/policy.json`,159 policyJson({160 asks: [...stated],161 deciders: [{ handles: [project.decider], paths: "**" }],162 functions: { admit: false, opensAlone: false },162 functions: { admit: false },163 kinds: [164 {165 checkKind: "redThenGreen",166 claimers: "vouched",
61 unmodified lines
228229 const clock = yield* DevClock;230231 yield* clock.set(devMinute(at + 2));232 yield* api.proposeAsk(Person.make({ handle: visitors.regular }), {233 want: `${project.project} sheds load by route, not only in total.`,232 yield* api.postDiscussion(Person.make({ handle: visitors.regular }), {233 body: `Could ${project.project} shed load by route, not only in total?`,234 title: "Shed load by route",235 });236 }),237 { discard: true }238 );
modified:apps/web/src/dev/fixtures/record.ts-17 removed
8 unmodified lines
9import { Ask } from "@repo/protocol/domain/ask";10import type { AskListing } from "@repo/protocol/domain/ask";11import { ClaimView } from "@repo/protocol/domain/claim";12import { ForkRef } from "@repo/protocol/domain/code";13import { ConfigFile } from "@repo/protocol/domain/common";13import { Decision } from "@repo/protocol/domain/decision";14import type { Choice, Today } from "@repo/protocol/domain/decision";15import { EnvSchemaView } from "@repo/protocol/domain/env";16import { ProjectEvent } from "@repo/protocol/domain/event";17import { LandingView } from "@repo/protocol/domain/landing";19import { Proposal } from "@repo/protocol/domain/proposal";18import type { CreditSummary } from "@repo/protocol/domain/record";19import { Ledger } from "@repo/protocol/domain/visibility";20import { sameHandle } from "@repo/protocol/ids";21import type {
1 unmodified line
23 CommitSha,24 DecisionId,25 Handle,26 LandedSha,29 ProposalId,27} from "@repo/protocol/ids";28import {29 DecisionClosed,30 NotDecider,
2 unmodified lines
33import { Array, DateTime, Effect, Option, Schema } from "effect";3435import { present } from "./story.ts";3640export interface HeldProposal {41 readonly files: readonly ConfigFile[];42 readonly proposal: Proposal;43}4437export interface KeptLog {38 readonly claimant: Handle;39 readonly lane: Verdict["lanes"][number]["lane"];40 readonly text: string;
14 unmodified lines
55 readonly head: LandedSha;56 readonly landings: readonly LandingView[];57 readonly ledger: Ledger;58 readonly logs: ReadonlyMap<string, KeptLog>;67 readonly proposals: ReadonlyMap<ProposalId, HeldProposal>;59 readonly verdicts: ReadonlyMap<AskId, readonly Verdict[]>;60}6162const asType = <S extends Schema.Top>(schema: S) =>
15 unmodified lines
78 yield* many(LandingView, record.landings);79 yield* many(Decision, record.decisions);80 yield* many(ClaimView, record.claims);81 yield* many(ForkRef, record.forks);91 yield* many(92 Proposal,93 [...record.proposals.values()].map((held) => held.proposal)94 );95 yield* many(96 ConfigFile,97 [...record.proposals.values()].flatMap(({ files }) => files)98 );82 yield* asType(Ledger)(record.ledger);83 yield* asType(EnvSchemaView)(record.env);8485 return record;
101 unmodified lines
modified:apps/web/src/dev/fixtures/story.ts+2 added-56 removed
31 unmodified lines
32 RequestId,33 SuiteRoot,34 TreeSha,35} from "@repo/protocol/ids";36import type {37 AskId,38 Handle,39 ProjectName,40 ProposalId,41} from "@repo/protocol/ids";36import type { AskId, Handle, ProjectName } from "@repo/protocol/ids";37import { Array, DateTime, Effect, Option, Record } from "effect";3839import { overlay, personIdentity, platformIdentity, scratch } from "../git.ts";40import type { Files } from "../git.ts";46import type { FixtureRecord, HeldProposal, KeptLog } from "./record.ts";41import type { FixtureRecord, KeptLog } from "./record.ts";4243const MODULUS = 4_294_967_291;4445export const hexOf = (label: string, count: number): string => {
87 unmodified lines
133 const landings: LandingView[] = [];134 const claims = new Map<AskId, Held[]>();135 const decisions: Decision[] = [];136 const ledger: LedgerEntry[] = [];142 const proposals = new Map<ProposalId, HeldProposal>();137 const logs = new Map<string, KeptLog>();138 const firstClaims = new Map<Handle, DateTime.Utc>();139 const forked = new Set<RepoName>();140
506 unmodified lines
647 })648 );649 },650657 propose: (658 held: HeldProposal,659 settled?: { readonly at: DateTime.Utc; readonly ready: boolean }660 ) => {661 proposals.set(held.proposal.id, held);662 tell((seq) =>663 ProjectEvent.cases.ProposalOpened.make({664 at: held.proposal.openedAt,665 proposal: held.proposal.id,666 seq,667 })668 );669670 if (settled !== undefined) {671 tell((seq) =>672 ProjectEvent.cases.ProposalDrafted.make({673 at: settled.at,674 proposal: held.proposal.id,675 ready: settled.ready,676 seq,677 })678 );679 }680 },681682 drafted: (id: ProposalId, at: DateTime.Utc, ready: boolean) => {683 tell((seq) =>684 ProjectEvent.cases.ProposalDrafted.make({685 at,686 proposal: id,687 ready,688 seq,689 })690 );691 },692693 accepted: (id: ProposalId) => {694 const held = proposals.get(id);695696 if (held !== undefined) {697 proposals.set(id, {698 ...held,699 proposal: { ...held.proposal, state: "accepted" },700 });701 }702 },703651 tag: (name: string, sha: LandedSha) =>652 Effect.gen(function* () {653 const into = yield* scratch;654
96 unmodified lines
751 head,752 landings: [...landings],753 ledger: { ...apart.ledger, entries: [...ledger] },754 logs: new Map(logs),808 proposals: new Map(proposals),755 verdicts: new Map(verdicts),756 };757 },758 };
3 unmodified lines
modified:apps/web/src/dev/fixtures/vellum.ts+9 added-240 removed
6 unmodified lines
7import type { Decision, DecisionSubject } from "@repo/protocol/domain/decision";8import { DecisionSubject as Subject } from "@repo/protocol/domain/decision";9import type { EnvSchemaView } from "@repo/protocol/domain/env";10import { Outcome } from "@repo/protocol/domain/outcome";11import { DraftState } from "@repo/protocol/domain/proposal";12import type { Proposal } from "@repo/protocol/domain/proposal";11import { Territory } from "@repo/protocol/domain/territory";12import { LedgerEntry } from "@repo/protocol/domain/visibility";13import type { Ledger } from "@repo/protocol/domain/visibility";16import type { Handle, LandedSha } from "@repo/protocol/ids";14import type { LandedSha } from "@repo/protocol/ids";15import {16 AreaName,17 AskId,18 DecisionId,19 EnvKey,20 Handle,21 KindName,23 LaneName,22 keyOf,23 LayerName,24 ProjectName,27 ProposalId,25 RatchetName,26 RepoName,27 RepoPath,28} from "@repo/protocol/ids";
32 unmodified lines
61 ines: datekitPeople.decider,62 lin: burrowPeople.second,63 okafor: burrowPeople.decider,64 okonkwo: datekitPeople.zones,68 sefa: visitors.flagger,69 tove: visitors.proposer,65 sefa: Handle.make("sefa"),66 tove: visitors.asker,67 wren: visitors.regular,68} as const;6970export { operator as vellumInitializer } from "../examples.ts";
120 unmodified lines
191const HOUR_MS = 3_600_000;192193const policy = policyJson({194 asks: [],198 caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },195 caps: { claimsPerPerson: 3 },196 claims: {197 lapseAfterMs: CLAIMS.lapseAfter.hours * HOUR_MS,198 warnAfterMs: CLAIMS.warnAfter.hours * HOUR_MS,199 },
4 unmodified lines
204 { handles: [people.okonkwo], paths: ".env.schema" },205 { handles: [people.okonkwo], paths: `${dir}/vouched.td` },206 ],207 decisions: { expireDays: 3 },211 functions: { admit: false, opensAlone: false },208 functions: { admit: false },209 kinds: [210 {211 checkKind: "redThenGreen",212 claimers: "vouched",
138 unmodified lines
351 people.okafor,352 people.lin,353 `${people.tove} Started with the CLI docs.`,354 `${people.sefa} Came from the parser's issue thread.`,358 `-${people.wren} Opened proposals that advertised a paid fork.`,355 `-${people.wren} Opened discussions that advertised a paid fork.`,356 "",357 ].join("\n"),358 ],359]);
283 unmodified lines
643644const decisionId = (n: number) =>645 DecisionId.make(`dec-${String(n).padStart(6, "0")}`);646650const proposalId = (n: number) =>651 ProposalId.make(`prop-${String(n).padStart(6, "0")}`);652647const EXPIRY = { days: 3 } as const;648649const decision = (input: {650 readonly n: number;
126 unmodified lines
777 ],778 project: vellum,779});780787const proposal = (input: {788 readonly n: number;789 readonly at: DateTime.Utc;790 readonly proposer: Handle;791 readonly want: string;792 readonly files: readonly RepoPath[];793 readonly draft?: Proposal["draft"];794 readonly state?: Proposal["state"];795}): Proposal => ({796 expiresAt: DateTime.add(input.at, { days: 14 }),797 files: input.files,798 id: proposalId(input.n),799 openedAt: input.at,800 project: vellum,801 proposer: input.proposer,802 state: input.state ?? "open",803 want: input.want,804 ...present("draft", input.draft),805});806807const draftedFiles = (id: string, module: Module, want: string) => {808 const stated = fix({ id, module, want });809 const [askFile, testFile] = [...filesOf([stated])];810811 const fixture = [812 `packages/${module}/test/fixtures/${id}.vm`,813 "- a list item\n > a quote inside it\n",814 ] as const;815816 return [askFile, testFile, fixture].flatMap((entry) =>817 entry === undefined818 ? []819 : [{ content: entry[1], path: RepoPath.make(entry[0]) }]820 );821};822781const childEntry = (module: Module): Files =>782 new Map([[`packages/${module}/src/index.ts`, entryOf(module, "tokenize")]]);783784const childPage = (module: Module): Files =>
397 unmodified lines
1182 at: t("2026-10-05T12:00"),1183 changes: childPage("themes"),1184 });11851228 // The lint ask came from tove's proposal.1229 story.propose({1230 files: [],1231 proposal: proposal({1232 at: t("2026-10-05T13:00"),1233 files: [],1234 n: 1,1235 proposer: people.tove,1236 want: ask.headings.brief.want,1237 }),1238 });1239 story.decision(1240 decision({1241 at: t("2026-10-05T13:00"),1242 deciders: [people.ines, people.lin],1243 evidence: [1244 { label: "want", value: ask.headings.brief.want },1245 { label: "territory", value: "@vellum/lint" },1246 ],1247 n: 3,1248 subject: Subject.cases.OpenProposal.make({ proposal: proposalId(1) }),1249 })1250 );12511186 const wrapHead = story.push(ask.wrap.id, t("2026-10-05T14:00"), 2);11871188 story.judge(ask.wrap.id, wrapHead, {1189 at: t("2026-10-05T14:00"),
58 unmodified lines
1248 files: filesOf([stated]),1249 });1250 }12511318 const ready = draftedFiles(1319 "parse-nested-quotes",1320 "parser",1321 "The parser reads a blockquote nested inside a list item."1322 );13231324 story.propose(1325 {1326 files: ready,1327 proposal: proposal({1328 at: t("2026-10-05T15:30"),1329 draft: DraftState.cases.Ready.make({1330 attempts: 1,1331 model: "memory",1332 red: {1333 lane: LaneName.make("redThenGreen"),1334 signature: "expected 1 blockquote, received 0",1335 },1336 round: 1,1337 }),1338 files: ready.map(({ path }) => path),1339 n: 2,1340 proposer: people.bram,1341 want: "The parser reads a blockquote nested inside a list item.",1342 }),1343 },1344 { at: t("2026-10-05T16:00"), ready: true }1345 );1346 story.decision(1347 decision({1348 at: t("2026-10-05T16:00"),1349 deciders: [people.ines],1350 evidence: [1351 {1352 label: "want",1353 value: "The parser reads a blockquote nested inside a list item.",1354 },1355 { label: "territory", value: "@vellum/parser" },1356 ...ready.map(({ content, path }) => ({1357 label: path,1358 value: content,1359 })),1360 {1361 label: "red first",1362 value: "redThenGreen: expected 1 blockquote, received 0",1363 },1364 { label: "drafted by", value: "memory, attempt 1 of 3" },1365 ],1366 n: 5,1367 subject: Subject.cases.OpenProposal.make({ proposal: proposalId(2) }),1368 })1369 );13701252 story.claim(1253 tokenizer.child("parser"),1254 people.tove,1255 t("2026-10-05T16:00"),
196 unmodified lines
1452 }),1453 })1454 );14551575 story.propose(1576 {1577 files: [],1578 proposal: proposal({1579 at: t("2026-10-06T14:30"),1580 draft: DraftState.cases.Failed.make({1581 attempts: 3,1582 model: "memory",1583 refusal: "NotRedFirst",1584 round: 1,1585 }),1586 files: [],1587 n: 3,1588 proposer: people.sefa,1589 want: "Themes can set their own font for code blocks.",1590 }),1591 },1592 { at: t("2026-10-06T15:00"), ready: false }1593 );1594 story.decision(1595 decision({1596 at: t("2026-10-06T15:00"),1597 deciders: [people.ines, people.lin],1598 evidence: [1599 {1600 label: "want",1601 value: "Themes can set their own font for code blocks.",1602 },1603 {1604 label: "draft failed",1605 value:1606 "The check passed on main, so it proves nothing about an answer.",1607 },1608 ],1609 n: 9,1610 subject: Subject.cases.OpenProposal.make({ proposal: proposalId(3) }),1611 })1612 );16131456 // The parser child: every lane passed, one held-back check in the parser did not.1457 const parserHead = story.push(1458 tokenizer.child("parser"),1459 t("2026-10-06T15:00")
68 unmodified lines
1528 line: 31,1529 path: RepoPath.make("packages/export/test/epub.test.ts"),1530 };15311690 const carryReason = "EPUB 2 readers come later; their own ask is drafted.";1532 const carryReason = "EPUB 2 readers come later, in an ask of their own.";15331534 story.judge(ask.carry.id, carryHead, {1535 at: t("2026-10-06T18:00"),1536 heldBack: [held(EXPORT, 7, 7), held(PARSER, 4, 4)],
26 unmodified lines
1563 }),1564 })1565 );15661725 const subsets = draftedFiles(1726 "export-font-subsets",1727 "export",1728 "Export embeds only the font subsets a document uses."1729 );17301731 story.propose(1732 {1733 files: subsets,1734 proposal: proposal({1735 at: t("2026-10-06T18:30"),1736 draft: DraftState.cases.Failed.make({1737 attempts: 1,1738 model: "memory",1739 refusal: "VerifierBlocked",1740 round: 2,1741 }),1742 files: subsets.map(({ path }) => path),1743 n: 4,1744 proposer: people.okafor,1745 want: "Export embeds only the font subsets a document uses.",1746 }),1747 },1748 { at: t("2026-10-06T19:00"), ready: true }1749 );1750 story.drafted(proposalId(4), t("2026-10-06T20:00"), false);1751 story.decision(1752 decision({1753 at: t("2026-10-06T20:00"),1754 deciders: [people.okonkwo],1755 evidence: [1756 {1757 label: "want",1758 value: "Export embeds only the font subsets a document uses.",1759 },1760 { label: "territory", value: "@vellum/export" },1761 ...subsets.map(({ content, path }) => ({1762 label: path,1763 value: content,1764 })),1765 {1766 label: "draft failed",1767 value:1768 "The Checker was busy; the platform could not run the check this round.",1769 },1770 ],1771 n: 12,1772 subject: Subject.cases.OpenProposal.make({ proposal: proposalId(4) }),1773 })1774 );17751567 story.claim(1568 ask.exportErrors.id,1569 people.tove,1570 t("2026-10-07T07:00"),
40 unmodified lines
1611 evidence: [1612 { label: "handle", value: people.wren },1613 {1614 label: "line",1824 value: `${people.wren} Asks to come back; proposals since are on topic.`,1615 value: `${people.wren} Asks to come back; posts since are on topic.`,1616 },1617 ],1618 n: 14,1619 subject: Subject.cases.Vouch.make({ handle: people.wren }),
1 unmodified line
1621 );16221623 story.push(ask.numbers.id, t("2026-10-07T08:15"));16241834 story.decide(decisionId(3), {1835 at: t("2026-10-07T08:30"),1836 by: people.ines,1837 choice: "accept",1838 note: "Clear want; tove's test covers the skip.",1839 });1840 story.accepted(proposalId(1));1625 yield* story.open({1626 asks: [ask.headings],1627 at: t("2026-10-07T08:30"),1628 by: people.ines,
24 unmodified lines
1653 outcome: Outcome.cases.Checking.make({ stage: "checks" }),1654 stage: "checks",1655 });16561873 story.propose({1874 files: [],1875 proposal: proposal({1876 at: t("2026-10-07T09:50"),1877 draft: DraftState.cases.Drafting.make({1878 round: 1,1879 startedAt: t("2026-10-07T09:50"),1880 }),1881 files: [],1882 n: 5,1883 proposer: people.lin,1884 want: "The CLI prints a table of contents with --toc.",1885 }),1886 });18871657 const apart = {1658 env: envAt(story.head(), t("2026-10-06T16:30")),1659 ledger,1660 working: [people.ines, people.okonkwo],
18 unmodified lines
modified:apps/web/src/dev/examples.ts+3 added-17 removed
1// The projects and their people are invented; any likeness to a real one is not meant.2import { Brand } from "@repo/brand";3import { cannedDraft } from "@repo/drafting/draft-runs/canned";3import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";4import { Command, SymbolName } from "@repo/protocol/domain/common";5import type { AskKind } from "@repo/protocol/domain/kind";6import { PolicyInput } from "@repo/protocol/domain/policy";
220 unmodified lines
227 want: "diffInDays counts calendar days across a daylight-saving change.",228 }),229];230232const draftedAsk: StatedAsk = {233 askedBy: datekitPeople.decider,234 blockedBy: [],235 brief: { current: cannedDraft.current, want: cannedDraft.want },236 check: encodeCheck(237 CheckSpec.cases.RedThenGreen.make({ path: cannedDraft.test.path })238 ),239 file: `${dir}/asks/${cannedDraft.id}.ask.ts`,240 id: cannedDraft.id,241 kind: cannedDraft.kind,242 territory: { module: ".", paths: [...cannedDraft.territory] },243};244231const library: Files = new Map([232 [233 "README.md",234 [
106 unmodified lines
341 ],342 [343 `${dir}/policy.json`,344 policyJson({359 asks: [...datekitAsks.map(({ stated }) => stated), draftedAsk],345 asks: datekitAsks.map(({ stated }) => stated),346 deciders: [347 { handles: [datekitPeople.decider], paths: "**" },348 { handles: [datekitPeople.zones], paths: "src/tz.ts" },349 ],364 functions: { admit: false, opensAlone: false },350 functions: { admit: false },351 kinds: [fix],352 ratchets: [],353 run: {354 checks: { types: "bun run typecheck" },
262 unmodified lines
617 handles: [burrowPeople.decider, burrowPeople.second],618 paths: "**",619 },620 ],635 functions: { admit: false, opensAlone: false },621 functions: { admit: false },622 kinds: [623 {624 checkKind: "migrate",625 claimers: "vouched",
61 unmodified lines
modified:apps/web/src/dev/fixtures.ts-7 removed
13 unmodified lines
14 NotDecider,15 UnknownAsk,16 UnknownCommit,17 UnknownProject,18 UnknownProposal,18} from "@repo/protocol/refusal";19import {20 Clock,21 Context,
307 unmodified lines
329 Effect.mapError(() => new UnknownAsk({ ask: id })),330 Effect.map((ask) => ({ ask, brief: briefOf(ask) }))331 )332 ),334 showProposal: (_caller, id) =>335 Effect.flatMap(current, ({ proposals }) =>336 Effect.fromOption(Option.fromUndefinedOr(proposals.get(id))).pipe(337 Effect.mapError(() => new UnknownProposal({ proposal: id }))338 )339 ),333 standing: () =>334 Effect.map(current, (record) => ({335 posture: record.ledger.posture,336 seen: lastSeqOf(record),
91 unmodified lines
modified:apps/web/src/dev/front-page.ts-2 removed
80 unmodified lines
81 Landed: () => rows,82 Lapsed: ({ ask }) => withClaims(rows, keyOf(project, ask), -1),83 DiscussionPosted: () => rows,84 LedgerAppended: () => rows,85 ProposalDrafted: () => rows,86 ProposalOpened: () => rows,85 Pushed: () => rows,86 Released: ({ ask }) => withClaims(rows, keyOf(project, ask), -1),87 Warned: () => rows,88 });
201 unmodified lines
modified:apps/web/src/dev/handlers.ts-16 removed
164 unmodified lines
165 decide: ({ project, ...input }) =>166 Effect.flatMap(person, (who) =>167 on(project, (api) => api.decide(who, input))168 ),169 draftAsk: ({ project, ...input }) =>170 Effect.flatMap(person, (who) =>171 on(project, (api) => api.draftAsk(who, input))172 ),169 evidence: ({ project, ref }) =>170 Effect.flatMap(person, (who) =>171 on(project, (api) =>172 api
9 unmodified lines
182 finish: ({ project, ...input }) =>183 Effect.flatMap(person, (who) =>184 on(project, (api) => api.finish(who, input))185 ),190 flagAsk: ({ project, ...input }) =>191 Effect.flatMap(person, (who) =>192 on(project, (api) => api.flagAsk(who, input))193 ),186 fork: ({ project }) =>187 Effect.gen(function* () {188 const who = yield* person;189 const { fork } = yield* on(project, (api) => api.fork(who));
71 unmodified lines
261 Effect.flatMap(person, (who) =>262 on(project, (api) => api.postDiscussion(who, input))263 ),264 projectPolicy: ({ project }) => on(project, (api) => api.policy()),273 proposeAsk: ({ project, ...input }) =>274 Effect.flatMap(person, (who) =>275 on(project, (api) => api.proposeAsk(who, input))276 ),265 readFile: ({ at, path, project }) =>266 code(project, (of) => fileOf(of, Option.fromUndefinedOr(at), path)),267 readTree: ({ at, path, project }) =>268 code(project, (of) =>
19 unmodified lines
288 showDiscussion: ({ discussion, project }) =>289 Effect.flatMap(caller, (who) =>290 on(project, (api) => api.showDiscussion(who, discussion))291 ),304 showProposal: ({ project, proposal }) =>305 Effect.flatMap(caller, (who) =>306 on(project, (api) => api.showProposal(who, proposal))307 ),292 status: ({ project }) =>293 Effect.gen(function* () {294 const who = yield* person;295
64 unmodified lines
modified:apps/web/src/dev/seed.ts+29 added-75 removed
2 unmodified lines
3import { LandingCommand } from "@repo/project/landing";4import type { ProjectApi } from "@repo/project/project";5import { Projects } from "@repo/project/projects";6import type { HarnessAudit } from "@repo/protocol/audit";7import { DecisionSubject } from "@repo/protocol/domain/decision";8import type { Decision } from "@repo/protocol/domain/decision";7import { AskId, Handle, keyOf, RepoName, RequestId } from "@repo/protocol/ids";10import type { CommitSha, ProjectName, ProposalId } from "@repo/protocol/ids";8import type { CommitSha, DiscussionId, ProjectName } from "@repo/protocol/ids";9import { Anonymous, Person } from "@repo/protocol/principal";10import { OutOfScope } from "@repo/protocol/refusal";11import { Array, DateTime, Effect, Option } from "effect";12
12 unmodified lines
2526const mainRef = RefName.make("refs/heads/main");2728export const visitors = {31 flagger: Handle.make("sefa"),32 proposer: Handle.make("tove"),29 asker: Handle.make("tove"),30 regular: Handle.make("wren"),31} as const;3233export const devPeople: readonly Handle[] = [34 operator,35 datekitPeople.decider,36 datekitPeople.zones,37 datekitPeople.contributor,41 visitors.proposer,42 visitors.flagger,38 visitors.asker,39 visitors.regular,40 burrowPeople.decider,41 burrowPeople.second,42];
90 unmodified lines
133 startedAt(project, initializer, files, devMinute(minute)),134 ({ api }) => api135 );136137/** Each ask opened a minute apart; one named in `from` is opened from that discussion, which it marks asked. */138export const opened = (139 api: ProjectApi,140 decider: Handle,141 asks: readonly (readonly [AskId, Opening])[],145 minute: number142 minute: number,143 from: ReadonlyMap<AskId, DiscussionId> = new Map()144) =>145 Effect.forEach(146 asks,147 ([ask, files], index) =>148 Effect.andThen(149 at(minute + index),152 api.openAsk(as(decider), { ask, files })150 api.openAsk(151 as(decider),152 Option.match(Option.fromUndefinedOr(from.get(ask)), {153 onNone: () => ({ ask, files }),154 onSome: (discussion) => ({ ask, discussion, files }),155 })156 )157 ),158 { discard: true }159 );160
133 unmodified lines
294 hold: true,295 });296 });297294const decisionOn = (api: ProjectApi, decider: Handle, proposal: ProposalId) =>295 Effect.flatMap(api.today(as(decider)), ({ decisions }) =>296 Effect.fromOption(297 Array.findFirst(298 decisions,299 ({ subject }: Decision) =>300 DecisionSubject.guards.OpenProposal(subject) &&301 subject.proposal === proposal302 )303 )304 );305306const DECLINED = [307 "parseISO accepts two-digit years.",308 "datekit wraps the Temporal API.",309];310298const seedDatekit = Effect.gen(function* () {299 const { contributor, decider } = datekitPeople;300 const api = yield* started(datekit.project, operator, datekit.files, 0);301315 yield* opened(api, decider, datekit.asks, 2);302 // A visitor's question that a maintainer opens as an ask.303 yield* at(1);304305 const asked = yield* api.postDiscussion(as(visitors.asker), {306 body: "Could parseISO take week dates like 2026-W41-3 too?",307 title: "ISO week dates",308 });309310 yield* opened(311 api,312 decider,313 datekit.asks,314 2,315 new Map([[AskId.make("parse-iso-week"), asked.discussion.id]])316 );317318 yield* at(6);319 yield* api.claim(as(contributor), datekit.answer.ask);320321 yield* at(7);
4 unmodified lines
326327 yield* at(8);328 yield* api.claim(as(contributor), AskId.make("parse-iso-week"));329329 yield* at(9);330 yield* api.proposeAsk(as(visitors.proposer), {331 want: 'format(date, "Qo") prints the quarter as an ordinal.',332 });333334 yield* at(10);335 yield* api.flagAsk(as(visitors.flagger), {336 ask: AskId.make("add-months-clamp"),337 reason: "Its check pins a common year only; leap years need a case too.",338 });339340 // Two discussions: one open, one a maintainer turned into a proposal.330 // A discussion still open, with a maintainer's reply.331 yield* at(14);332333 const talked = yield* api.postDiscussion(as(visitors.regular), {334 body: "Weeks start on Monday in ISO 8601, but on Sunday in the US; which does parseISO assume?",
4 unmodified lines
339 body: "ISO, always: a locale never changes what a date string means.",340 discussion: talked.discussion.id,341 });342353 yield* at(15);354355 const asked = yield* api.postDiscussion(as(visitors.proposer), {356 body: "Could parseISO take week dates like 2026-W41-3 too?",357 title: "ISO week dates",358 });359360 yield* at(16);361 yield* api.proposeAsk(as(decider), {362 discussion: asked.discussion.id,363 want: "parseISO reads an ISO week date to the day it names.",364 });365366 yield* Effect.forEach(367 DECLINED,368 (want, index) =>369 Effect.gen(function* () {370 yield* at(17 + index * 2);371372 const { proposal } = yield* api.proposeAsk(as(visitors.regular), {373 want,374 });375376 yield* at(18 + index * 2);377378 const decision = yield* decisionOn(api, decider, proposal.id);379380 yield* api.decide(as(decider), {381 choice: "decline",382 decision: decision.id,383 note: "Out of scope for a small library.",384 });385 }),386 { discard: true }387 );388343 return api;344});345346const seedBurrow = Effect.flatMap(
47 unmodified lines
modified:apps/web/src/dev/world.ts+1 added-6 removed
1import type { RepoHost } from "@repo/artifacts/repo-host";2import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";3import type { EvidenceStore } from "@repo/checks/evidence-store";4import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";5import { cannedDrafter } from "@repo/drafting/draft-runs/canned";6import { withDraftRunsInline } from "@repo/drafting/draft-runs/inline";5import { AlarmsMemory } from "@repo/project/alarms/memory";6import { CodeStoreMemory } from "@repo/project/code-store/memory";7import { CodeCacheLive } from "@repo/project/code/cache";8import { ProjectDescriptionsMemory } from "@repo/project/description/memory";
21 unmodified lines
3031const ports = Layer.mergeAll(32 AlarmsMemory,33 DevAnswerRunsLayer,36 cannedDrafter,34 CodeCacheLive(CODE_READS_KEPT.light, CODE_READS_KEPT.heavy),35 CodeStoreMemory,36 DevProjection,37 RulesEvaluatorJson.pipe(Layer.provide(FinishersFromChecks))
1 unmodified line
39 Layer.provideMerge(Layer.mergeAll(DevChecker, DevLander)),40 Layer.provideMerge(RepoHostMemory)41);4246const core = withDraftRunsInline(ProjectsMemory).pipe(47 Layer.provideMerge(ports)48);43const core = ProjectsMemory.pipe(Layer.provideMerge(ports));4445export type DevCore = Layer.Success<typeof core> | DevClock;4647export const devWorldWith = <Out, E, In extends DevCore>(
26 unmodified lines
modified:apps/web/src/features/answer/subject.ts-2 removed
20 unmodified lines
21 Landed: () => [],22 Lapsed: ({ ask }) => [ask],23 DiscussionPosted: () => [],24 LedgerAppended: () => [],25 ProposalDrafted: () => [],26 ProposalOpened: () => [],25 Pushed: ({ ask }) => [ask],26 Released: ({ ask }) => [ask],27 Warned: ({ ask }) => [ask],28 });
114 unmodified lines
modified:apps/web/src/features/decision/choices.tsx+2 added-19 removed
1import type { Choice, Decision } from "@repo/protocol/domain/decision";2import type { DateTime } from "effect";3import { Option } from "effect";3import { useId } from "react";4import type { ReactNode } from "react";56import { Button } from "../../components/ui/button.tsx";8import { Spinner } from "../../components/ui/spinner.tsx";7import { HandleLink } from "../shared/handle.tsx";8import { StateMarkIcon } from "../shared/marks.tsx";9import { When } from "../shared/time.tsx";10import {
4 unmodified lines
15 takenWords,16 tookEffect,17} from "./subject.ts";1821export interface Held {22 readonly reason: string;23 readonly waiting: boolean;24}2519export type ChoicesLayout = "grid" | "stack";2021const LAYOUTS = {22 grid: "grid grid-cols-2 gap-x-3 gap-y-3",
2 unmodified lines
2526export const Choices = ({27 busy,28 decision,36 held = Option.none(),29 layout = "grid",30 onChoose,31}: {32 readonly decision: Decision;33 readonly busy: boolean;42 readonly held?: Option.Option<Held>;34 readonly layout?: ChoicesLayout;35 readonly onChoose: (choice: Choice) => void;36}) => {37 const id = useId();
5 unmodified lines
43 </legend>44 <div className={LAYOUTS[layout]}>45 {allowedChoices(decision.subject).map((choice) => {46 const isDefault = choice === decision.default;56 const waits = Option.filter(held, () => choice === "accept");47 const consequence = consequenceOf(decision.subject, choice);4849 return (50 <div className="flex min-w-0 flex-col gap-1.5" key={choice}>51 <Button52 aria-describedby={`${id}-${choice}`}53 className="tablet:h-9 h-11 w-full px-4"54 data-choice={choice}65 disabled={busy || Option.isSome(waits)}55 disabled={busy}56 onClick={() => {57 onChoose(choice);58 }}59 type="button"60 variant={isDefault ? "outline" : "default"}61 >72 {Option.isSome(waits) ? (73 <>74 {waits.value.waiting ? <Spinner /> : null}75 {waits.value.reason}76 </>77 ) : (78 choiceWords[choice]79 )}62 {choiceWords[choice]}63 {isDefault ? (64 <span className="text-muted-foreground font-normal">65 default66 </span>
89 unmodified lines
modified:apps/web/src/features/decision/decision-card.tsx+1 added-63 removed
1import type { Decide } from "@repo/protocol/contracts";2import { DecisionSubject } from "@repo/protocol/domain/decision";2import type { Choice, Decision } from "@repo/protocol/domain/decision";4import { DraftState } from "@repo/protocol/domain/proposal";5import type { ProposalId } from "@repo/protocol/ids";3import type { DateTime } from "effect";4import { Option } from "effect";5import { ChevronDown, Hourglass, Shield } from "lucide-react";6import { useId, useState } from "react";7import type { ReactNode } from "react";89import { Textarea } from "../../components/ui/textarea.tsx";10import { changedFiles, isFinishDecision, patchOf } from "../finish/patch.ts";14import { DraftRead, useLiveDraft } from "../proposal/live-draft.ts";11import { When } from "../shared/time.tsx";12import { Choices, DecisionRecord } from "./choices.tsx";17import type { ChoicesLayout, Held } from "./choices.tsx";13import type { ChoicesLayout } from "./choices.tsx";14import { DecisionEvidence, FinishLink } from "./evidence.tsx";15import { describeDefault } from "./subject.ts";1617export {
4 unmodified lines
22} from "./subject.ts";2324export type DecideInput = typeof Decide.payloadSchema.Type;2530const opensAsk = DecisionSubject.isAnyOf(["OpenProposal"]);3132const isDraftingNow = DraftState.isAnyOf(["Drafting"]);3334const acceptHeld = (read: DraftRead): Option.Option<Held> =>35 DraftRead.$match(read, {36 Read: ({ draft }) =>37 Option.exists(draft, isDraftingNow)38 ? Option.some({ reason: "Drafting…", waiting: true })39 : Option.none(),40 Unread: ({ failed }) =>41 Option.some(42 failed43 ? { reason: "Draft not read; reload", waiting: false }44 : { reason: "Reading the draft…", waiting: true }45 ),46 });4726export const ExpiryLines = ({27 decision,28 now,29 soon,
71 unmodified lines
101 readonly decision: Decision;102 readonly layout: ChoicesLayout;103}104127/**128 * Read in the browser, so the server never renders an Accept the browser might129 * then hold.130 */131const ProposalChoices = ({132 proposal,133 ...props134}: ChoiceProps & { readonly proposal: ProposalId }) => {135 const read = useLiveDraft(props.decision.project, proposal);136137 return (138 <Choices139 busy={props.busy}140 decision={props.decision}141 held={acceptHeld(read)}142 layout={props.layout}143 onChoose={props.handleChoose}144 />145 );146};147105const Ending = ({149 draft,106 now,107 stamp,108 ...props109}: ChoiceProps & {154 readonly draft: DraftRead | undefined;110 readonly now: DateTime.Utc;111 readonly stamp: boolean;112}) => {113 const { decision } = props;
8 unmodified lines
122 />123 );124 }125171 if (opensAsk(decision.subject)) {172 return draft === undefined ? (173 <ProposalChoices {...props} proposal={decision.subject.proposal} />174 ) : (175 <Choices176 busy={props.busy}177 decision={decision}178 held={acceptHeld(draft)}179 layout={props.layout}180 onChoose={props.handleChoose}181 />182 );183 }184126 return (127 <Choices128 busy={props.busy}129 decision={decision}
12 unmodified lines
142 busy = false,143 children,144 choices,145 decision,205 draft,146 expiry = true,147 finishLink = true,148 layout = "grid",149 now,
11 unmodified lines
161 readonly expiry?: boolean;162 readonly finishLink?: boolean;163 readonly layout?: ChoicesLayout;164 readonly stamp?: boolean;225 readonly draft?: DraftRead | undefined;165}) => {166 const [note, setNote] = useState("");167168 const handleChoose = (choice: Choice) => {
11 unmodified lines
180 const chosen = (181 <Ending182 busy={busy}183 decision={decision}245 draft={draft}184 handleChoose={handleChoose}185 layout={layout}186 now={now}187 stamp={stamp}
25 unmodified lines
modified:apps/web/src/features/decision/decision-page.tsx+1 added-22 removed
1import { Brand } from "@repo/brand";2import type { Ask } from "@repo/protocol/domain/ask";3import { DecisionSubject } from "@repo/protocol/domain/decision";4import type { Decision } from "@repo/protocol/domain/decision";5import type { Proposal } from "@repo/protocol/domain/proposal";5import type { DecisionId, ProjectName } from "@repo/protocol/ids";6import type { DateTime } from "effect";7import { Hourglass, Shield } from "lucide-react";8import type { ReactNode } from "react";
96 unmodified lines
105 </AppLink>106 </FactBlock>107);108110const ProposalFacts = ({ proposal }: { readonly proposal: Proposal }) => (111 <FactBlock label="The proposal">112 <p className="text-ui" data-said="">113 {proposal.want}114 </p>115 <p className="text-ui text-muted-foreground">116 Proposed by <HandleLink handle={proposal.proposer} />117 </p>118 <AppLink119 className={`text-ui ${LINK}`}120 to={`/${proposal.project}/proposals/${proposal.id}`}121 >122 Read its draft123 </AppLink>124 </FactBlock>125);126109export const WaiverDiff = ({110 decision,111 files,112}: {
44 unmodified lines
157 is about. A maintainer takes it on their Today, with its evidence and a158 safe default if nobody does.159 </p>160 <p className="text-ui">179 <AppLink className={LINK} to={`/${project}/people`}>161 <AppLink className={LINK} to={`/${project}/policy`}>162 Who decides in {project}163 </AppLink>164 </p>165 {children}
44 unmodified lines
210 facts={211 <>212 <DecisionFacts decision={decision} now={now} soon={found.soon} />213 {found.ask === undefined ? null : <AskFacts ask={found.ask} />}232 {found.proposal === undefined ? null : (233 <ProposalFacts proposal={found.proposal} />234 )}214 {found.posture === undefined ? null : (215 <PostureFacts216 label={found.posture.label}217 posture={found.posture.posture}
111 unmodified lines
modified:apps/web/src/features/decision/evidence.tsx+10 added-51 removed
1import type { Evidence as Fact } from "@repo/protocol/domain/common";1import { DecisionSubject } from "@repo/protocol/domain/decision";2import type { Decision } from "@repo/protocol/domain/decision";3import type { Posture } from "@repo/protocol/posture";5import { ArrowRight, FileDiff, FileText } from "lucide-react";4import { ArrowRight, FileDiff } from "lucide-react";5import type { ReactNode } from "react";67import { commitHref, shortSha } from "../code/paths.ts";8import { FORK_LABEL, PATCH_LABEL } from "../finish/patch.ts";10import { DraftedCode } from "../proposal/client-file.tsx";9import { HandleLink } from "../shared/handle.tsx";10import { AppLink } from "../shared/link.tsx";11import { POSTURE_MARKS } from "../shared/mark-look.ts";12import { Mark } from "../shared/marks.tsx";
8 unmodified lines
21const LINK = "decoration-rule underline hover:decoration-current";2223const CODE = "text-mono font-mono [overflow-wrap:anywhere]";2427/**28 * A label that is a path: one word with a slash or a dot, where every other29 * label is words.30 */31const isFileFact = ({ label }: Fact) => /^\S*[./]\S*$/u.test(label);3233const opensAsk = DecisionSubject.isAnyOf(["OpenProposal"]);3435export const filesOf = (decision: Decision): readonly Fact[] =>36 opensAsk(decision.subject) ? decision.evidence.filter(isFileFact) : [];3725const FactRow = ({26 children,27 label,28}: {
22 unmodified lines
51 icon: Icon,52 to,53}: {54 readonly children: ReactNode;68 readonly icon: typeof FileText;55 readonly icon: typeof FileDiff;56 readonly to: string;57}) => (58 <AppLink59 className={`text-ui flex w-fit items-center gap-2 font-medium ${LINK}`}
60 unmodified lines
120 </code>121 </FactRow>122 </FactList>123 ),137 OpenProposal: ({ proposal }) => (138 <PageLink139 icon={FileText}140 to={`/${decision.project}/proposals/${proposal}`}141 >142 Read the draft of {proposal}143 </PageLink>144 ),124 PostureChange: ({ from, to }) => (125 <FactList>126 <FactRow label="Posture">127 <FromTo
124 unmodified lines
252 "escape",253 "ratchet",254]);255277const OtherFacts = ({278 decision,279 files,280}: {281 readonly decision: Decision;282 readonly files: readonly Fact[];283}) => {256const OtherFacts = ({ decision }: { readonly decision: Decision }) => {257 const facts = decision.evidence.filter(285 (fact) => !SHOWN_ELSEWHERE.has(fact.label) && !files.includes(fact)258 (fact) => !SHOWN_ELSEWHERE.has(fact.label)259 );260261 return facts.length === 0 ? null : (262 <FactList>
32 unmodified lines
295);296297export const DecisionEvidence = ({298 decision,326 heading = "h4",299}: {300 readonly decision: Decision;329 readonly heading?: "h3" | "h4";330}) => {331 const files = filesOf(decision);332333 return (334 <div className="@container flex min-w-0 flex-col gap-3" data-evidence="">335 <SubjectFacts decision={decision} />336 <OtherFacts decision={decision} files={files} />337 {files.map(({ label, value }) => (338 <DraftedCode339 content={value}340 heading={heading}341 key={label}342 path={label}343 />344 ))}345 </div>346 );347};301}) => (302 <div className="@container flex min-w-0 flex-col gap-3" data-evidence="">303 <SubjectFacts decision={decision} />304 <OtherFacts decision={decision} />305 </div>306);
modified:apps/web/src/features/decision/read.ts-16 removed
6 unmodified lines
7import { Ask } from "@repo/protocol/domain/ask";8import { Decision, DecisionSubject } from "@repo/protocol/domain/decision";9import type { ProjectEvent } from "@repo/protocol/domain/event";10import { Outcome } from "@repo/protocol/domain/outcome";11import { Proposal } from "@repo/protocol/domain/proposal";11import { CommitSha, DecisionId, ProjectName } from "@repo/protocol/ids";12import type { AskId } from "@repo/protocol/ids";13import { Posture } from "@repo/protocol/posture";14import { Refusal } from "@repo/protocol/refusal";
18 unmodified lines
33 placed: Schema.Array(Placed),34 posture: Schema.optionalKey(35 Schema.Struct({ label: Schema.String, posture: Posture })36 ),38 proposal: Schema.optionalKey(Proposal),37 soon: Schema.Boolean,38 verdict: Schema.optionalKey(Verdict),39 },40 NotOnToday: {},
45 unmodified lines
86};8788const askOf = DecisionSubject.match({89 Finish: ({ ask }) => Option.some(ask),92 OpenProposal: () => Option.none(),90 PostureChange: () => Option.none(),91 ProxyWidened: () => Option.none(),92 RaiseRatchet: ({ ask }) => Option.some(ask),93 SecretInTree: ({ ask }) => Option.some(ask),
15 unmodified lines
109 Effect.orElseSucceed(() => Option.none())110 ),111 });112116 const proposal = DecisionSubject.guards.OpenProposal(subject)117 ? yield* client118 .showProposal({ project, proposal: subject.proposal })119 .pipe(120 Effect.map(({ proposal: shown }) => Option.some(shown)),121 Effect.orElseSucceed(() => Option.none())122 )123 : Option.none();124113 const posture = DecisionSubject.guards.PostureChange(subject)114 ? yield* client.ledger({ project }).pipe(115 Effect.map((ledger) =>116 Option.some({ label: ledger.postureLabel, posture: ledger.posture })
32 unmodified lines
149 ...Option.match(ask, {150 onNone: () => ({}),151 onSome: (shown) => ({ ask: shown }),152 }),165 ...Option.match(proposal, {166 onNone: () => ({}),167 onSome: (shown) => ({ proposal: shown }),168 }),153 ...Option.match(posture, {154 onNone: () => ({}),155 onSome: (shown) => ({ posture: shown }),156 }),
59 unmodified lines
modified:apps/web/src/features/decision/subject.ts-7 removed
8 unmodified lines
9 * offers each subject its own words only.10 */11export const allowedChoices = DecisionSubject.match({12 Finish: () => yesOrNo,13 OpenProposal: () => yesOrNo,13 PostureChange: () => yesOrNo,14 ProxyWidened: () => yesOrNo,15 RaiseRatchet: () => yesOrNo,16 SecretInTree: () => yesOrNo,
8 unmodified lines
2526export const describeSubject = DecisionSubject.match({27 Finish: ({ ask, head }) =>28 `Finish the passing answer to ${ask}, at ${short(head)}`,30 OpenProposal: ({ proposal }) => `Open the ask proposed in ${proposal}`,29 PostureChange: ({ from, to }) =>30 `Change the project's posture from ${from} to ${to}`,31 ProxyWidened: ({ hosts, item }) =>32 `Let ${item} be sent to ${hosts.length === 0 ? "more hosts" : hosts.join(", ")} through the platform's proxy`,
9 unmodified lines
42});4344export const subjectKind = DecisionSubject.match({45 Finish: () => "finish",48 OpenProposal: () => "proposal",46 PostureChange: () => "posture change",47 ProxyWidened: () => "proxy",48 RaiseRatchet: () => "ratchet",49 SecretInTree: () => "stored value",
16 unmodified lines
66 Finish: (): Lines => ({67 no: "Nothing lands; the answer keeps waiting for a finish.",68 yes: "Lands the answer as it is, with you as Finished-by.",69 }),73 OpenProposal: (): Lines => ({74 no: "The proposal closes; nothing lands.",75 yes: "Opens the ask: its file and check land on main, with you as Decided-by.",76 }),70 PostureChange: ({ from }): Lines => ({71 no: `The answer that changes it is refused; the posture stays ${from}.`,72 yes: "The answer that changes it goes on through the gate, with you as Decided-by.",73 }),
81 unmodified lines
modified:apps/web/src/features/discussion/discussion-view.tsx+11 added-14 removed
1 unmodified line
2import type {3 Discussion,4 DiscussionPost,5} from "@repo/protocol/domain/discussion";6import type { ProjectName, ProposalId } from "@repo/protocol/ids";6import type { DateTime } from "effect";7import type { ReactNode } from "react";89import { CommandLine } from "../shared/command.tsx";10import { FactBlock } from "../shared/facts.tsx";11import { HandleLink } from "../shared/handle.tsx";12import { AppLink } from "../shared/link.tsx";13import { askPath } from "../shared/paths.ts";14import { Workspace } from "../shared/shell/workspace.tsx";15import { When } from "../shared/time.tsx";16import { replyCommand, STATE_LABEL } from "./discussions-view.tsx";1718const LINK = "decoration-rule underline hover:decoration-current";1920const proposalPath = (project: ProjectName, proposal: ProposalId) =>21 `/${project}/proposals/${proposal}`;2220const Post = ({21 now,22 post,23}: {
15 unmodified lines
39 </article>40);4142const Became = ({ discussion }: { readonly discussion: Discussion }) =>46 discussion.proposal === undefined ? null : (47 <p className="text-ui" data-became={discussion.proposal}>48 {"A maintainer turned this discussion into "}43 discussion.ask === undefined ? null : (44 <p className="text-ui" data-became={discussion.ask}>45 {"A maintainer opened the ask "}46 <AppLink47 className={`text-mono font-mono ${LINK}`}51 to={proposalPath(discussion.project, discussion.proposal)}48 to={askPath(discussion.project, discussion.ask)}49 >53 {discussion.proposal}50 {discussion.ask}51 </AppLink>55 , which expires unless a maintainer accepts it.52 {" from this discussion."}53 </p>54 );5556const ThreadFacts = ({ discussion }: { readonly discussion: Discussion }) => (57 <FactBlock label="This discussion">58 {discussion.state === "open" ? (59 <>60 <p className="text-ui">64 Reply from a terminal; anyone not denounced may. A maintainer may turn65 the thread into a proposal with{" "}66 <code className="text-mono font-mono">{`${Brand.cli} propose --discussion ${discussion.id}`}</code>61 Reply from a terminal; anyone not denounced may. A maintainer may open62 an ask from the thread with{" "}63 <code className="text-mono font-mono">{`${Brand.cli} ask open <ask> --discussion ${discussion.id}`}</code>64 .65 </p>66 <CommandLine command={replyCommand(discussion)} numbered />67 </>68 ) : (69 <p className="text-ui">70 {discussion.state === "closed"71 ? "This discussion is closed: it takes no more posts."75 : "This discussion became a proposal: it takes no more posts."}72 : "This discussion became an ask: it takes no more posts."}73 </p>74 )}75 </FactBlock>76);
33 unmodified lines
modified:apps/web/src/features/discussion/discussions-view.tsx+11 added-4 removed
10 unmodified lines
11import { EmptyState } from "../shared/empty.tsx";12import { FactBlock } from "../shared/facts.tsx";13import { HandleLink } from "../shared/handle.tsx";14import { AppLink } from "../shared/link.tsx";15import { discussionPath } from "../shared/paths.ts";15import { askPath, discussionPath } from "../shared/paths.ts";16import { Workspace } from "../shared/shell/workspace.tsx";17import { When } from "../shared/time.tsx";1819const LINK = "decoration-rule underline hover:decoration-current";
2 unmodified lines
22 `${count} ${count === 1 ? one : many}`;2324/** Every state reads as a word beside its mark, never by colour alone. */25export const STATE_LABEL = {26 asked: "Became an ask",27 closed: "Closed",28 open: "Open",28 proposed: "Became a proposal",29} as const satisfies Record<DiscussionState, string>;3031export const openCommand = (project: ProjectName) =>32 `${Brand.cli} discussion post --project ${project} --title "<title>" --body "<post>"`;
34 unmodified lines
67 {"last post "}68 <When at={listing.lastPostAt} now={now} />69 </span>70 <span>{STATE_LABEL[listing.state]}</span>71 {listing.ask === undefined ? null : (72 <AppLink73 className={`text-mono font-mono ${LINK}`}74 to={askPath(listing.project, listing.ask)}75 >76 {listing.ask}77 </AppLink>78 )}79 </p>80 </li>81);8283const PostFacts = ({ project }: { readonly project: ProjectName }) => (84 <FactBlock label="How to post">85 <p className="text-ui">86 Anyone not denounced may open a thread or reply, from a terminal. A79 discussion lands nothing itself; a maintainer may turn one into a80 proposal.87 discussion lands nothing itself; a maintainer may open an ask from one.88 </p>89 <CommandLine command={openCommand(project)} numbered />90 </FactBlock>91);
31 unmodified lines
modified:apps/web/src/features/finish/finish-column.tsx+1 added-1 removed
50 unmodified lines
51 <AppLink className={ROW} to={INBOX_PATH}>52 Inbox53 </AppLink>54 {project === undefined ? null : (55 <AppLink className={ROW} to={`/${project}/people`}>55 <AppLink className={ROW} to={`/${project}/policy`}>56 Who decides in {project}57 </AppLink>58 )}59 </div>
17 unmodified lines
modified:apps/web/src/features/import/use-importer.tsx+2 added-2 removed
7 unmodified lines
89import { importAtom, importMade } from "../../client/import.ts";10import { hereOf } from "../auth/session-slot.tsx";11import { whoAtom } from "../auth/who.ts";12import { ProposalFailure } from "../proposal/failure.tsx";12import { CallFailure } from "../shared/call-failure.tsx";13import type { Importer } from "./import-form.tsx";1415export const afterImport = (made: ProjectName, at?: ProjectName) =>16 made === at
36 unmodified lines
53 send(payload);54 },55 refusal: AsyncResult.isFailure(imported) ? (56 <div aria-live="polite">57 <ProposalFailure cause={imported.cause} doing="import it" here={here} />57 <CallFailure cause={imported.cause} doing="import it" here={here} />58 </div>59 ) : undefined,60 };61};
modified:apps/web/src/features/people/person-page.tsx+1 added-3 removed
87 unmodified lines
88 })),89 project: Array.headNonEmpty(inProject).project,90 }));9192/** The Landings tab's own address, with the filter or region it opens. */92/** The Landings tab's own address, with the filter it opens. */93const landingsOf = (project: ProjectName) =>94 projectSections(project).find(({ tab }) => tab === "landings") ?? {95 hash: undefined,95 search: undefined,96 to: projectPath(project),97 };98
5 unmodified lines
104 >105 {credit.areas.map(({ area, roles }) => (106 <Row107 data={{ "data-area": area, "data-project": credit.project }}109 hash={landingsOf(credit.project).hash}108 href={landingsOf(credit.project).to}109 search={landingsOf(credit.project).search}110 id={`${credit.project}/${area}`}111 key={area}
59 unmodified lines
added:apps/web/src/features/project/asks-page.tsx+77 added
1import { Brand } from "@repo/brand";2import type { Ask, AskListing } from "@repo/protocol/domain/ask";3import type { AskId, ProjectName } from "@repo/protocol/ids";4import { useRouter } from "@tanstack/react-router";5import { Predicate } from "effect";6import type { DateTime } from "effect";78import { stillWaiting } from "../front/families.ts";9import type { AskProgress } from "../shared/ask-progress.ts";10import { CommandLine } from "../shared/command.tsx";11import { FactBlock } from "../shared/facts.tsx";12import { useRowSelection } from "../shared/row.tsx";13import { Workspace } from "../shared/shell/workspace.tsx";14import { askListIds, OpenAskRows, openAsks, openCount } from "./asks.tsx";1516export interface ProjectAsksProps {17 readonly asks: readonly AskListing[] | undefined;18 readonly now: DateTime.Utc;19 readonly parents: readonly Ask[];20 readonly project: ProjectName;21 readonly stamps: ReadonlySet<AskId>;22 readonly states: ReadonlyMap<AskId, AskProgress>;23 readonly unreachable: boolean;24}2526export const claimCommand = (project: ProjectName) =>27 `${Brand.cli} claim <ask> --project ${project}`;2829const TakeFacts = ({ project }: { readonly project: ProjectName }) => (30 <FactBlock label="How to take one">31 <p className="text-ui">32 Claim an ask open to take; the claim comes with a fork to push your answer33 to, and the platform checks it and lands it, or refuses it.34 </p>35 <CommandLine command={claimCommand(project)} numbered />36 </FactBlock>37);3839const AsksPanes = ({40 props,41 selected,42}: {43 readonly props: ProjectAsksProps;44 readonly selected: string | undefined;45}) => (46 <Workspace47 {...(props.asks === undefined48 ? {}49 : { count: openCount(openAsks(props.asks)) })}50 facts={<TakeFacts project={props.project} />}51 factsHeading="Taking an ask"52 title="Asks"53 variant="list"54 >55 <OpenAskRows {...props} selected={selected} />56 </Workspace>57);5859const Selectable = ({ props }: { readonly props: ProjectAsksProps }) => {60 const { selected } = useRowSelection(61 props.asks === undefined ? [] : askListIds(props.asks),62 "ask"63 );6465 return <AsksPanes props={props} selected={selected} />;66};6768/** The project's Asks tab: its open asks, as Overview lists them, on a page of their own. */69export const ProjectAsksView = (given: ProjectAsksProps) => {70 const props = { ...given, asks: given.asks && stillWaiting(given.asks) };7172 return Predicate.isNotNullish(useRouter({ warn: false })) ? (73 <Selectable props={props} />74 ) : (75 <AsksPanes props={props} selected={undefined} />76 );77};
modified:apps/web/src/features/project/asks.tsx+40 added
1import { Brand } from "@repo/brand";2import type { Ask, AskListing } from "@repo/protocol/domain/ask";3import type { AskId, ProjectName } from "@repo/protocol/ids";4import type { DateTime } from "effect";5import type { ReactNode } from "react";67import { plural } from "../front/facts.tsx";8import { arrange } from "../front/families.ts";9import type { AskProgress } from "../shared/ask-progress.ts";10import { EmptyState } from "../shared/empty.tsx";11import { FamilyStrip } from "../shared/family.tsx";12import { ReadingRows, UnreachableNotice } from "../shared/pending.tsx";13import { AskRow, RowList } from "../shared/row.tsx";1415export const openToTake = (listing: AskListing) =>16 !listing.claimed &&
81 unmodified lines
98export const askListIds = (asks: readonly AskListing[]) =>99 arrange(asks).map((item) =>100 item.kind === "ask" ? item.listing.ask : item.parent.ask101 );102103export const openCount = (open: readonly AskListing[]) =>104 `${plural(open.length, "open ask", "open asks")}, ${105 open.filter(openToTake).length106 } open to take`;107108export interface OpenAskRowsProps {109 readonly asks: readonly AskListing[] | undefined;110 readonly now: DateTime.Utc;111 readonly unreachable: boolean;112 readonly project: ProjectName;113 readonly parents: readonly Ask[];114 readonly states: ReadonlyMap<AskId, AskProgress>;115 readonly stamps: ReadonlySet<AskId>;116 readonly selected: string | undefined;117}118119/** A project's open asks, or why there are none to show yet. */120export const OpenAskRows = ({121 asks,122 unreachable,123 ...props124}: OpenAskRowsProps): ReactNode => {125 if (asks === undefined) {126 return unreachable ? <UnreachableNotice /> : <ReadingRows />;127 }128129 return asks.length === 0 ? (130 <EmptyState131 command={`${Brand.cli} ask open <ask> --files <files>`}132 title="No open asks. A maintainer opens one from an ask file."133 />134 ) : (135 <AskList asks={asks} {...props} />136 );137};
modified:apps/web/src/features/project/project-header.tsx+10 added-20 removed
196 unmodified lines
197 open === undefined198 ? "Its open asks"199 : `${plural(open.takeable, "ask", "asks")} open to take now`200 }201 hash="open-asks"202 to={`/${project}`}201 to={`/${project}/asks`}202 >203 Take an open ask204 </MenuLink>205 <MenuLink207 detail="A change you want, with a check the agent can draft"208 to={`/${project}/proposals/new`}206 detail="A change you want, talked over before it is an ask"207 to={`/${project}/discussions`}208 >210 Propose an ask209 Start a discussion210 </MenuLink>211 <MenuLink212 detail="What lands here and who decides"214 to={`/${project}/people`}213 to={`/${project}/policy`}214 >215 Read the policy216 </MenuLink>217 </nav>
46 unmodified lines
264265const TAB =266 "text-ui text-muted-foreground hover:text-foreground data-current:border-foreground data-current:text-foreground -mb-px flex h-(--tabs) shrink-0 items-center gap-1.5 border-b-2 border-transparent px-3 whitespace-nowrap no-underline transition-colors duration-[120ms] first:pl-0 focus-visible:outline-offset-[-2px] data-current:font-medium";267269/**270 * The router marks a link to the page being read. A tab that opens a region271 * of Overview counts the fragment, so the router marks it only in the browser272 * once the reader has opened that region; every other tab counts the path.273 */274const activeFor = (hash: string | undefined) => ({275 exact: true,276 includeHash: hash !== undefined,277 includeSearch: false,278});268/** The router marks a link to the page being read, by its path. */269const ACTIVE = { exact: true, includeSearch: false } as const;270271/**272 * Text tabs, the current one ink with the 2 px underline. The current tab273 * follows the page's path alone, so the server and the browser draw the same283 * mark, and a region of Overview opened by its tab leaves Overview current.274 * mark.275 */276export const ProjectTabs = ({277 current,278 open,
13 unmodified lines
292 className="tablet:after:hidden after:from-background relative after:pointer-events-none after:absolute after:inset-y-0 after:right-0 after:w-10 after:bg-linear-to-l after:to-transparent after:content-['']"293 data-tabs-fade=""294 >295 <div className="flex [scrollbar-width:none] overflow-x-auto overscroll-x-contain">305 {projectSections(project).map(({ hash, label, search, tab, to }) => (296 {projectSections(project).map(({ label, search, tab, to }) => (297 <AppLink307 activeOptions={activeFor(hash)}298 activeOptions={ACTIVE}299 aria-current={tab === current ? "page" : undefined}300 className={TAB}301 data-current={tab === current ? "" : undefined}302 key={tab}303 to={to}313 {...(hash === undefined ? {} : { hash })}304 {...(search === undefined ? {} : { search })}305 >306 {label}307 {tab === "asks" && open !== undefined ? (
60 unmodified lines
modified:apps/web/src/features/project/project-page.tsx+12 added-107 removed
1import { IMPORTED_NOTE } from "@repo/agent-kit/docs/imported-note";2import { Brand } from "@repo/brand";2import type { Ask, AskListing } from "@repo/protocol/domain/ask";3import type { FileView, TreeListing } from "@repo/protocol/domain/code";4import type { Glob } from "@repo/protocol/domain/common";5import type { ProjectListing } from "@repo/protocol/domain/front-page";
9 unmodified lines
15import type { DateTime } from "effect";16import { LockKeyhole } from "lucide-react";17import type { ReactNode } from "react";1820import { signInHref } from "../auth/session-slot.tsx";19import { ForAgents, Onward, plural } from "../front/facts.tsx";20import { stillWaiting } from "../front/families.ts";23import { ProposeLink } from "../propose/propose-link.tsx";24import { proposeFormPath } from "../propose/propose-view.tsx";21import type { AskProgress } from "../shared/ask-progress.ts";22import { LINK } from "../shared/classes.ts";23import { CommandLine } from "../shared/command.tsx";28import { EmptyState } from "../shared/empty.tsx";24import { CommandSlotProvider } from "../shared/keys.tsx";25import { AppLink } from "../shared/link.tsx";26import {27 ENVIRONMENT_ANCHOR,28 LEDGER_ANCHOR,29 visibilityPath,30} from "../shared/paths.ts";36import { ReadingRows, UnreachableNotice } from "../shared/pending.tsx";31import { MetaCode, useRowSelection } from "../shared/row.tsx";32import { GUTTER } from "../shared/shell/gutter.ts";33import { stageNames, stageRuns } from "../shared/status-line.tsx";40import { AskList, askListIds, openAsks, openToTake } from "./asks.tsx";34import { askListIds, OpenAskRows, openAsks, openCount } from "./asks.tsx";35import type { OpenAskRowsProps } from "./asks.tsx";36import { LandingList, recentShown } from "./landings.tsx";37import { CloneSteps } from "./project-header.tsx";38import { ReadmeSection } from "./readme-section.tsx";39
79 unmodified lines
119 readonly code?: ProjectCode | undefined;120 readonly parents?: readonly Ask[];121 readonly states?: ReadonlyMap<AskId, AskProgress>;122 readonly stamps?: ReadonlySet<AskId>;128 readonly signedIn?: boolean;123}124125/** A plain bordered surface, its headline first (DESIGN.md "Cards"). */126const AboutCard = ({
81 unmodified lines
208 </li>209 ) : null}210 </ul>211 )}218 <Onward to={`/${project}/people`}>Policy</Onward>212 <Onward to={`/${project}/policy`}>Policy</Onward>213 </AboutCard>214 );215};216
182 unmodified lines
399 </section>400 );401};402409const countOf = (open: readonly AskListing[]) =>410 `${plural(open.length, "open ask", "open asks")}, ${411 open.filter(openToTake).length412 } open to take`;413414const AsksSection = ({415 asks,416 now,417 parents,418 project,419 selected,420 stamps,421 states,422 unreachable,423}: {424 readonly asks: readonly AskListing[] | undefined;425 readonly now: DateTime.Utc;426 readonly unreachable: boolean;427 readonly project: ProjectName;428 readonly parents: readonly Ask[];429 readonly states: ReadonlyMap<AskId, AskProgress>;430 readonly stamps: ReadonlySet<AskId>;431 readonly selected: string | undefined;432}) => {433 let list: ReactNode;434435 if (asks === undefined) {436 list = unreachable ? <UnreachableNotice /> : <ReadingRows />;437 } else if (asks.length === 0) {438 list = (439 <EmptyState440 command={`${Brand.cli} ask open <ask> --files <files>`}441 title="No open asks. A maintainer opens one from an ask file."442 />443 );444 } else {445 list = (446 <AskList447 asks={asks}448 now={now}449 parents={parents}450 project={project}451 selected={selected}452 stamps={stamps}453 states={states}454 />455 );456 }457458 return (459 <section460 aria-labelledby="open-asks"461 className="flex min-w-0 flex-col gap-2"462 >463 <SectionHead464 count={asks === undefined ? undefined : countOf(openAsks(asks))}465 id="open-asks"466 title="Open asks"467 />468 {list}469 </section>470 );471};472473/**474 * The Proposals tab opens this region until a project's proposals have a475 * page of their own, so the tab keeps the project's header and tabs.476 */477const ProposalsSection = ({478 project,479 signedIn,480}: {481 readonly project: ProjectName;482 readonly signedIn: boolean;483}) => (484 <section aria-labelledby="proposals" className="flex min-w-0 flex-col gap-2">403const AsksSection = (props: OpenAskRowsProps) => (404 <section aria-labelledby="open-asks" className="flex min-w-0 flex-col gap-2">405 <SectionHead486 action={signedIn ? <ProposeLink project={project} /> : undefined}487 id="proposals"488 title="Proposals"406 count={407 props.asks === undefined ? undefined : openCount(openAsks(props.asks))408 }409 id="open-asks"410 title="Open asks"411 />490 <p className="text-ui text-muted-foreground max-w-(--measure)">491 A proposal asks a maintainer to open an ask. An agent on the platform492 drafts its ask file and check, and it expires unless a maintainer accepts493 it.494 {signedIn ? null : (495 <>496 {" "}497 <a className={LINK} href={signInHref(proposeFormPath(project))}>498 Sign in499 </a>{" "}500 to propose one.501 </>502 )}503 </p>412 <OpenAskRows {...props} />413 </section>414);415416/**508 * Overview: open asks, recent landings, proposals and the README in the main column,417 * Overview: open asks, recent landings and the README in the main column,418 * and the about column beside it from `columns`, under it below.419 */420const ProjectPanes = ({421 props,
35 unmodified lines
457 now={props.now}458 platformUrl={props.platformUrl}459 project={project}460 />552 <ProposalsSection553 project={project}554 signedIn={props.signedIn === true}555 />461 {code?.readme === undefined ? null : (462 <div className="max-w-(--measure) min-w-0">463 <ReadmeSection file={code.readme} project={project} />464 </div>
30 unmodified lines
added:apps/web/src/features/project-people/moved.ts+23 added
1import { redirect } from "@tanstack/react-router";2import { Effect } from "effect";34import { policyHref } from "../shared/paths.ts";56// A project's policy page was `/people` until the People tab folded into it. The worker answers a document load with7// its own 301 (`canonicalAddress`); this sends on a navigation inside the app, from a page kept before the move.8// It rejects with the redirect: the lint keeps a bare `throw` for `Error`s, which a redirect is not.9export const movedToPolicy = ({10 location,11 params,12}: {13 readonly location: { readonly searchStr: string };14 readonly params: { readonly project: string };15}): Promise<never> =>16 Effect.runPromise(17 Effect.fail(18 redirect({19 href: policyHref(params.project, location.searchStr),20 statusCode: 301,21 })22 )23 );
modified:apps/web/src/features/project-people/people-view.tsx+3 added-10 removed
41 unmodified lines
42 : plural(hours, "hour", "hours");43};4445const vouchModes = {46 all: "For everything: claiming an ask, offering a sealed answer and proposing an ask all need a vouch.",46 all: "For everything, which today gates what for code does: claiming an ask needs a vouch; anyone not denounced may post in a discussion.",47 bansOnly:48 "Bans only: nobody needs a vouch, but a denounced person still may not claim, push or propose.",48 "Bans only: nobody needs a vouch, but a denounced person still may not claim, push or post.",49 forCode:50 "For code: claiming an ask or offering a sealed answer needs a vouch; anyone not denounced may propose an ask.",50 "For code: claiming an ask needs a vouch; anyone not denounced may post in a discussion.",51} as const satisfies Record<PublicPolicy["vouch"]["mode"], string>;5253const Code = ({ children }: { readonly children: ReactNode }) => (54 <code className="text-mono font-mono [overflow-wrap:anywhere]">
150 unmodified lines
205 <Definitions label="Limits">206 <Definition term="Claims">207 <Num>{`${plural(caps.claimsPerPerson, "claim", "claims")} at once for a person nobody has vouched for; a vouched person and a maintainer are never held`}</Num>208 </Definition>209 <Definition term="Proposals">210 <Num>211 {caps.proposalsPerPerson === 0212 ? "Proposals are off"213 : `${plural(caps.proposalsPerPerson, "proposal", "proposals")} open at once for a person nobody has vouched for`}214 </Num>215 </Definition>209 <Definition term="Decisions">210 <Num>{`an undecided one takes its default after ${plural(decisions.expireDays, "day", "days")}`}</Num>211 </Definition>212 <Definition term="Claim timing">
256 unmodified lines
deleted:apps/web/src/features/proposal/client-file.tsx-45 removed
1/**2 * `import.meta.env.SSR` is `true` in the Worker's build, so the dynamic import3 * below is dead code there and the Worker bundles none of it.4 */5import { ClientOnly } from "@tanstack/react-router";6import { lazy, Suspense } from "react";78import type { DraftedFileProps } from "./drafted-file.tsx";910const DraftedFileLater = import.meta.env.SSR11 ? undefined12 : lazy(() => import("./drafted-file.tsx"));1314const Plain = ({ content }: { readonly content: string }) => (15 <pre className="border-rule bg-surface text-mono leading-code overflow-x-auto border px-3 py-2 font-mono">16 {content}17 </pre>18);1920export const DraftedCode = ({21 content,22 heading: Heading = "h3",23 path,24}: DraftedFileProps & {25 readonly heading?: "h3" | "h4";26}) => {27 const fallback = <Plain content={content} />;2829 return (30 <section className="flex min-w-0 flex-col gap-1.5" data-file={path}>31 <Heading className="text-mono font-mono font-medium [overflow-wrap:anywhere]">32 {path}33 </Heading>34 {DraftedFileLater === undefined ? (35 fallback36 ) : (37 <ClientOnly fallback={fallback}>38 <Suspense fallback={fallback}>39 <DraftedFileLater content={content} path={path} />40 </Suspense>41 </ClientOnly>42 )}43 </section>44 );45};
deleted:apps/web/src/features/proposal/drafted-file.tsx-37 removed
1import { File } from "@pierre/diffs/react";2import type { FileOptions } from "@pierre/diffs/react";3import { useMemo } from "react";45import { diffsOptions, registerCodeTheme } from "../code/pierre.ts";6import { CodePool } from "../code/pool.tsx";78registerCodeTheme();910export interface DraftedFileProps {11 readonly path: string;12 readonly content: string;13}1415const options: FileOptions<undefined, undefined> = {16 ...diffsOptions,17 disableFileHeader: true,18 overflow: "scroll",19};2021export const DraftedFile = ({ content, path }: DraftedFileProps) => {22 const file = useMemo(23 () => ({ contents: content, name: path }),24 [content, path]25 );2627 return (28 <CodePool>29 <div className="border-rule min-w-0 border" data-code="pierre">30 <File file={file} options={options} />31 </div>32 </CodePool>33 );34};3536// `React.lazy` takes a module's default export.37export default DraftedFile;
deleted:apps/web/src/features/proposal/failure.tsx-52 removed
1import { Unauthenticated } from "@repo/protocol/principal";2import { Refusal } from "@repo/protocol/refusal";3import { Cause, Option, Schema } from "effect";4import { LogIn } from "lucide-react";56import { signInHref } from "../auth/session-slot.tsx";7import { UnreachableNotice } from "../shared/pending.tsx";8import { RefusalView } from "../shared/refusal.tsx";910const isUnauthenticated = Schema.is(Unauthenticated);1112const isRefusal = Schema.is(Refusal);1314export const ProposalFailure = ({15 cause,16 doing,17 here,18}: {19 readonly cause: Cause.Cause<unknown>;20 readonly doing: string;21 readonly here: string;22}) => {23 const error = Cause.findErrorOption(cause);2425 if (Option.exists(error, isUnauthenticated)) {26 return (27 <p className="border-rule text-ui flex items-start gap-2 border-y py-3">28 <LogIn29 aria-hidden="true"30 className="mt-0.5 size-4 shrink-0"31 strokeWidth={1.75}32 />33 <span>34 You are not signed in, or your session has ended.{" "}35 <a36 className="decoration-rule font-medium underline hover:decoration-current"37 href={signInHref(here)}38 >39 Sign in40 </a>{" "}41 to {doing}; you come back to this page.42 </span>43 </p>44 );45 }4647 return Option.isSome(error) && isRefusal(error.value) ? (48 <RefusalView refusals={[error.value]} />49 ) : (50 <UnreachableNotice />51 );52};
deleted:apps/web/src/features/proposal/live-draft.ts-34 removed
1import { useAtomValue } from "@effect/atom-react";2import type { ShowProposal } from "@repo/protocol/contracts";3import type { DraftState } from "@repo/protocol/domain/proposal";4import type { ProjectName, ProposalId } from "@repo/protocol/ids";5import { Data, Option } from "effect";6import { AsyncResult } from "effect/reactivity";78import { proposalAtom } from "../../client/proposal.ts";910export type DraftRead = Data.TaggedEnum<{11 Read: { readonly draft: Option.Option<DraftState> };12 Unread: { readonly failed: boolean };13}>;1415export const DraftRead = Data.taggedEnum<DraftRead>();1617export const readDraft = (draft?: DraftState): DraftRead =>18 DraftRead.Read({ draft: Option.fromUndefinedOr(draft) });1920export const draftReadOf = (21 result: AsyncResult.AsyncResult<22 typeof ShowProposal.successSchema.Type,23 unknown24 >25): DraftRead =>26 Option.match(AsyncResult.value(result), {27 onNone: () => DraftRead.Unread({ failed: AsyncResult.isFailure(result) }),28 onSome: (shown) => readDraft(shown.proposal.draft),29 });3031export const useLiveDraft = (32 project: ProjectName,33 proposal: ProposalId34): DraftRead => draftReadOf(useAtomValue(proposalAtom(project)(proposal)));
deleted:apps/web/src/features/proposal/proposal-view.tsx-483 removed
1import { Brand } from "@repo/brand";2import type { ConfigFile } from "@repo/protocol/domain/common";3import { DraftState } from "@repo/protocol/domain/proposal";4import type { Proposal } from "@repo/protocol/domain/proposal";5import type { DecisionId, ProjectName } from "@repo/protocol/ids";6import { groups } from "@repo/protocol/refusal";7import type { Refusal } from "@repo/protocol/refusal";8import { Array as Arr, DateTime, Option } from "effect";9import { constVoid } from "effect/Function";10import { ChevronDown, Scale, X } from "lucide-react";11import { useId, useState } from "react";12import type { ReactNode } from "react";1314import { Button } from "../../components/ui/button.tsx";15import { Textarea } from "../../components/ui/textarea.tsx";16import { isTestPath } from "../code/diff-model.ts";17import { FactBlock } from "../shared/facts.tsx";18import { HandleLink } from "../shared/handle.tsx";19import { AppLink } from "../shared/link.tsx";20import { decisionPath } from "../shared/paths.ts";21import { RefusalView } from "../shared/refusal.tsx";22import { Workspace } from "../shared/shell/workspace.tsx";23import { StatusLine } from "../shared/status-line.tsx";24import { When } from "../shared/time.tsx";25import { DraftedCode } from "./client-file.tsx";2627/**28 * The platform's `DRAFT_ROUNDS`, which the web's production code does not29 * import; `test/proposal.test.tsx` holds the two equal.30 */31export const DRAFT_ATTEMPTS = 3;3233const NOTE_LIMIT = 2000;3435export const standing = (proposal: Proposal) =>36 proposal.state === "open" && proposal.draft !== undefined37 ? proposal.draft._tag38 : proposal.state;3940const draftingNow = DraftState.isAnyOf(["Drafting"]);4142const failedNow = DraftState.isAnyOf(["Failed"]);4344export const isDrafting = (proposal: Proposal) =>45 proposal.draft !== undefined && draftingNow(proposal.draft);4647const refusalKinds = groups.flatMap(({ members }) => [...members]);4849/**50 * A draft keeps only the tag, so a refusal that needs fields of its own cannot51 * be drawn whole.52 */53export const refusalOfTag = (tag: string): Option.Option<Refusal> =>54 Arr.findFirst(refusalKinds, (kind) => kind.identifier === tag).pipe(55 Option.flatMap((kind): Option.Option<Refusal> =>56 // SAFETY: `makeOption` checks its input at run time, so a refusal whose fields all have defaults is made and one that needs a field answers None.57 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a loop over the union's members cannot name each member's input; see SAFETY.58 kind.makeOption({} as never)59 )60 );6162const isAskFile = ({ path }: ConfigFile) =>63 path.startsWith(`${Brand.configDir}/`) || path.endsWith(".ask.ts");6465const filesInOrder = (files: readonly ConfigFile[]) => {66 const askFile = files.find(isAskFile);67 const rest = files.filter((file) => file !== askFile);68 const checks = rest.filter(({ path }) => isTestPath(path));69 const others = rest.filter(({ path }) => !isTestPath(path));7071 return { askFile, checks, others };72};7374const kindIn = (source: string) =>75 /\bkinds\.(?<kind>[A-Za-z]+)/u.exec(source)?.groups?.kind;7677const Step = ({78 children,79 id,80 title,81}: {82 readonly children: ReactNode;83 readonly id: string;84 readonly title: string;85}) => (86 <section aria-labelledby={id} className="flex min-w-0 flex-col gap-3">87 <h2 className="text-title" id={id}>88 {title}89 </h2>90 {children}91 </section>92);9394const Row = ({95 children,96 label,97}: {98 readonly children: ReactNode;99 readonly label: string;100}) => (101 <div className="contents">102 <dt className="text-label text-muted-foreground pt-0.5">{label}</dt>103 <dd className="text-ui min-w-0 [overflow-wrap:anywhere]">{children}</dd>104 </div>105);106107const AskFileStep = ({108 file,109 proposal,110}: {111 readonly file: ConfigFile | undefined;112 readonly proposal: Proposal;113}) => {114 const kind = file === undefined ? undefined : kindIn(file.content);115116 return (117 <Step id={`${proposal.id}-ask-file`} title="The ask file">118 <dl className="tablet:grid-cols-[7rem_1fr] grid grid-cols-1 gap-x-4 gap-y-1.5">119 <Row label="Want">{proposal.want}</Row>120 {proposal.territory === undefined ? null : (121 <Row label="Territory">122 <code className="text-mono font-mono">{proposal.territory}</code>123 </Row>124 )}125 {kind === undefined ? null : (126 <Row label="Kind">127 <code className="text-mono font-mono">{kind}</code>128 </Row>129 )}130 </dl>131 {file === undefined ? null : (132 <details className="group">133 <summary className="text-ui text-muted-foreground hover:text-foreground flex w-fit cursor-pointer list-none items-center gap-1.5 [&::-webkit-details-marker]:hidden">134 Its source, <code className="text-mono font-mono">{file.path}</code>135 <ChevronDown136 aria-hidden="true"137 className="size-3.5 transition-transform duration-150 group-open:rotate-180"138 strokeWidth={1.75}139 />140 </summary>141 <div className="mt-2">142 <DraftedCode content={file.content} path={file.path} />143 </div>144 </details>145 )}146 </Step>147 );148};149150const RedFirst = ({ draft }: { readonly draft: DraftState }) =>151 DraftState.match(draft, {152 Drafting: () => null,153 Failed: () => null,154 Ready: ({ attempts, model, red }) => (155 <Step id="red-first" title="Red first">156 <p className="text-ui">157 The check ran on main and fails twice the same way in lane {red.lane}:{" "}158 <span className="sr-only">{red.signature}</span>159 </p>160 <samp161 aria-hidden="true"162 className="border-rule bg-surface text-mono leading-terminal block border px-3 py-2 font-mono [overflow-wrap:anywhere] whitespace-pre-wrap"163 >164 {red.signature}165 </samp>166 <p className="text-label text-muted-foreground font-normal">167 drafted by {model}, attempt {attempts} of {DRAFT_ATTEMPTS}168 </p>169 </Step>170 ),171 });172173const FailedRound = ({ draft }: { readonly draft: DraftState }) =>174 DraftState.match(draft, {175 Drafting: () => null,176 Failed: ({ attempts, model, refusal, round }) =>177 Option.match(refusalOfTag(refusal), {178 onNone: () => (179 <p className="text-want flex items-start gap-2" data-draft="Failed">180 <X181 aria-hidden="true"182 className="mt-1 size-4 shrink-0"183 strokeWidth={1.75}184 />185 <span>186 <strong className="font-semibold">The draft failed:</strong>{" "}187 <code className="text-mono font-mono">{refusal}</code>, in round{" "}188 {round}, after {attempts} of {DRAFT_ATTEMPTS} attempts by {model}.189 </span>190 </p>191 ),192 onSome: (made) => (193 <div className="flex flex-col gap-2" data-draft="Failed">194 <p className="text-ui text-muted-foreground">195 Round {round} failed after {attempts} of {DRAFT_ATTEMPTS} attempts196 by {model}, with:197 </p>198 <RefusalView refusals={[made]} />199 </div>200 ),201 }),202 Ready: () => null,203 });204205const Redraft = ({206 again,207 busy,208 onRedraft,209}: {210 readonly again: boolean;211 readonly busy: boolean;212 readonly onRedraft: (note: string | undefined) => void;213}) => {214 const [note, setNote] = useState("");215 const noteId = useId();216217 return (218 <section219 aria-label="Draft again"220 className="border-rule flex flex-col gap-3 border-t pt-4"221 >222 <details className="group">223 <summary className="text-ui text-muted-foreground hover:text-foreground flex w-fit cursor-pointer list-none items-center gap-1.5 py-1 select-none [&::-webkit-details-marker]:hidden">224 Add a note for the agent225 <ChevronDown226 aria-hidden="true"227 className="size-3.5 transition-transform duration-150 group-open:rotate-180"228 strokeWidth={1.75}229 />230 </summary>231 <label232 className="text-label text-muted-foreground mt-2 block"233 htmlFor={noteId}234 >235 What the next draft should do differently236 </label>237 <Textarea238 className="tablet:text-ui mt-1 text-base"239 id={noteId}240 maxLength={NOTE_LIMIT}241 onChange={(event) => {242 setNote(event.target.value);243 }}244 value={note}245 />246 </details>247 <Button248 className="tablet:h-9 tablet:w-fit h-11 w-full px-4"249 disabled={busy}250 onClick={() => {251 const written = note.trim();252253 onRedraft(written.length === 0 ? undefined : written);254 }}255 type="button"256 variant="outline"257 >258 {again ? "Draft again" : "Let the platform's agent draft it"}259 </Button>260 </section>261 );262};263264const DecisionLink = ({265 decision,266 project,267}: {268 readonly decision: DecisionId;269 readonly project: ProjectName;270}) => (271 <AppLink272 className="text-ui decoration-rule flex w-fit items-center gap-2 font-medium underline hover:decoration-current"273 data-decision={decision}274 to={decisionPath(project, decision)}275 >276 <Scale aria-hidden="true" className="size-4 shrink-0" strokeWidth={1.75} />277 Decide it: {decision}278 </AppLink>279);280281const roundLine = (draft: DraftState) =>282 DraftState.match(draft, {283 Drafting: ({ round }) => `Round ${round}, drafting now`,284 Failed: ({ attempts, round }) =>285 `Round ${round} failed after ${attempts} of ${DRAFT_ATTEMPTS} attempts`,286 Ready: ({ attempts, round }) =>287 `Round ${round} ready after ${attempts} of ${DRAFT_ATTEMPTS} attempts`,288 });289290const ProposalFacts = ({291 decision,292 now,293 project,294 proposal,295}: {296 readonly decision: Option.Option<DecisionId>;297 readonly now: DateTime.Utc;298 readonly project: ProjectName;299 readonly proposal: Proposal;300}) => (301 <>302 <FactBlock label="Proposal">303 <dl className="text-ui grid grid-cols-[6rem_1fr] gap-x-3 gap-y-1.5">304 <dt className="text-label text-muted-foreground pt-0.5">Proposed by</dt>305 <dd>306 <HandleLink handle={proposal.proposer} />{" "}307 <span className="text-muted-foreground">308 <When at={proposal.openedAt} now={now} />309 </span>310 </dd>311 <dt className="text-label text-muted-foreground pt-0.5">Expires</dt>312 <dd>313 <When at={proposal.expiresAt} now={now} />314 <span className="text-muted-foreground">315 {" "}316 unless a maintainer opens it317 </span>318 </dd>319 <dt className="text-label text-muted-foreground pt-0.5">State</dt>320 <dd321 className="first-letter:uppercase"322 data-standing={standing(proposal)}323 >324 {proposal.state}325 </dd>326 </dl>327 </FactBlock>328 {Option.isSome(decision) ? (329 <FactBlock label="Decision">330 <DecisionLink decision={decision.value} project={project} />331 </FactBlock>332 ) : null}333 {proposal.draft === undefined ? null : (334 <FactBlock label="Drafting">335 <p className="text-ui">{roundLine(proposal.draft)}</p>336 </FactBlock>337 )}338 </>339);340341const ProposalStatus = ({ proposal }: { readonly proposal: Proposal }) => {342 const { draft } = proposal;343 const drafting = draft !== undefined && draftingNow(draft);344345 return (346 <div347 className="flex flex-col gap-3"348 data-draft={draft?._tag}349 data-proposal={proposal.id}350 data-standing={standing(proposal)}351 >352 {draft !== undefined && failedNow(draft) && proposal.state === "open" ? (353 <FailedRound draft={draft} />354 ) : (355 <StatusLine subject={{ kind: "proposal", proposal }} />356 )}357 {drafting ? (358 <p className="text-ui text-muted-foreground max-w-(--measure)">359 The platform&apos;s agent is writing the ask and a check, then running360 the check on main, where it must fail twice the same way. This takes a361 few minutes; the page follows it.362 </p>363 ) : null}364 {drafting && draft.note !== undefined ? (365 <p366 className="text-ui [overflow-wrap:anywhere] whitespace-pre-line"367 data-note=""368 >369 <span className="text-label text-muted-foreground">Note:</span>{" "}370 {draft.note}371 </p>372 ) : null}373 </div>374 );375};376377const DraftGuide = ({378 files,379 proposal,380}: {381 readonly files: readonly ConfigFile[];382 readonly proposal: Proposal;383}) => {384 const { askFile, checks, others } = filesInOrder(files);385 const kept = proposal.draft !== undefined && failedNow(proposal.draft);386387 if (files.length === 0) {388 return proposal.draft === undefined ? (389 <p className="text-body max-w-(--measure)">390 A want alone: no ask file or check yet. A maintainer who accepts it391 writes the change it asks for.392 </p>393 ) : null;394 }395396 return (397 <>398 {kept ? (399 <p className="text-ui text-muted-foreground" data-kept="">400 An earlier round&apos;s ready draft, which a maintainer can still401 accept: it runs red first again on main before the ask opens.402 </p>403 ) : null}404 <AskFileStep file={askFile} proposal={proposal} />405 {checks.length === 0 ? null : (406 <Step id={`${proposal.id}-check`} title="The check">407 {[...checks, ...others].map(({ content, path }) => (408 <DraftedCode content={content} key={path} path={path} />409 ))}410 </Step>411 )}412 {proposal.draft === undefined ? null : (413 <RedFirst draft={proposal.draft} />414 )}415 </>416 );417};418419export const ProposalView = ({420 busy = false,421 children,422 decision,423 files,424 mayRedraft,425 now = DateTime.nowUnsafe(),426 onRedraft = constVoid,427 project,428 proposal,429}: {430 readonly project: ProjectName;431 readonly proposal: Proposal;432 readonly files: readonly ConfigFile[];433 readonly decision: Option.Option<DecisionId>;434 readonly mayRedraft: boolean;435 readonly onRedraft?: (note: string | undefined) => void;436 readonly busy?: boolean;437 readonly children?: ReactNode;438 readonly now?: DateTime.Utc;439}): ReactNode => {440 const open = proposal.state === "open";441442 return (443 <Workspace444 crumbs={[445 { label: project, to: `/${project}` },446 { label: "Proposals" },447 { label: proposal.id, mono: true },448 ]}449 facts={450 <ProposalFacts451 decision={decision}452 now={now}453 project={project}454 proposal={proposal}455 />456 }457 factsHeading="This proposal"458 meta={459 <>460 proposed by <HandleLink handle={proposal.proposer} /> ·{" "}461 <code className="text-mono font-mono">{proposal.id}</code>462 </>463 }464 state={<StatusLine compact subject={{ kind: "proposal", proposal }} />}465 status={<ProposalStatus proposal={proposal} />}466 said467 title={proposal.want}468 >469 {Option.isSome(decision) && open ? (470 <DecisionLink decision={decision.value} project={project} />471 ) : null}472 <DraftGuide files={files} proposal={proposal} />473 {children}474 {mayRedraft && open && !isDrafting(proposal) ? (475 <Redraft476 again={proposal.draft !== undefined}477 busy={busy}478 onRedraft={onRedraft}479 />480 ) : null}481 </Workspace>482 );483};
deleted:apps/web/src/features/propose/client-territory.tsx-47 removed
1/**2 * `import.meta.env.SSR` is `true` in the Worker's build, so the dynamic import3 * below is dead code there and the Worker bundles none of it.4 */5import { ClientOnly } from "@tanstack/react-router";6import { ChevronDown } from "lucide-react";7import { lazy, Suspense } from "react";89import type { TerritorySelectProps } from "./territory-select.tsx";1011const SelectLater = import.meta.env.SSR12 ? undefined13 : lazy(() => import("./territory-select.tsx"));1415const StandIn = ({ choices, labelledBy, value }: TerritorySelectProps) => (16 <>17 <button18 aria-labelledby={labelledBy}19 className="border-input tablet:text-ui tablet:h-9 flex h-11 w-full max-w-xs items-center justify-between gap-1.5 border bg-transparent py-2 pr-2 pl-2.5 text-base"20 data-slot="select-trigger"21 disabled22 type="button"23 >24 {choices.find((choice) => choice.value === value)?.label ?? value}25 <ChevronDown26 aria-hidden="true"27 className="text-muted-foreground size-4"28 strokeWidth={1.75}29 />30 </button>31 <input name="territory" type="hidden" value={value} />32 </>33);3435export const ClientTerritorySelect = (props: TerritorySelectProps) => {36 const fallback = <StandIn {...props} />;3738 return SelectLater === undefined ? (39 fallback40 ) : (41 <ClientOnly fallback={fallback}>42 <Suspense fallback={fallback}>43 <SelectLater {...props} />44 </Suspense>45 </ClientOnly>46 );47};
deleted:apps/web/src/features/propose/propose-link.tsx-32 removed
1/**2 * Who is signed in is the browser's to learn, after the first paint, so the3 * server renders no link and the browser adds it.4 */5import { useAtomValue } from "@effect/atom-react";6import type { ProjectName } from "@repo/protocol/ids";7import { Option } from "effect";8import { AsyncResult } from "effect/reactivity";9import { MessageSquarePlus } from "lucide-react";1011import { whoAtom } from "../auth/who.ts";12import { proposeFormPath } from "./propose-view.tsx";1314export const ProposeLink = ({ project }: { readonly project: ProjectName }) => (15 <a16 className="text-ui decoration-rule flex w-fit items-center gap-2 font-medium underline hover:decoration-current"17 data-propose=""18 href={proposeFormPath(project)}19 >20 <MessageSquarePlus aria-hidden="true" className="size-4 shrink-0" />21 Propose an ask22 </a>23);2425export const SignedInProposeLink = ({26 project,27}: {28 readonly project: ProjectName;29}) =>30 Option.isSome(Option.flatten(AsyncResult.value(useAtomValue(whoAtom)))) ? (31 <ProposeLink project={project} />32 ) : null;
deleted:apps/web/src/features/propose/propose-view.tsx-336 removed
1import { Brand } from "@repo/brand";2import type { ProposeAsk } from "@repo/protocol/contracts";3import type { CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";4import { Option } from "effect";5import { LogIn } from "lucide-react";6import { useId, useState } from "react";7import type { ReactNode } from "react";89import { Button } from "../../components/ui/button.tsx";10import { Checkbox } from "../../components/ui/checkbox.tsx";11import { Label } from "../../components/ui/label.tsx";12import { Spinner } from "../../components/ui/spinner.tsx";13import { Textarea } from "../../components/ui/textarea.tsx";14import { signInHref } from "../auth/session-slot.tsx";15import { CommandLine } from "../shared/command.tsx";16import { FactBlock } from "../shared/facts.tsx";17import { Workspace } from "../shared/shell/workspace.tsx";18import { ClientTerritorySelect } from "./client-territory.tsx";1920export type ProposePayload = typeof ProposeAsk.payloadSchema.Type;2122export interface About {23 readonly path: RepoPath;24 readonly line: number;25 readonly at: CommitSha;26}2728/**29 * `draft: true` only when the box is checked: the contract takes no `draft:30 * false`.31 */32export const proposalPayload = (form: {33 readonly project: ProjectName;34 readonly want: string;35 readonly territory?: RepoPath;36 readonly draft: boolean;37}): ProposePayload => {38 const want = form.want.trim();3940 const named =41 form.territory === undefined42 ? { project: form.project, want }43 : { project: form.project, territory: form.territory, want };4445 return form.draft ? { ...named, draft: true } : named;46};4748export const wantAbout = ({ at, line, path }: About) =>49 `In \`${path}\` line ${line} at ${at.slice(0, 7)}: `;5051export const proposeFormPath = (52 project: ProjectName,53 about: Option.Option<About> = Option.none()54) =>55 Option.match(about, {56 onNone: () => `/${project}/proposals/new`,57 onSome: ({ at, line, path }) =>58 `/${project}/proposals/new?${new URLSearchParams({ about: path, at, line: String(line) }).toString()}`,59 });6061const AGENT_CHOOSES = "";6263export const territoryChoices = (modules: readonly RepoPath[]) => [64 { label: "Let the agent choose", value: AGENT_CHOOSES },65 ...modules.map((module) => ({ label: module, value: module })),66];6768const proposeWords = (written: boolean, busy: boolean) => {69 if (!written) {70 return "Write the want first";71 }7273 return busy ? "Proposing" : "Propose";74};7576/** The same proposal from a terminal, with the flags the CLI's `propose` takes: the want, the project, and a draft asked for. */77export const proposeCommand = (project: ProjectName) =>78 `${Brand.cli} propose --want "<want>" --project ${project} --draft`;7980const SignInFirst = ({81 about,82 project,83}: {84 readonly about: Option.Option<About>;85 readonly project: ProjectName;86}) => (87 <section88 aria-label="Sign in to propose"89 className="flex max-w-(--measure) flex-col items-start gap-3"90 >91 <p className="text-body">92 A proposal asks {project} to open an ask nobody wrote yet: a want in your93 words, which the platform&apos;s agent can draft into an ask file and a94 failing check for a maintainer to accept.95 </p>96 <p className="text-ui flex items-start gap-2">97 <LogIn98 aria-hidden="true"99 className="mt-0.5 size-4 shrink-0"100 strokeWidth={1.75}101 />102 <span>103 Proposing is for signed-in members.{" "}104 <a105 className="decoration-rule font-medium underline hover:decoration-current"106 href={signInHref(proposeFormPath(project, about))}107 >108 Sign in109 </a>{" "}110 to propose one here, or propose from your clone:111 </span>112 </p>113 <CommandLine command={proposeCommand(project)} />114 </section>115);116117const GoodWant = ({ project }: { readonly project: ProjectName }) => (118 <>119 <FactBlock label="A good want">120 <ul className="text-ui flex list-disc flex-col gap-1.5 pl-4">121 <li>Says what the project should do, not how to change the code.</li>122 <li>Asks for one change, small enough to check on its own.</li>123 <li>Says how you would tell it is done: what a check would see.</li>124 </ul>125 </FactBlock>126 <FactBlock label="From a terminal">127 <CommandLine command={proposeCommand(project)} numbered />128 </FactBlock>129 </>130);131132const Form = ({133 about,134 busy,135 children,136 modules,137 onPropose,138 project,139}: {140 readonly project: ProjectName;141 readonly about: Option.Option<About>;142 readonly modules: readonly RepoPath[];143 readonly onPropose?: ((payload: ProposePayload) => void) | undefined;144 readonly busy: boolean;145 readonly children?: ReactNode;146}) => {147 const id = useId();148149 const [want, setWant] = useState(() =>150 Option.match(about, { onNone: () => "", onSome: wantAbout })151 );152153 const [territory, setTerritory] = useState(AGENT_CHOOSES);154 const [draft, setDraft] = useState(true);155 const chosen = modules.find((module) => module === territory);156 const written = want.trim().length > 0;157 const choices = territoryChoices(modules);158159 return (160 <form161 aria-label="Propose an ask"162 className="flex max-w-(--measure) flex-col gap-6"163 data-propose=""164 onSubmit={(event) => {165 event.preventDefault();166167 if (written) {168 onPropose?.(169 proposalPayload(170 chosen === undefined171 ? { draft, project, want }172 : { draft, project, territory: chosen, want }173 )174 );175 }176 }}177 >178 <div className="flex flex-col gap-1.5">179 <label className="text-ui font-medium" htmlFor={`${id}-want`}>180 What should {project} do that it does not do now?181 </label>182 <Textarea183 className="min-h-32 text-base leading-6"184 id={`${id}-want`}185 name="want"186 onChange={(event) => {187 setWant(event.target.value);188 }}189 required190 value={want}191 />192 </div>193194 <div className="flex flex-col gap-1.5">195 <span className="text-ui font-medium" id={`${id}-territory`}>196 Territory197 </span>198 <ClientTerritorySelect199 choices={choices}200 labelledBy={`${id}-territory`}201 onChange={setTerritory}202 value={territory}203 />204 <p className="text-label text-muted-foreground font-normal">205 One of the project&apos;s top folders, or the agent picks from the206 want.207 </p>208 </div>209210 <div className="flex flex-col gap-1.5">211 <div className="flex items-start gap-2">212 <Checkbox213 checked={draft}214 className="mt-0.5"215 id={`${id}-draft`}216 name="draft"217 onCheckedChange={(checked) => {218 setDraft(checked);219 }}220 />221 <Label className="text-ui leading-snug" htmlFor={`${id}-draft`}>222 Let the platform&apos;s agent draft the ask223 </Label>224 </div>225 <p className="text-label text-muted-foreground pl-6 font-normal">226 It writes the ask file and a check that fails on main, runs it red227 first, and puts the draft to a maintainer. Clear the box to propose228 the want alone.229 </p>230 </div>231232 {children}233234 <Button235 className={`tablet:h-9 tablet:w-fit h-11 w-full min-w-28 px-4 ${written ? "" : "text-muted-foreground border-dashed disabled:opacity-100"}`}236 data-written={written}237 disabled={busy || !written}238 type="submit"239 variant={written ? "default" : "outline"}240 >241 {busy ? <Spinner /> : null}242 {proposeWords(written, busy)}243 </Button>244 </form>245 );246};247248const ProposeBody = ({249 about,250 busy,251 checking,252 children,253 modules,254 onPropose,255 project,256 signedIn,257}: {258 readonly project: ProjectName;259 readonly signedIn: boolean;260 readonly checking: boolean;261 readonly about: Option.Option<About>;262 readonly modules: readonly RepoPath[];263 readonly onPropose?: ((payload: ProposePayload) => void) | undefined;264 readonly busy: boolean;265 readonly children?: ReactNode;266}) => {267 if (checking) {268 return (269 <output className="text-ui text-muted-foreground block">270 Checking who is signed in271 </output>272 );273 }274275 return signedIn ? (276 <Form277 about={about}278 busy={busy}279 modules={modules}280 onPropose={onPropose}281 project={project}282 >283 {children}284 </Form>285 ) : (286 <SignInFirst about={about} project={project} />287 );288};289290export const ProposeView = ({291 about,292 busy = false,293 checking = false,294 children,295 modules,296 onPropose,297 project,298 signedIn,299}: {300 readonly project: ProjectName;301 readonly signedIn: boolean;302 readonly checking?: boolean;303 readonly about: Option.Option<About>;304 readonly modules: readonly RepoPath[];305 readonly onPropose?: (payload: ProposePayload) => void;306 readonly busy?: boolean;307 readonly children?: ReactNode;308}): ReactNode => (309 <div className="contents [&_[data-facts=inline]]:hidden">310 <Workspace311 crumbs={[312 { label: project, to: `/${project}` },313 { label: "Propose an ask" },314 ]}315 facts={<GoodWant project={project} />}316 factsHeading="Proposing"317 meta="A maintainer decides whether the ask opens; nothing lands from here."318 title="Propose an ask"319 >320 <ProposeBody321 about={about}322 busy={busy}323 checking={checking}324 modules={modules}325 onPropose={onPropose}326 project={project}327 signedIn={signedIn}328 >329 {children}330 </ProposeBody>331 <div className="border-rule flex flex-col border-t pt-4">332 <GoodWant project={project} />333 </div>334 </Workspace>335 </div>336);
deleted:apps/web/src/features/propose/territory-select.tsx-54 removed
1import {2 Select,3 SelectContent,4 SelectItem,5 SelectTrigger,6 SelectValue,7} from "../../components/ui/select.tsx";89export interface TerritorySelectProps {10 readonly choices: readonly {11 readonly label: string;12 readonly value: string;13 }[];14 readonly labelledBy: string;15 readonly onChange: (value: string) => void;16 readonly value: string;17}1819export const TRIGGER =20 "tablet:text-ui tablet:h-9 h-11 w-full max-w-xs text-base";2122export const TerritorySelect = ({23 choices,24 labelledBy,25 onChange,26 value,27}: TerritorySelectProps) => (28 <Select29 items={choices}30 name="territory"31 onValueChange={(chosen) => {32 onChange(chosen ?? "");33 }}34 value={value}35 >36 <SelectTrigger aria-labelledby={labelledBy} className={TRIGGER}>37 <SelectValue />38 </SelectTrigger>39 <SelectContent>40 {choices.map(({ label, value: each }) => (41 <SelectItem key={each} value={each}>42 {each === "" ? (43 label44 ) : (45 <code className="text-mono font-mono">{label}</code>46 )}47 </SelectItem>48 ))}49 </SelectContent>50 </Select>51);5253// `React.lazy` takes a module's default export.54export default TerritorySelect;
modified:apps/web/src/features/shared/shell/sections.ts+21 added-53 removed
1 unmodified line
2import { Option } from "effect";34import { INBOX_PATH, segmentsOf } from "../paths.ts";56/** A project's nine tabs (ADR 0041, with Discussions), in the header's order. */6/** A project's seven tabs (ADR 0041, with Discussions), in the header's order. */7export type ProjectTab =8 | "asks"9 | "code"10 | "discussions"11 | "landings"12 | "overview"13 | "people"13 | "policy"15 | "proposals"14 | "visibility";1516export interface Section {17 readonly label: string;18 readonly tab: ProjectTab;19 readonly to: string;22 /** A tab whose own page has not been built yet opens the region of Overview that holds it. */23 readonly hash?: string;20 /** A tab that opens a page's filtered view carries the filter in the query. */21 readonly search?: Readonly<Record<string, string>>;22}2324/**29 * Each tab opens a page inside the project's frame that exists today: Asks,30 * Proposals and People open their regions of Overview, Landings the history31 * of main shown as its landings (the Code tab's History, filtered), Policy32 * the policy at the address it has always had, and Visibility its own page.33 * Starting a proposal is a focused page of its own, so it is Contribute's,34 * not a tab's.25 * Each tab opens a page of its own inside the project's frame: Landings is26 * the history of main shown as its landings (the Code tab's History,27 * filtered), and Policy holds who decides as well as the limits.28 */29export const projectSections = (project: string): readonly Section[] => [30 { label: "Overview", tab: "overview", to: `/${project}` },31 { label: "Code", tab: "code", to: `/${project}/tree/main` },39 { hash: "open-asks", label: "Asks", tab: "asks", to: `/${project}` },32 { label: "Asks", tab: "asks", to: `/${project}/asks` },33 {34 label: "Landings",35 search: { show: "landings" },36 tab: "landings",37 to: `/${project}/commits/main`,38 },46 {47 hash: "proposals",48 label: "Proposals",49 tab: "proposals",50 to: `/${project}`,51 },39 { label: "Discussions", tab: "discussions", to: `/${project}/discussions` },53 { hash: "who-decides", label: "People", tab: "people", to: `/${project}` },54 { label: "Policy", tab: "policy", to: `/${project}/people` },40 { label: "Policy", tab: "policy", to: `/${project}/policy` },41 { label: "Visibility", tab: "visibility", to: `/${project}/visibility` },42];4344/** The tab each page of a project sits under, by its first segment: the history and a commit are the Landings tab's, as its crumb says. */
4 unmodified lines
49 commit: "landings",50 commits: "landings",51 decisions: "asks",52 discussions: "discussions",67 people: "policy",68 proposals: "proposals",53 policy: "policy",54 raw: "code",55 refs: "code",56 tree: "code",57 visibility: "visibility",
1 unmodified line
59} as const satisfies Record<string, ProjectTab>;6061/** A crumb names the page itself, which may be narrower than its tab. */62type PageSection =63 | "asks"64 | "code"65 | "discussions"66 | "landings"67 | "overview"82 | "people"68 | "policy"69 | "refs"70 | "visibility";7172const PAGE_TO = (project: string) =>73 ({74 asks: `/${project}/asks`,75 code: `/${project}/tree/main`,76 discussions: `/${project}/discussions`,77 landings: `/${project}/commits/main`,78 overview: `/${project}`,92 people: `/${project}/people`,79 policy: `/${project}/policy`,80 refs: `/${project}/refs`,81 visibility: `/${project}/visibility`,82 }) as const satisfies Record<PageSection, string>;8384const SECTION_OF = {98 answers: "overview",99 asks: "overview",85 answers: "asks",86 asks: "asks",87 blob: "code",88 commit: "landings",89 commits: "landings",90 discussions: "discussions",104 people: "people",91 policy: "policy",92 refs: "refs",93 tree: "code",94 visibility: "visibility",95 why: "code",
27 unmodified lines
123 ? "overview"124 : Object.entries(TAB_OF).find(([segment]) => segment === page)?.[1];125};126140/**141 * The pages under a project that its route draws in another shell: starting142 * a proposal is focused (`staticData.shell` is `focus`), so it has no header.143 */144const OUTSIDE_FRAME: readonly (readonly string[])[] = [["proposals", "new"]];145127/** Whether a path is a project's page drawn in the project's frame, under its header. */147export const inProjectFrame = (pathname: string): boolean => {148 const address = addressOf(pathname);128export const inProjectFrame = (pathname: string): boolean =>129 addressOf(pathname) !== undefined;130150 return (151 address !== undefined &&152 !OUTSIDE_FRAME.some(153 (page) =>154 page.length === address.rest.length &&155 page.every((segment, at) => address.rest[at] === segment)156 )157 );158};159131const sectionOf = (pathname: string): PageSection | undefined => {132 const address = addressOf(pathname);133134 if (address === undefined) {
13 unmodified lines
148 readonly to?: string;149}150151const SECTION_LABEL = {152 asks: "Asks",153 code: "Code",154 discussions: "Discussions",155 landings: "Landings",184 overview: "Asks",185 people: "Policy",156 overview: "Overview",157 policy: "Policy",158 refs: "Refs",159 visibility: "Visibility",160} as const satisfies Record<PageSection, string>;161
35 unmodified lines
197>;198199const SUBJECT_CRUMBS = {200 answers: (project: string, ask: string) => [229 ...projectCrumbs(project, "overview", true),201 ...projectCrumbs(project, "asks", true),202 { label: ask, mono: true, to: `/${project}/asks/${ask}` },203 { label: "Answer" },204 ],205 asks: (project: string, ask: string) => [234 ...projectCrumbs(project, "overview", true),206 ...projectCrumbs(project, "asks", true),207 { label: ask, mono: true },208 ],209 blob: (project: string, _rev: string, path: string) =>210 pathCrumbs(project, path),
9 unmodified lines
220 { label: project, to: `/${project}` },221 { label: "Inbox", to: INBOX_PATH },222 { label: decision, mono: true },223 ],252 proposals: (project: string, proposal: string) => [253 ...projectCrumbs(project, "overview", true),254 proposal === "new" ? { label: "Propose" } : { label: proposal, mono: true },255 ],224 tree: (project: string, _rev: string, path: string) =>225 pathCrumbs(project, path),226 why: (project: string, _rev: string, path: string) =>227 pathCrumbs(project, path),
44 unmodified lines
modified:apps/web/src/features/shared/shell/shells.ts+2 added-2 removed
1/**2 * The four frames a page is drawn in (ADR 0041). A route names its own in3 * `staticData.shell`; the deepest route that names one wins, so a project's4 * new proposal can be focused inside the project's routes.3 * `staticData.shell`; the deepest route that names one wins, so a page can4 * be focused inside routes that name another frame.5 */6import { useMatches } from "@tanstack/react-router";7import { createContext, useContext } from "react";8
20 unmodified lines
modified:apps/web/src/features/shared/ask-progress.ts-2 removed
99 unmodified lines
100 change(ask, startedOver);101 },102 DiscussionPosted: constVoid,103 LedgerAppended: constVoid,104 ProposalDrafted: constVoid,105 ProposalOpened: constVoid,104 Pushed: ({ ask, at, head }) => {105 change(ask, (progress) => ({ ...progress, lastPush: { at, head } }));106 },107 Released: ({ ask }) => {
106 unmodified lines
added:apps/web/src/features/shared/call-failure.tsx+52 added
1import { Unauthenticated } from "@repo/protocol/principal";2import { Refusal } from "@repo/protocol/refusal";3import { Cause, Option, Schema } from "effect";4import { LogIn } from "lucide-react";56import { signInHref } from "../auth/session-slot.tsx";7import { UnreachableNotice } from "./pending.tsx";8import { RefusalView } from "./refusal.tsx";910const isUnauthenticated = Schema.is(Unauthenticated);1112const isRefusal = Schema.is(Refusal);1314export const CallFailure = ({15 cause,16 doing,17 here,18}: {19 readonly cause: Cause.Cause<unknown>;20 readonly doing: string;21 readonly here: string;22}) => {23 const error = Cause.findErrorOption(cause);2425 if (Option.exists(error, isUnauthenticated)) {26 return (27 <p className="border-rule text-ui flex items-start gap-2 border-y py-3">28 <LogIn29 aria-hidden="true"30 className="mt-0.5 size-4 shrink-0"31 strokeWidth={1.75}32 />33 <span>34 You are not signed in, or your session has ended.{" "}35 <a36 className="decoration-rule font-medium underline hover:decoration-current"37 href={signInHref(here)}38 >39 Sign in40 </a>{" "}41 to {doing}; you come back to this page.42 </span>43 </p>44 );45 }4647 return Option.isSome(error) && isRefusal(error.value) ? (48 <RefusalView refusals={[error.value]} />49 ) : (50 <UnreachableNotice />51 );52};
modified:apps/web/src/features/shared/paths.ts+13 added
73 unmodified lines
74 anchor: string,75 search: string76) => `/${project}/visibility${search}#${anchor}`;7778/** A project's policy page, which was `/people` until the People tab folded into it. */79export const policyPath = (project: ProjectName) => `/${project}/policy`;8081/** A project's own Asks tab, beside the site's `/asks`. */82export const projectAsksPath = (project: ProjectName) => `/${project}/asks`;8384/** The page of a project that moved to its policy page. */85export const MOVED_TO_POLICY = "people";8687/** Where the old `/people` goes: the policy page, the query as it was spelled. */88export const policyHref = (project: string, search: string) =>89 `/${project}/policy${search}`;9091export const decisionPath = (project: ProjectName, decision: DecisionId) =>92 `/${project}/decisions/${decision}`;9394const decoded = (segment: string) =>
10 unmodified lines
modified:apps/web/src/features/shared/status-line.tsx+1 added-61 removed
4 unmodified lines
5import type { Ask } from "@repo/protocol/domain/ask";6import type { Choice, Decision } from "@repo/protocol/domain/decision";7import { Outcome } from "@repo/protocol/domain/outcome";8import type { StageName } from "@repo/protocol/domain/outcome";9import { DraftState } from "@repo/protocol/domain/proposal";10import type { Proposal } from "@repo/protocol/domain/proposal";9import type { Handle, ProjectName } from "@repo/protocol/ids";10import { headline } from "@repo/protocol/render";11import { DateTime, Match } from "effect";12import { Fragment } from "react";
79 unmodified lines
92 readonly kind: "decision";93 readonly decision: Decision;94 readonly now: DateTime.Utc;95 readonly viewerDecides: boolean;98 }99 | { readonly kind: "proposal"; readonly proposal: Proposal };96 };9798export type StatusTone =99 | "checking"100 | "ink"
363 unmodified lines
464 tone: "waiting",465 };466};467471const proposalReading = (proposal: Proposal): Reading => {472 if (proposal.state === "accepted") {473 return { after: [], lead: "Accepted", mark: "landed", tone: "landed" };474 }475476 if (proposal.state === "declined") {477 return { after: [], lead: "Declined", mark: "notNeeded", tone: "ink" };478 }479480 if (proposal.state === "expired") {481 return { after: [], lead: "Expired", mark: "notNeeded", tone: "ink" };482 }483484 const waiting: Reading = {485 after: ["a maintainer's move"],486 lead: "Waiting",487 mark: "waiting",488 rest: " for a maintainer to open it or decline it",489 tone: "waiting",490 };491492 return proposal.draft === undefined493 ? waiting494 : DraftState.match(proposal.draft, {495 Drafting: ({ round }): Reading => ({496 after: ["the platform's move"],497 lead: "Drafting",498 mark: "checking",499 rest: round > 1 ? `, round ${round}` : undefined,500 tone: "checking",501 }),502 Failed: ({ attempts, refusal }): Reading => ({503 after: [],504 lead: "The draft failed",505 mark: "failed",506 rest: (507 <>508 {" "}509 after {attempts} {attempts === 1 ? "attempt" : "attempts"}:{" "}510 <Code>{refusal}</Code>511 </>512 ),513 tone: "ink",514 }),515 Ready: (): Reading => ({516 after: ["a maintainer's move"],517 lead: "Ready",518 mark: "waiting",519 rest: ", waits for a maintainer",520 tone: "waiting",521 }),522 });523};524468export const readStatus: (subject: StatusSubject) => Reading =469 Match.type<StatusSubject>().pipe(470 Match.discriminator("kind")("answer", answerReading),471 Match.discriminator("kind")("ask", askReading),472 Match.discriminator("kind")("decision", decisionReading),530 Match.discriminator("kind")("proposal", ({ proposal }) =>531 proposalReading(proposal)532 ),473 Match.exhaustive474 );475476const SIZE = {
73 unmodified lines
modified:apps/web/src/features/why/range-summary.tsx+1 added-17 removed
7 unmodified lines
8import { HandleLink } from "../shared/handle.tsx";9import { AppLink } from "../shared/link.tsx";10import { answerPath, askPath } from "../shared/paths.ts";11import { LandingWords } from "./band.tsx";12import {13 askOf,14 linesWords,15 priorHref,16 proposeHref,17 verdictWords,18} from "./rows.ts";12import { askOf, linesWords, priorHref, verdictWords } from "./rows.ts";13import type { WhyRow } from "./rows.ts";1415const LINK = "decoration-rule underline hover:decoration-current";16
25 unmodified lines
42 <AppLink className={LINK} to={prior}>43 why, one step back44 </AppLink>45 )}52 <a53 className={LINK}54 href={proposeHref(project, {55 at: view.at,56 line: row.range.start,57 path: view.path,58 })}59 >60 Propose an ask about this line61 </a>46 </span>47 );48};49
95 unmodified lines
modified:apps/web/src/features/why/rows.ts-13 removed
91 unmodified lines
92) =>93 Option.map(Option.fromUndefinedOr(commit.parents[0]), (parent) =>94 whyHref(project, pinnedRev(rev, parent), path)95 );9697export const proposeHref = (98 project: ProjectName,99 {100 at,101 line,102 path,103 }: { readonly at: string; readonly line: number; readonly path: string }104) => {105 const query = new URLSearchParams({ about: path, at, line: String(line) });106107 return `/${project}/proposals/new?${query.toString()}`;108};
added:apps/web/src/routes/$owner/$project/asks/index.tsx+120 added
1import { useAtomMount, useAtomValue } from "@effect/atom-react";2import { createFileRoute } from "@tanstack/react-router";3import { createServerFn } from "@tanstack/react-start";4import { env } from "cloudflare:workers";5import { Effect, Option, Predicate, Schema } from "effect";6import { AsyncResult } from "effect/reactivity";7import { useMemo } from "react";89import { projectEventsAtom } from "../../../../client/events.ts";10import { asksAtom } from "../../../../client/project.ts";11import { SeededAtoms, seedSuccess } from "../../../../client/seeded.ts";12import type { Seed } from "../../../../client/seeded.ts";13import { watchAtom } from "../../../../client/watch.ts";14import { useStamps } from "../../../../features/front/stamps.ts";15import { ProjectAsksView } from "../../../../features/project/asks-page.tsx";16import { UnknownProjectView } from "../../../../features/project/unknown-project.tsx";17import { askStates } from "../../../../features/shared/ask-progress.ts";18import { pageHead } from "../../../../features/shared/head.ts";19import { reloadOnEnter } from "../../../../features/shared/shell/selection.ts";20import { branchPage } from "../../../../server/cache-headers.ts";21import { serverClient } from "../../../../server/client.ts";22import {23 ProjectAsksData,24 readProjectAsks,25} from "../../../../server/project-page.ts";2627const asksPage = createServerFn({ method: "GET" })28 .validator((name: string) => name)29 .handler(({ data }) =>30 Effect.runPromise(31 readProjectAsks(data).pipe(Effect.provide(serverClient(env)))32 )33 );3435const LiveAsks = ({ data }: { readonly data: ProjectAsksData }) => {36 const { project } = data;3738 useAtomMount(watchAtom(project));3940 const asksRead = useAtomValue(asksAtom(project));4142 const asks = Option.getOrElse(43 Option.map(AsyncResult.value(asksRead), ({ asks: listed }) => listed),44 () => data.asks45 );4647 const events = Option.getOrElse(48 AsyncResult.value(useAtomValue(projectEventsAtom(project))),49 () => data.events50 );5152 const reads = useMemo(53 () => new Map(events === undefined ? [] : [[project, events]]),54 [events, project]55 );5657 const stamps = useStamps(reads)(project);58 const states = useMemo(() => askStates(events ?? []), [events]);5960 return (61 <ProjectAsksView62 asks={asks}63 now={data.now}64 parents={data.parents}65 project={project}66 stamps={stamps}67 states={states}68 unreachable={AsyncResult.isFailure(asksRead)}69 />70 );71};7273const AsksPage = () => {74 const loaded = Route.useLoaderData();7576 const data = useMemo(77 () => Schema.decodeSync(ProjectAsksData)(loaded),78 [loaded]79 );8081 const { project } = data;8283 const seeds: readonly Seed[] = [84 ...(data.asks === undefined85 ? []86 : [seedSuccess(asksAtom(project), { asks: data.asks })]),87 ...(data.events === undefined88 ? []89 : [seedSuccess(projectEventsAtom(project), data.events)]),90 ];9192 return (93 <SeededAtoms id={`${project}/asks`} seeds={seeds}>94 <LiveAsks data={data} />95 </SeededAtoms>96 );97};9899const Unknown = () => {100 const { project } = Route.useParams();101102 return <UnknownProjectView name={project} />;103};104105export const Route = createFileRoute("/$owner/$project/asks/")({106 staticData: { shell: "project" },107 // TanStack infers each option from the ones before it.108 validateSearch: ({ ask }: { readonly ask?: unknown }) =>109 Predicate.isString(ask) ? { ask } : {},110 loader: ({ params }) => asksPage({ data: params.project }),111 shouldReload: reloadOnEnter,112 headers: () => branchPage,113 head: ({ params: { project } }) =>114 pageHead({115 title: `Asks · ${project}`,116 description: `${project}'s open asks: each one a want with a check, ready to claim.`,117 }),118 component: AsksPage,119 notFoundComponent: Unknown,120});
modified:apps/web/src/routes/$owner/$project/decisions/$decision.tsx+2 added-6 removed
44 unmodified lines
45import {46 marksKey,47 useReadMarks,48} from "../../../../features/finish/read-marks.ts";49import { ProposalFailure } from "../../../../features/proposal/failure.tsx";49import { CallFailure } from "../../../../features/shared/call-failure.tsx";50import { pageHead } from "../../../../features/shared/head.ts";51import { personalPage } from "../../../../server/cache-headers.ts";52import { serverClient } from "../../../../server/client.ts";53
192 unmodified lines
246 const [decided, decide] = useAtom(decideAtom);247 const here = useLocation({ select: hereOf });248249 const failure = AsyncResult.isFailure(decided) ? (250 <ProposalFailure251 cause={decided.cause}252 doing="take this decision"253 here={here}254 />250 <CallFailure cause={decided.cause} doing="take this decision" here={here} />251 ) : undefined;252253 const waiverFiles = useMemo(254 () =>
51 unmodified lines
deleted:apps/web/src/routes/$owner/$project/proposals/$proposal.tsx-184 removed
1import { useAtom, useAtomMount, useAtomValue } from "@effect/atom-react";2import { Client, ShowProposal } from "@repo/protocol/contracts";3import { DecisionSubject } from "@repo/protocol/domain/decision";4import type { Today } from "@repo/protocol/domain/decision";5import type { Proposal } from "@repo/protocol/domain/proposal";6import { ProjectName, ProposalId } from "@repo/protocol/ids";7import type { DecisionId, Handle } from "@repo/protocol/ids";8import { createFileRoute, notFound, useLocation } from "@tanstack/react-router";9import { createServerFn } from "@tanstack/react-start";10import { env } from "cloudflare:workers";11import { Array, DateTime, Effect, Option, Schema } from "effect";12import { AsyncResult } from "effect/reactivity";1314import {15 draftAtom,16 projectTodayAtom,17 proposalAtom,18} from "../../../../client/proposal.ts";19import { SeededAtoms, seedSuccess } from "../../../../client/seeded.ts";20import { watchAtom } from "../../../../client/watch.ts";21import { NotFoundView } from "../../../../features/ask/refused.tsx";22import { hereOf } from "../../../../features/auth/session-slot.tsx";23import { whoAtom } from "../../../../features/auth/who.ts";24import { ProposalFailure } from "../../../../features/proposal/failure.tsx";25import { ProposalView } from "../../../../features/proposal/proposal-view.tsx";26import { pageHead } from "../../../../features/shared/head.ts";27import { notFoundFor, Refusals } from "../../../../features/shared/refusals.ts";28import { personalPage } from "../../../../server/cache-headers.ts";29import { serverClient } from "../../../../server/client.ts";3031type Shown = typeof ShowProposal.successSchema.Type;3233export const readProposal = (name: string, id: string) =>34 Effect.gen(function* () {35 const project = yield* Schema.decodeEffect(ProjectName)(name).pipe(36 Effect.mapError(() => notFound())37 );3839 const proposal = yield* Schema.decodeEffect(ProposalId)(id).pipe(40 Effect.mapError(() => notFound())41 );4243 const client = yield* Client;4445 const shown = yield* client.showProposal({ project, proposal }).pipe(46 Effect.catchTags({47 UnknownProject: notFoundFor,48 UnknownProposal: notFoundFor,49 })50 );5152 return yield* Schema.encodeEffect(ShowProposal.successSchema)(shown);53 });5455const proposalPage = createServerFn({ method: "GET" })56 .validator(57 (params: { readonly project: string; readonly proposal: string }) => params58 )59 .handler(({ data }) =>60 Effect.runPromise(61 readProposal(data.project, data.proposal).pipe(62 Effect.provide(serverClient(env))63 )64 )65 );6667const decisionOn = (68 today: AsyncResult.AsyncResult<Today, unknown>,69 proposal: Proposal70): Option.Option<DecisionId> =>71 Option.flatMap(AsyncResult.value(today), ({ decisions }) =>72 Array.findFirst(73 decisions,74 ({ decided, project, subject }) =>75 decided === undefined &&76 project === proposal.project &&77 DecisionSubject.guards.OpenProposal(subject) &&78 subject.proposal === proposal.id79 ).pipe(Option.map(({ id }) => id))80 );8182const mayRedraftAs = (83 who: AsyncResult.AsyncResult<Option.Option<Handle>, unknown>,84 today: AsyncResult.AsyncResult<Today, unknown>,85 proposal: Proposal86) =>87 AsyncResult.isSuccess(today) ||88 Option.exists(89 Option.flatten(AsyncResult.value(who)),90 (handle) => handle.toLowerCase() === proposal.proposer.toLowerCase()91 );9293const FreshProposal = ({94 project,95 read,96}: {97 readonly project: ProjectName;98 readonly read: Shown;99}) => {100 useAtomMount(watchAtom(project));101102 const { files, proposal } = Option.getOrElse(103 AsyncResult.value(useAtomValue(proposalAtom(project)(read.proposal.id))),104 () => read105 );106107 const here = useLocation({ select: hereOf });108 const who = useAtomValue(whoAtom);109 const today = useAtomValue(projectTodayAtom(project));110 const [redrafted, redraft] = useAtom(draftAtom);111112 return (113 <ProposalView114 busy={redrafted.waiting}115 now={DateTime.nowUnsafe()}116 decision={decisionOn(today, proposal)}117 files={files}118 mayRedraft={mayRedraftAs(who, today, proposal)}119 onRedraft={(note) => {120 redraft(121 note === undefined122 ? { project, proposal: proposal.id }123 : { note, project, proposal: proposal.id }124 );125 }}126 project={project}127 proposal={proposal}128 >129 {AsyncResult.isFailure(redrafted) ? (130 <div aria-live="polite">131 <ProposalFailure132 cause={redrafted.cause}133 doing="draft it again"134 here={here}135 />136 </div>137 ) : null}138 </ProposalView>139 );140};141142const ProposalPage = () => {143 const read = Schema.decodeSync(ShowProposal.successSchema)(144 Route.useLoaderData()145 );146147 const { id, project } = read.proposal;148149 return (150 <SeededAtoms151 id={`${project}/${id}`}152 seeds={[seedSuccess(proposalAtom(project)(id), read)]}153 >154 <FreshProposal project={project} read={read} />155 </SeededAtoms>156 );157};158159const decodeRefusals = Schema.decodeUnknownOption(Refusals);160161const Unknown = ({ data }: { readonly data?: unknown }) => (162 <NotFoundView163 nothing="Nothing is at this address: a project's name is lowercase words joined by single dashes, and a proposal's id reads prop- and six digits."164 refusals={Option.getOrUndefined(decodeRefusals(data))}165 title="No such proposal"166 />167);168169export const Route = createFileRoute("/$owner/$project/proposals/$proposal")({170 staticData: { shell: "project" },171 loader: ({ params }) => proposalPage({ data: params }),172 headers: () => personalPage,173 head: ({ loaderData, params: { project, proposal } }) =>174 pageHead(175 loaderData === undefined176 ? { title: `${proposal} · ${project}` }177 : {178 description: loaderData.proposal.want,179 title: `${proposal} · ${project}`,180 }181 ),182 component: ProposalPage,183 notFoundComponent: Unknown,184});
deleted:apps/web/src/routes/$owner/$project/proposals/new.tsx-126 removed
1import { useAtom, useAtomValue } from "@effect/atom-react";2import { CommitSha, ownerOf, ProjectName, RepoPath } from "@repo/protocol/ids";3import {4 createFileRoute,5 useLocation,6 useNavigate,7} from "@tanstack/react-router";8import { Option, Schema } from "effect";9import { AsyncResult } from "effect/reactivity";10import { useEffect, useState } from "react";1112import {13 modulesAtom,14 proposalMade,15 proposeAtom,16} from "../../../../client/propose.ts";17import { hereOf } from "../../../../features/auth/session-slot.tsx";18import { whoAtom } from "../../../../features/auth/who.ts";19import { UnknownProjectView } from "../../../../features/project/unknown-project.tsx";20import { ProposalFailure } from "../../../../features/proposal/failure.tsx";21import { ProposeView } from "../../../../features/propose/propose-view.tsx";22import type { About } from "../../../../features/propose/propose-view.tsx";23import { pageHead } from "../../../../features/shared/head.ts";2425const decodeProject = Schema.decodeUnknownOption(ProjectName);2627const AboutParts = Schema.Struct({28 about: RepoPath,29 at: CommitSha,30 line: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),31});3233const decodeAbout = Schema.decodeUnknownOption(AboutParts);3435const decodeText = Schema.decodeUnknownOption(Schema.String);3637const decodeLine = Schema.decodeUnknownOption(Schema.Int);3839const aboutOf = (search: {40 readonly about?: string | undefined;41 readonly at?: string | undefined;42 readonly line?: number | undefined;43}): Option.Option<About> =>44 Option.map(decodeAbout(search), ({ about, at, line }) => ({45 at,46 line,47 path: about,48 }));4950const Propose = ({ project }: { readonly project: ProjectName }) => {51 const navigate = useNavigate();52 const search = Route.useSearch();53 const here = useLocation({ select: hereOf });54 const who = useAtomValue(whoAtom);5556 const modules = Option.getOrElse(57 AsyncResult.value(useAtomValue(modulesAtom(project))),58 () => []59 );6061 const [proposed, propose] = useAtom(proposeAtom);62 // Set once this form sends: a proposal the atom still holds from an63 // earlier visit never moves the page.64 const [sent, setSent] = useState(false);6566 const made = sent ? Option.getOrUndefined(proposalMade(proposed)) : undefined;6768 useEffect(() => {69 if (made !== undefined) {70 void navigate({71 params: { owner: ownerOf(project), project, proposal: made },72 to: "/$owner/$project/proposals/$proposal",73 });74 }75 }, [made, navigate, project]);7677 return (78 <ProposeView79 about={aboutOf(search)}80 busy={proposed.waiting}81 checking={!AsyncResult.isSuccess(who)}82 modules={modules}83 onPropose={(payload) => {84 setSent(true);85 propose(payload);86 }}87 project={project}88 signedIn={AsyncResult.isSuccess(who) && Option.isSome(who.value)}89 >90 {AsyncResult.isFailure(proposed) ? (91 <div aria-live="polite">92 <ProposalFailure93 cause={proposed.cause}94 doing="propose it"95 here={here}96 />97 </div>98 ) : null}99 </ProposeView>100 );101};102103const Page = () => {104 const params = Route.useParams();105106 return Option.match(decodeProject(params.project), {107 onNone: () => <UnknownProjectView name={params.project} />,108 onSome: (project) => <Propose project={project} />,109 });110};111112export const Route = createFileRoute("/$owner/$project/proposals/new")({113 staticData: { shell: "focus" },114 component: Page,115 validateSearch: (search: {116 readonly about?: unknown;117 readonly at?: unknown;118 readonly line?: unknown;119 }) => ({120 about: Option.getOrUndefined(decodeText(search.about)),121 at: Option.getOrUndefined(decodeText(search.at)),122 line: Option.getOrUndefined(decodeLine(search.line)),123 }),124 head: ({ params: { project } }) =>125 pageHead({ title: `Propose an ask · ${project}` }),126});
modified:apps/web/src/routes/$owner/$project/index.tsx+1 added-6 removed
15 unmodified lines
16} from "../../../client/project.ts";17import { SeededAtoms, seedSuccess } from "../../../client/seeded.ts";18import type { Seed } from "../../../client/seeded.ts";19import { watchAtom } from "../../../client/watch.ts";20import { useSignedIn } from "../../../features/auth/session-slot.tsx";20import { ledeOf } from "../../../features/front/head.ts";21import {22 markdownAlternateLink,23 markdownLink,
84 unmodified lines
108109const LiveProject = ({110 data,111 platformUrl,113 signedIn,112}: {113 readonly data: ProjectPageData;114 readonly platformUrl: string;117 readonly signedIn: boolean;115}) => {116 const { project } = data;117118 useAtomMount(watchAtom(project));
49 unmodified lines
168 listing={homeListing({ asks, ledger, project })}169 now={data.now}170 parents={data.parents}171 platformUrl={platformUrl}175 signedIn={signedIn}172 stamps={stamps}173 states={states}174 unreachable={AsyncResult.isFailure(asksRead)}175 />
8 unmodified lines
184 [loaded]185 );186187 const { platformUrl } = root.useLoaderData();192 const signedIn = useSignedIn();188 const { project } = data;189190 const seeds: readonly Seed[] = [191 ...(data.asks === undefined
14 unmodified lines
206 ];207208 return (209 <SeededAtoms id={project} seeds={seeds}>215 <LiveProject data={data} platformUrl={platformUrl} signedIn={signedIn} />210 <LiveProject data={data} platformUrl={platformUrl} />211 </SeededAtoms>212 );213};214
35 unmodified lines
modified:apps/web/src/routes/$owner/$project/people.tsx+3 added-122 removed
1import {2 RegistryProvider,3 useAtomMount,4 useAtomValue,5} from "@effect/atom-react";6import { Client } from "@repo/protocol/contracts";7import { PolicyPending, PublicPolicy } from "@repo/protocol/domain/policy";8import { Ledger } from "@repo/protocol/domain/visibility";9import { ProjectName } from "@repo/protocol/ids";10import { createFileRoute, notFound } from "@tanstack/react-router";1import { createFileRoute } from "@tanstack/react-router";11import { createServerFn } from "@tanstack/react-start";12import { env } from "cloudflare:workers";13import { Effect, Option, Schema, Struct } from "effect";14import { AsyncResult, Atom } from "effect/reactivity";216import { ledgerAtom } from "../../../client/ledger.ts";17import { policyAtom } from "../../../client/policy.ts";18import { watchAtom } from "../../../client/watch.ts";19import { PeopleView } from "../../../features/project-people/people-view.tsx";20import { UnknownProjectView } from "../../../features/project/unknown-project.tsx";21import { pageHead } from "../../../features/shared/head.ts";22import { branchPage } from "../../../server/cache-headers.ts";23import { serverClient } from "../../../server/client.ts";3import { movedToPolicy } from "../../../features/project-people/moved.ts";425// The project's policy page, at the address it has always had.2627const PeoplePageData = Schema.Struct({28 ledger: Ledger,29 policy: Schema.optionalKey(PublicPolicy),30 unevaluated: Schema.optionalKey(PolicyPending),31});3233type PeoplePageData = typeof PeoplePageData.Type;3435export const readPeople = (name: string) =>36 Effect.gen(function* () {37 const project = yield* Schema.decodeEffect(ProjectName)(name).pipe(38 Effect.mapError(() => notFound())39 );4041 const client = yield* Client;4243 const [read, ledger] = yield* Effect.all(44 [client.projectPolicy({ project }), client.ledger({ project })],45 { concurrency: 2 }46 ).pipe(Effect.catchTag("UnknownProject", () => Effect.fail(notFound())));4748 return yield* Schema.encodeEffect(PeoplePageData)({ ...read, ledger });49 });5051const peoplePage = createServerFn({ method: "GET" })52 .validator((name: string) => name)53 .handler(({ data }) =>54 Effect.runPromise(readPeople(data).pipe(Effect.provide(serverClient(env))))55 );5657const FreshPeople = ({58 project,59 read,60}: {61 readonly project: ProjectName;62 readonly read: PeoplePageData;63}) => {64 useAtomMount(watchAtom(project));6566 const { policy, unevaluated } = Option.getOrElse(67 AsyncResult.value(useAtomValue(policyAtom(project))),68 () => read69 );7071 const ledger = Option.getOrElse(72 AsyncResult.value(useAtomValue(ledgerAtom(project))),73 () => read.ledger74 );7576 return (77 <PeopleView78 ledger={ledger}79 policy={Option.fromUndefinedOr(policy)}80 project={project}81 unevaluated={Option.fromUndefinedOr(unevaluated)}82 />83 );84};8586const PeoplePage = () => {87 const read = Schema.decodeSync(PeoplePageData)(Route.useLoaderData());88 const { project } = read.ledger;8990 return (91 <RegistryProvider92 initialValues={[93 Atom.initialValue(94 policyAtom(project),95 AsyncResult.success(Struct.pick(read, ["policy", "unevaluated"]))96 ),97 Atom.initialValue(98 ledgerAtom(project),99 AsyncResult.success(read.ledger)100 ),101 ]}102 key={project}103 >104 <FreshPeople project={project} read={read} />105 </RegistryProvider>106 );107};108109const Unknown = () => {110 const { project } = Route.useParams();111112 return <UnknownProjectView name={project} />;113};1145export const Route = createFileRoute("/$owner/$project/people")({116 staticData: { shell: "project" },117 loader: ({ params }) => peoplePage({ data: params.project }),118 headers: () => branchPage,119 head: ({ params: { project } }) =>120 pageHead({121 title: `Policy · ${project}`,122 description: `${project}'s maintainers and limits.`,123 }),124 component: PeoplePage,125 notFoundComponent: Unknown,6 beforeLoad: movedToPolicy,7});
added:apps/web/src/routes/$owner/$project/policy.tsx+126 added
1import {2 RegistryProvider,3 useAtomMount,4 useAtomValue,5} from "@effect/atom-react";6import { Client } from "@repo/protocol/contracts";7import { PolicyPending, PublicPolicy } from "@repo/protocol/domain/policy";8import { Ledger } from "@repo/protocol/domain/visibility";9import { ProjectName } from "@repo/protocol/ids";10import { createFileRoute, notFound } from "@tanstack/react-router";11import { createServerFn } from "@tanstack/react-start";12import { env } from "cloudflare:workers";13import { Effect, Option, Schema, Struct } from "effect";14import { AsyncResult, Atom } from "effect/reactivity";1516import { ledgerAtom } from "../../../client/ledger.ts";17import { policyAtom } from "../../../client/policy.ts";18import { watchAtom } from "../../../client/watch.ts";19import { PeopleView } from "../../../features/project-people/people-view.tsx";20import { UnknownProjectView } from "../../../features/project/unknown-project.tsx";21import { pageHead } from "../../../features/shared/head.ts";22import { branchPage } from "../../../server/cache-headers.ts";23import { serverClient } from "../../../server/client.ts";2425// The project's policy page; it was `/people` until the People tab folded into it.2627const PeoplePageData = Schema.Struct({28 ledger: Ledger,29 policy: Schema.optionalKey(PublicPolicy),30 unevaluated: Schema.optionalKey(PolicyPending),31});3233type PeoplePageData = typeof PeoplePageData.Type;3435export const readPeople = (name: string) =>36 Effect.gen(function* () {37 const project = yield* Schema.decodeEffect(ProjectName)(name).pipe(38 Effect.mapError(() => notFound())39 );4041 const client = yield* Client;4243 const [read, ledger] = yield* Effect.all(44 [client.projectPolicy({ project }), client.ledger({ project })],45 { concurrency: 2 }46 ).pipe(Effect.catchTag("UnknownProject", () => Effect.fail(notFound())));4748 return yield* Schema.encodeEffect(PeoplePageData)({ ...read, ledger });49 });5051const peoplePage = createServerFn({ method: "GET" })52 .validator((name: string) => name)53 .handler(({ data }) =>54 Effect.runPromise(readPeople(data).pipe(Effect.provide(serverClient(env))))55 );5657const FreshPeople = ({58 project,59 read,60}: {61 readonly project: ProjectName;62 readonly read: PeoplePageData;63}) => {64 useAtomMount(watchAtom(project));6566 const { policy, unevaluated } = Option.getOrElse(67 AsyncResult.value(useAtomValue(policyAtom(project))),68 () => read69 );7071 const ledger = Option.getOrElse(72 AsyncResult.value(useAtomValue(ledgerAtom(project))),73 () => read.ledger74 );7576 return (77 <PeopleView78 ledger={ledger}79 policy={Option.fromUndefinedOr(policy)}80 project={project}81 unevaluated={Option.fromUndefinedOr(unevaluated)}82 />83 );84};8586const PeoplePage = () => {87 const read = Schema.decodeSync(PeoplePageData)(Route.useLoaderData());88 const { project } = read.ledger;8990 return (91 <RegistryProvider92 initialValues={[93 Atom.initialValue(94 policyAtom(project),95 AsyncResult.success(Struct.pick(read, ["policy", "unevaluated"]))96 ),97 Atom.initialValue(98 ledgerAtom(project),99 AsyncResult.success(read.ledger)100 ),101 ]}102 key={project}103 >104 <FreshPeople project={project} read={read} />105 </RegistryProvider>106 );107};108109const Unknown = () => {110 const { project } = Route.useParams();111112 return <UnknownProjectView name={project} />;113};114115export const Route = createFileRoute("/$owner/$project/policy")({116 staticData: { shell: "project" },117 loader: ({ params }) => peoplePage({ data: params.project }),118 headers: () => branchPage,119 head: ({ params: { project } }) =>120 pageHead({121 title: `Policy · ${project}`,122 description: `${project}'s maintainers and limits.`,123 }),124 component: PeoplePage,125 notFoundComponent: Unknown,126});
modified:apps/web/src/routes/$owner/$project/route.tsx+3 added-7 removed
52 unmodified lines
5354const decodeHeader = Schema.decodeSync(ProjectHeaderData);5556/**57 * The layout reads the header for every page drawn under it, but Overview,58 * which reads its header with its own reads, and a focused page (a new59 * proposal), which draws none.57 * The layout reads the header for every page drawn under it but Overview,58 * which reads its header with its own reads.59 */60export const headerLoader =61 (62 read: (
63 unmodified lines
126127 // The current tab and the title's element follow the path alone: a fragment never reaches the server.128 const pathname = useLocation({ select: (location) => location.pathname });129131 // A focused page under a project (a new proposal) draws no project frame.130 // A page under a project that names another shell draws no project frame.131 if (shell !== "project") {132 return <Outlet />;133 }134
17 unmodified lines
152153/**154 * How long the header's facts stand before a move between the project's pages155 * reads them again: without it the router reads the six facts on every move.157 * A reader who enters at a page with no header of its own (a new proposal)158 * and moves to a tab within this time sees the frame without a header until159 * the next read.156 */157export const HEADER_STALE_MS = 60_000;158159// One header for every page of a project, and the page's side column (`staticData.column`) under it, so both
8 unmodified lines
modified:apps/web/src/server/addresses.ts+17 added-5 removed
9 unmodified lines
10import { Option, Schema } from "effect";1112import {13 INBOX_PATH,14 MOVED_TO_POLICY,15 MOVED_TO_VISIBILITY,16 policyHref,17 segmentsOf,18 visibilityHref,19} from "../features/shared/paths.ts";20import { KEPT_NOWHERE } from "./edge-cache.ts";
105 unmodified lines
126 movedTo(to + search)127 );128};129128// A project's old ledger and env pages folded into its Visibility tab (ADR 0041): one move from an old or miscased name too.130// A project's old ledger and env pages folded into its Visibility tab (ADR 0041), and its old `/people` is its policy131// page: one move from an old or miscased name too.132const movedProjectHref = (133 name: string,134 page: string,135 search: string136): Option.Option<string> =>137 page === MOVED_TO_POLICY138 ? Option.some(policyHref(name, search))139 : Option.map(140 Option.fromUndefinedOr(MOVED_TO_VISIBILITY.get(page)),141 (anchor) => visibilityHref(name, anchor, search)142 );143144const movedProjectPage = (145 name: string,146 rest: readonly string[],147 search: string
1 unmodified line
149 const [page, ...below] = rest;150151 return page === undefined || below.length > 0152 ? Option.none()138 : Option.map(139 Option.fromUndefinedOr(MOVED_TO_VISIBILITY.get(page)),140 (anchor) => movedTo(visibilityHref(name, anchor, search))141 );153 : Option.map(movedProjectHref(name, page, search), movedTo);154};155156export const canonicalAddress = (request: Request): Option.Option<Response> => {157 const url = new URL(request.url);
49 unmodified lines
modified:apps/web/src/server/project-page.ts+62 added-9 removed
156 unmodified lines
157};158159const AT_ONCE = 4;160161const parentsOf = (162 client: Client["Service"],163 project: ProjectName,164 asks: readonly AskListing[]165) =>166 Effect.forEach(167 familiesIn(asks),168 ({ parent }) =>169 client.showAsk({ ask: parent, project }).pipe(170 Effect.map((shown) => Option.some(shown.ask)),171 Effect.orElseSucceed(() => Option.none<Ask>())172 ),173 { concurrency: AT_ONCE }174 ).pipe(Effect.map(Arr.getSomes));175176export const readProjectPage = (name: string) =>177 Effect.gen(function* () {178 const project = yield* Effect.fromOption(decodeName(name));179 const client = yield* Client;
9 unmodified lines
189 );190191 const asks = Option.map(read.asks, (listed) => listed.asks);192178 const parents = yield* Effect.forEach(179 familiesIn(Option.getOrElse(asks, () => [])),180 ({ parent }) =>181 client.showAsk({ ask: parent, project }).pipe(182 Effect.map((shown) => Option.some(shown.ask)),183 Effect.orElseSucceed(() => Option.none<Ask>())184 ),185 { concurrency: AT_ONCE }193 const parents = yield* parentsOf(194 client,195 project,196 Option.getOrElse(asks, () => [])197 );198199 const now = yield* DateTime.now;200
10 unmodified lines
211 ...onlySome(read.events, (events) => ({ events })),212 ...onlySome(read.ledger, (ledger) => ({ ledger })),213 header: headerOf(project, now, read),214 now,204 parents: Arr.getSomes(parents),215 parents,216 project,217 }).pipe(Effect.orDie);218 }).pipe(Effect.catchTag("NoSuchElementError", () => Effect.fail(notFound())));219220/** The Asks tab: the project's open asks, its events for each ask's progress, and each family's parent. */221export const ProjectAsksData = Schema.Struct({222 asks: Schema.optionalKey(Schema.Array(AskListing)),223 events: Schema.optionalKey(Schema.Array(ProjectEvent)),224 now: Schema.DateTimeUtcFromString,225 parents: Schema.Array(Ask),226 project: ProjectName,227});228229export type ProjectAsksData = typeof ProjectAsksData.Type;230231export const readProjectAsks = (name: string) =>232 Effect.gen(function* () {233 const project = yield* Effect.fromOption(decodeName(name));234 const client = yield* Client;235236 const read = yield* Effect.all(237 {238 asks: optional(client.listAsks({ project })),239 events: optional(240 Stream.runCollect(client.watch({ project, since: 0 }))241 ),242 },243 { concurrency: "unbounded" }244 );245246 const asks = Option.map(read.asks, (listed) => listed.asks);247248 // What the platform sent decoded, so it encodes; a failure is a defect.249 return yield* Schema.encodeEffect(ProjectAsksData)({250 ...onlySome(asks, (listed) => ({ asks: listed })),251 ...onlySome(read.events, (events) => ({ events })),252 now: yield* DateTime.now,253 parents: yield* parentsOf(254 client,255 project,256 Option.getOrElse(asks, () => [])257 ),258 project,259 }).pipe(Effect.orDie);260 }).pipe(Effect.catchTag("NoSuchElementError", () => Effect.fail(notFound())));261262/**263 * The header alone, for a page whose own loader does not read it: every264 * read at once and none waiting on another, beside the page's own reads.265 */
36 unmodified lines
modified:apps/web/test/client-today.test.ts+12 added-12 removed
46 unmodified lines
47 ).toStrictEqual({48 decider: "ines-v",49 newcomers: ["bram"],50 projects: ["oscabriel/datekit"],51 subjects: ["OpenProposal", "OpenProposal", "OpenProposal", "StrayPush"],51 subjects: ["StrayPush"],52 unattended: ["diff-in-days-dst"],53 });54 })55 );5657 // The page's atoms live in a registry of the page's own (`SeededAtoms`),58 // the rail's in the root's: a decision taken on the page refetches both.59 it.live(60 "closes a decision the maintainer declines, and Today refetches without it, on the page and in the rail",60 "closes a decision the maintainer takes, and Today refetches without it, on the page and in the rail",61 () =>62 Effect.gen(function* () {63 const registry = registryAs(DECIDER);64 const rail = registryAs(DECIDER);
2 unmodified lines
67 const before = yield* settled(registry, todayAtom);68 // Read in the rail before the decision, so a refetch is what changes it.69 yield* settled(rail, todayAtom);7071 const proposal = Exit.isSuccess(before)71 const stray = Exit.isSuccess(before)72 ? before.value.decisions.find(({ subject }) =>73 DecisionSubject.guards.OpenProposal(subject)73 DecisionSubject.guards.StrayPush(subject)74 )75 : undefined;7677 expect(proposal).toBeDefined();77 expect(stray).toBeDefined();7879 if (proposal === undefined) {79 if (stray === undefined) {80 return;81 }8283 const decide = ContractsClient.mutation("decide");8485 registry.set(decide, {86 payload: {87 choice: "decline",88 decision: proposal.id,89 project: proposal.project,87 choice: "adopt",88 decision: stray.id,89 project: stray.project,90 },91 reactivityKeys: [...keys.today(), ...keys.project(proposal.project)],91 reactivityKeys: [...keys.today(), ...keys.project(stray.project)],92 });9394 const decided = yield* settled(registry, decide);9596 const taken = Exit.isSuccess(decided)97 ? decided.value.decision.decided98 : undefined;99100 expect(taken?.choice).toBe("decline");100 expect(taken?.choice).toBe("adopt");101 expect(102 taken === undefined ? undefined : DateTime.formatIso(taken.at)103 ).toBe("2026-10-07T09:27:00.000Z");104
1 unmodified line
106 Effect.map(settled(where, todayAtom), (today) =>107 Exit.isSuccess(today)108 ? {109 holds: today.value.decisions.some(110 ({ id }) => id === proposal.id110 ({ id }) => id === stray.id111 ),112 }113 : undefined114 );
14 unmodified lines
modified:apps/web/test/decision.test.tsx+3 added-200 removed
2 unmodified lines
3import { Contracts } from "@repo/protocol/contracts";4import { RefNameText } from "@repo/protocol/domain/common";5import { DecisionSubject } from "@repo/protocol/domain/decision";6import type { Choice, Decision, Today } from "@repo/protocol/domain/decision";7import { DraftState } from "@repo/protocol/domain/proposal";7import {8 AskId,9 CommitSha,10 DecisionId,11 Handle,13 LaneName,12 ProjectName,15 ProposalId,13 RepoPath,14} from "@repo/protocol/ids";15import { DecisionClosed } from "@repo/protocol/refusal";16import type { UnknownDecision } from "@repo/protocol/refusal";
6 unmodified lines
2324import { decideAtom } from "../src/client/decide.ts";25import { keys } from "../src/client/keys.ts";26import { todayAtom } from "../src/client/today.ts";30import { DecisionCard } from "../src/features/decision/decision-card.tsx";27import {28 DecisionRead,29 DecisionView,30} from "../src/features/decision/decision-page.tsx";
1 unmodified line
32import { patchFiles } from "../src/features/finish/files.ts";33import { waiverPatchOf } from "../src/features/finish/patch.ts";34import { InboxView } from "../src/features/inbox/inbox-page.tsx";35import { Decisions, InboxRead, Takeable } from "../src/features/inbox/read.ts";40import { ProposalFailure } from "../src/features/proposal/failure.tsx";41import {42 DraftRead,43 draftReadOf,44 readDraft,45} from "../src/features/proposal/live-draft.ts";36import { CallFailure } from "../src/features/shared/call-failure.tsx";37import { RefusalView } from "../src/features/shared/refusal.tsx";38import { ContractsClient, webContracts } from "../src/surfaces.ts";3940const markupOf = (element: ReactElement) => renderToStaticMarkup(element);
251 unmodified lines
292 })293 );294});295305const acceptOf = (markup: string) =>306 /<button[^>]*data-choice="accept"[^>]*>/u.exec(markup)?.[0] ?? "";307308describe("DecisionCard for an OpenProposal", () => {309 const askFile = `${Brand.configDir}/asks/x.ask.ts`;310311 const proposal = ProposalId.make("prop-000007");312313 const opening: Decision = {314 deciders: [okonkwo],315 default: "decline",316 evidence: [317 { label: "want", value: "formatISO keeps the offset it was given." },318 {319 label: askFile,320 value: 'export default ask({ id: "x", kind: kinds.fix });\n',321 },322 { label: "red first", value: "unit: expected '+02:00', got 'Z'" },323 ],324 expiresAt: DateTime.makeUnsafe("2026-10-08T10:00:00Z"),325 id: DecisionId.make("dec-000003"),326 openedAt: DateTime.makeUnsafe("2026-10-06T10:00:00Z"),327 project: datekit,328 subject: DecisionSubject.cases.OpenProposal.make({ proposal }),329 };330331 const card = (draft: DraftState) =>332 markupOf(333 <DecisionCard334 decision={opening}335 draft={readDraft(draft)}336 now={now}337 onDecide={() => {}}338 />339 );340341 const shown = (draft?: DraftState) => {342 const wanted = {343 expiresAt: opening.expiresAt,344 files: [],345 id: proposal,346 openedAt: opening.openedAt,347 project: datekit,348 proposer: Handle.make("lin-h"),349 state: "open" as const,350 want: "formatISO keeps the offset it was given.",351 };352353 return {354 files: [],355 proposal: draft === undefined ? wanted : { ...wanted, draft },356 };357 };358359 const cardRead = (draft?: DraftState) =>360 markupOf(361 <DecisionCard362 decision={opening}363 draft={draftReadOf(AsyncResult.success(shown(draft)))}364 now={now}365 onDecide={() => {}}366 />367 );368369 const drafting = DraftState.cases.Drafting.make({370 round: 2,371 startedAt: now,372 });373374 const ready = DraftState.cases.Ready.make({375 attempts: 1,376 model: "@cf/moonshotai/kimi-k2.7-code",377 red: { lane: LaneName.make("unit"), signature: "expected '+02:00'" },378 round: 1,379 });380381 const failed = DraftState.cases.Failed.make({382 attempts: 3,383 model: "@cf/moonshotai/kimi-k2.7-code",384 refusal: "NotRedFirst",385 round: 2,386 });387388 it("shows a file's path as a heading and its content in a pre", () => {389 const markup = card(ready);390391 expect(markup).toMatch(new RegExp(`<h4[^>]*>${askFile}</h4>`, "u"));392 expect(markup).toMatch(393 /<pre[^>]*>export default ask\(\{ id: &quot;x&quot;, kind: kinds\.fix \}\);\n<\/pre>/u394 );395 expect(markup).not.toMatch(new RegExp(`<dt[^>]*>${askFile}</dt>`, "u"));396 expect(markup).toMatch(/<dt[^>]*>red first<\/dt>/u);397 });398399 it("holds Accept while the proposal's draft is drafting", () => {400 const markup = card(drafting);401402 expect(acceptOf(markup)).toContain('disabled=""');403 expect(markup).toContain("Drafting…");404 expect(405 /<button[^>]*data-choice="decline"[^>]*>/u.exec(markup)?.[0]406 ).not.toContain('disabled=""');407 });408409 it("holds Accept on the server, until the browser has read the draft", () => {410 const markup = markupOf(411 <DecisionCard decision={opening} now={now} onDecide={() => {}} />412 );413414 expect(acceptOf(markup)).toContain('disabled=""');415 expect(markup).toContain("Reading the draft…");416 expect(draftReadOf(AsyncResult.initial(true))).toStrictEqual(417 DraftRead.Unread({ failed: false })418 );419 });420421 it("holds Accept, without a spinner, when the browser could not read the draft", () => {422 const read = draftReadOf(AsyncResult.failure(Cause.fail("offline")));423424 const markup = markupOf(425 <DecisionCard426 decision={opening}427 draft={read}428 now={now}429 onDecide={() => {}}430 />431 );432433 expect(read).toStrictEqual(DraftRead.Unread({ failed: true }));434 expect(acceptOf(markup)).toContain('disabled=""');435 expect(markup).toContain("Draft not read; reload");436 expect(markup).not.toContain("Reading the draft…");437 expect(438 /<button[^>]*data-choice="accept"[^>]*>.*?<\/button>/u.exec(markup)?.[0]439 ).not.toContain('data-slot="spinner"');440 });441442 it("offers Accept once the read draft is ready, failed (an earlier ready draft or the want alone), or the proposal is a want alone", () => {443 for (const markup of [cardRead(ready), cardRead(failed), cardRead()]) {444 expect(acceptOf(markup)).not.toContain('disabled=""');445 expect(markup).not.toContain("Reading the draft…");446 expect(markup).not.toContain("Drafting…");447 }448 });449450 it("holds Accept, saying why, while the read draft is drafting", () => {451 const markup = cardRead(drafting);452453 expect(acceptOf(markup)).toContain('disabled=""');454 expect(markup).toContain("Drafting…");455 expect(markup).not.toContain("Reading the draft…");456 });457458 it("offers Accept once the draft is ready", () => {459 const markup = card(ready);460461 expect(acceptOf(markup)).not.toContain('disabled=""');462 expect(markup).not.toContain("Drafting…");463 });464465 it("shows a check at the repo's root as code too", () => {466 const markup = markupOf(467 <DecisionCard468 decision={{469 ...opening,470 evidence: [471 ...opening.evidence,472 { label: "offset.test.ts", value: "test('keeps +02:00');\n" },473 ],474 }}475 draft={readDraft(ready)}476 now={now}477 onDecide={() => {}}478 />479 );480481 expect(markup).toMatch(/<h4[^>]*>offset\.test\.ts<\/h4>/u);482 expect(markup).not.toMatch(/<dt[^>]*>offset\.test\.ts<\/dt>/u);483 expect(markup).toMatch(/<dt[^>]*>want<\/dt>/u);484 });485486 it("links the proposal's page", () => {487 expect(card(ready)).toContain(488 'href="/oscabriel/datekit/proposals/prop-000007"'489 );490 });491});492296const vellum = ProjectName.make("oscabriel/vellum");297298const waiver: Decision = {299 deciders: [okonkwo],
144 unmodified lines
444445 const markup = pageOf(446 found,447 undefined,645 <ProposalFailure448 <CallFailure449 cause={Cause.fail(closed)}450 doing="take this decision"451 here="/oscabriel/vellum/decisions/dec-000002"452 />
11 unmodified lines
464465 expect(markup).not.toContain("data-choice=");466 expect(markup).not.toContain(".skip(");467 expect(text).toContain("A maintainer takes it on their Today");665 expect(markup).toContain('href="/oscabriel/vellum/people"');468 expect(markup).toContain('href="/oscabriel/vellum/policy"');469 expect(text).toContain(`${Brand.cli} today --project oscabriel/vellum`);470 });471});
modified:apps/web/test/dev-backend.test.ts+21 added-54 removed
1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";2import { Client, Contracts } from "@repo/protocol/contracts";3import { forkRev } from "@repo/protocol/domain/code";5import { DecisionSubject } from "@repo/protocol/domain/decision";4import { ProjectEvent } from "@repo/protocol/domain/event";5import { Handle, ProjectName } from "@repo/protocol/ids";6import { Unauthenticated } from "@repo/protocol/principal";7import {
505 unmodified lines
513 })514 );515});516519const drafted = inFreshWorld((as) =>517const discussed = inFreshWorld((as) =>518 Effect.gen(function* () {519 const anyone = yield* clientOf(as());522 const ines = yield* clientOf(as(decider));523 const bram = yield* clientOf(as(contributor));520 const project = ProjectName.make("oscabriel/datekit");525 const before = yield* ines.today({ project });521 const { discussions } = yield* anyone.listDiscussions({ project });522527 const { proposal } = yield* bram.proposeAsk({528 draft: true,529 project,530 want: "datekit reads ordinal dates such as 2026-280.",531 });532533 const shown = yield* anyone.showProposal({534 project,535 proposal: proposal.id,536 });537538 return {539 after: yield* ines.today({ project }),540 before,541 proposed: proposal,542 shown,543 };523 return discussions.map(({ ask, state, title }) => ({ ask, state, title }));524 })525);526547describe("a draft in the dev world", seededWorlds, () => {527describe("the dev world's discussions", seededWorlds, () => {528 it.live(549 "is drafted as it is proposed, red first on the scripted Checker, and its decision joins the maintainer's Today",529 "hold a thread a maintainer opened an ask from, and one still open",530 () =>531 Effect.gen(function* () {552 const { after, before, proposed, shown } = yield* drafted;553554 // Today holds every open decision, so the draft's joins the seeded ones.555 const joined = after.decisions.filter(556 ({ id }) => !before.decisions.some((was) => was.id === id)557 );558559 expect({560 files: shown.files.map(({ path }) => path),561 joined: joined.map(({ subject }) => subject),562 kept: before.decisions.every(({ id }) =>563 after.decisions.some((now) => now.id === id)564 ),565 proposed: proposed.draft?._tag,566 ready: shown.proposal.draft?._tag,567 }).toStrictEqual({568 files: [569 `${Brand.configDir}/asks/parse-ordinal.ask.ts`,570 "test/asks/parse-ordinal.test.ts",571 ],572 joined: [573 DecisionSubject.cases.OpenProposal.make({574 proposal: proposed.id,575 }),576 ],577 kept: true,578 proposed: "Drafting",579 ready: "Ready",580 });532 expect(533 (yield* discussed).toSorted((one, other) =>534 one.title.localeCompare(other.title)535 )536 ).toStrictEqual([537 {538 ask: "parse-iso-week",539 state: "asked",540 title: "ISO week dates",541 },542 {543 ask: undefined,544 state: "open",545 title: "Which day starts a week?",546 },547 ]);548 })549 );550});
modified:apps/web/test/dev-fixtures.test.tsnot shown

Its text is not shown, modified.

modified:apps/web/test/discussions.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/finish.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/import.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/nav.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/pierre.test.tsnot shown

Its text is not shown, modified.

modified:apps/web/test/project-people.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/project.test.tsxnot shown

Its text is not shown, modified.

deleted:apps/web/test/proposal.test.tsxnot shown

Its text is not shown, deleted.

deleted:apps/web/test/propose.test.tsxnot shown

Its text is not shown, deleted.

modified:apps/web/test/shared.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/status-line.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/today.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/watch.test.tsnot shown

Its text is not shown, modified.

modified:apps/web/test/why.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/package.json-1 removed
51 unmodified lines
52 "@playwright/test": "1.63.0",53 "@repo/artifacts": "workspace:*",54 "@repo/checks": "workspace:*",55 "@repo/config": "workspace:*",56 "@repo/drafting": "workspace:*",56 "@repo/project": "workspace:*",57 "@repo/rules": "workspace:*",58 "@repo/testkit": "workspace:*",59 "@tailwindcss/typography": "0.5.20",
13 unmodified lines
modified:examples/datekit/.myr/vouched.tdnot shown

Its text is not shown, modified.

modified:examples/datekit/layers/maintainers/.myr/layer.jsonnot shown

Its text is not shown, modified.

modified:examples/datekit/layers/maintainers/.myr/layer.tsnot shown

Its text is not shown, modified.

modified:examples/datekit/README.mdnot shown

Its text is not shown, modified.

modified:packages/agent-kit/src/docs/run-a-project.tsnot shown

Its text is not shown, modified.

modified:packages/agent-kit/src/docs/start-here.tsnot shown

Its text is not shown, modified.

modified:packages/agent-kit/src/agent-setup.tsnot shown

Its text is not shown, modified.

modified:packages/agent-kit/src/command-doc.tsnot shown

Its text is not shown, modified.

modified:packages/agent-kit/src/install-channels.tsnot shown

Its text is not shown, modified.

modified:packages/agent-kit/src/llms-sections.tsnot shown

Its text is not shown, modified.

modified:packages/agent-kit/src/refusals.tsnot shown

Its text is not shown, modified.

modified:packages/agent-kit/test/golden/agent-plugins-stdio.txtnot shown

Its text is not shown, modified.

modified:packages/agent-kit/test/golden/agent-plugins.txtnot shown

Its text is not shown, modified.

modified:packages/agent-kit/test/golden/agent-setup.txtnot shown

Its text is not shown, modified.

modified:packages/agent-kit/test/golden/claude-plugin-stdio.txtnot shown

Its text is not shown, modified.

modified:packages/agent-kit/test/golden/claude-plugin.txtnot shown

Its text is not shown, modified.

modified:packages/agent-kit/test/golden/full-llms.txtnot shown

Its text is not shown, modified.

modified:packages/agent-kit/test/golden/platform-skill.txtnot shown

Its text is not shown, modified.

modified:packages/agent-kit/test/golden/project-skill.txtnot shown

Its text is not shown, modified.

modified:packages/agent-kit/test/agent-setup.test.tsnot shown

Its text is not shown, modified.

modified:packages/agent-kit/test/command-doc.test.tsnot shown

Its text is not shown, modified.

modified:packages/agent-kit/test/docs.test.tsnot shown

Its text is not shown, modified.

modified:packages/agent-kit/test/fixtures.tsnot shown

Its text is not shown, modified.

modified:packages/agent-kit/test/full-llms.test.tsnot shown

Its text is not shown, modified.

modified:packages/config/test/docs-public.test.tsnot shown

Its text is not shown, modified.

modified:packages/config/test/smoke-loop.test.tsnot shown

Its text is not shown, modified.

deleted:packages/drafting/src/draft-runs/canned.tsnot shown

Its text is not shown, deleted.

deleted:packages/drafting/src/draft-runs/inline.tsnot shown

Its text is not shown, deleted.

deleted:packages/drafting/src/drafter/binding.tsnot shown

Its text is not shown, deleted.

deleted:packages/drafting/src/drafter/memory.tsnot shown

Its text is not shown, deleted.

deleted:packages/drafting/src/context.tsnot shown

Its text is not shown, deleted.

deleted:packages/drafting/src/drafted.tsnot shown

Its text is not shown, deleted.

deleted:packages/drafting/src/drafter.tsnot shown

Its text is not shown, deleted.

deleted:packages/drafting/src/prompt.tsnot shown

Its text is not shown, deleted.

deleted:packages/drafting/src/render.tsnot shown

Its text is not shown, deleted.

deleted:packages/drafting/src/run.tsnot shown

Its text is not shown, deleted.

deleted:packages/drafting/test/binding.test.tsnot shown

Its text is not shown, deleted.

deleted:packages/drafting/test/context.test.tsnot shown

Its text is not shown, deleted.

deleted:packages/drafting/test/memory.test.tsnot shown

Its text is not shown, deleted.

deleted:packages/drafting/test/prompt.test.tsnot shown

Its text is not shown, deleted.

deleted:packages/drafting/test/render.test.tsnot shown

Its text is not shown, deleted.

deleted:packages/drafting/test/run.test.tsnot shown

Its text is not shown, deleted.

deleted:packages/drafting/package.jsonnot shown

Its text is not shown, deleted.

deleted:packages/drafting/tsconfig.jsonnot shown

Its text is not shown, deleted.

deleted:packages/drafting/vitest.config.tsnot shown

Its text is not shown, deleted.

modified:packages/gate/src/stages/parse.tsnot shown

Its text is not shown, modified.

modified:packages/gate/test/facts.tsnot shown

Its text is not shown, modified.

modified:packages/git/test/gateway.test.tsnot shown

Its text is not shown, modified.

modified:packages/project/src/attention/decisions.tsnot shown

Its text is not shown, modified.

modified:packages/project/src/attention/discussions.tsnot shown

Its text is not shown, modified.

modified:packages/project/src/attention/effects.tsnot shown

Its text is not shown, modified.

deleted:packages/project/src/attention/promote.tsnot shown

Its text is not shown, deleted.

deleted:packages/project/src/attention/proposals.tsnot shown

Its text is not shown, deleted.

modified:packages/project/src/attention/vouch.tsnot shown

Its text is not shown, modified.

modified:packages/project/src/metrics/binding.tsnot shown

Its text is not shown, modified.

modified:packages/project/src/project-store/memory.tsnot shown

Its text is not shown, modified.

modified:packages/project/src/project-store/migrations.tsnot shown

Its text is not shown, modified.

modified:packages/project/src/project-store/rows.tsnot shown

Its text is not shown, modified.

modified:packages/project/src/project-store/sqlite.tsnot shown

Its text is not shown, modified.

modified:packages/project/src/project-store/tables.tsnot shown

Its text is not shown, modified.

modified:packages/project/src/projection-d1/projection.tsnot shown

Its text is not shown, modified.

modified:packages/project/src/deciders.tsnot shown

Its text is not shown, modified.

deleted:packages/project/src/draft-runs.tsnot shown

Its text is not shown, deleted.

modified:packages/project/src/metrics.tsnot shown

Its text is not shown, modified.

modified:packages/project/src/outbox.tsnot shown

Its text is not shown, modified.

modified:packages/project/src/project-store.tsnot shown

Its text is not shown, modified.

modified:packages/project/src/project.tsnot shown

Its text is not shown, modified.

modified:packages/project/test/attention/decisions.test.tsnot shown

Its text is not shown, modified.

deleted:packages/project/test/attention/promote.test.tsnot shown

Its text is not shown, deleted.

deleted:packages/project/test/attention/proposals.test.tsnot shown

Its text is not shown, deleted.

modified:packages/project/test/attention/vouch.test.tsnot shown

Its text is not shown, modified.

modified:packages/project/test/deciders.test.tsnot shown

Its text is not shown, modified.

modified:packages/project/test/discussions.test.tsnot shown

Its text is not shown, modified.

deleted:packages/project/test/draft-settle.test.tsnot shown

Its text is not shown, deleted.

deleted:packages/project/test/drafting.model.test.tsnot shown

Its text is not shown, deleted.

modified:packages/project/test/metrics.test.tsnot shown

Its text is not shown, modified.

modified:packages/project/test/project-store-sqlite.test.tsnot shown

Its text is not shown, modified.

modified:packages/project/test/project-store.contract.tsnot shown

Its text is not shown, modified.

deleted:packages/project/test/rehearse.test.tsnot shown

Its text is not shown, deleted.

modified:packages/protocol/src/domain/decision.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/discussion.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/event.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/policy.tsnot shown

Its text is not shown, modified.

deleted:packages/protocol/src/domain/proposal.tsnot shown

Its text is not shown, deleted.

modified:packages/protocol/src/cli.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/contracts.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/exit-code.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/ids.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/refusal.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/render.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/testing.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/fixtures/contracts.jsonnot shown

Its text is not shown, modified.

modified:packages/protocol/test/fixtures/domain.jsonnot shown

Its text is not shown, modified.

modified:packages/protocol/test/cli.test.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/contracts.test.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/domain.test.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/examples.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/exit-code.test.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/field-descriptions.test.tsnot shown

Its text is not shown, modified.

modified: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/rules/src/rules-evaluator.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/fixtures/cm/project.jsonnot shown

Its text is not shown, modified.

modified:packages/rules/test/fixtures/cm/project.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/fixtures/json-only/policy.jsonnot shown

Its text is not shown, modified.

modified:packages/rules/test/evaluate.test.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/worker.test.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/world.tsnot shown

Its text is not shown, modified.

modified:packages/sdk/src/functions.tsnot shown

Its text is not shown, modified.

modified:packages/sdk/src/index.tsnot shown

Its text is not shown, modified.

modified:packages/sdk/src/kind.tsnot shown

Its text is not shown, modified.

modified:packages/sdk/src/project.tsnot shown

Its text is not shown, modified.

modified:packages/sdk/test/sdk.test.tsnot shown

Its text is not shown, modified.

modified:packages/testkit/src/scenarios.tsnot shown

Its text is not shown, modified.

modified:packages/testkit/test/scenarios.test.tsnot shown

Its text is not shown, modified.

modified:scripts/lib/smoke/core-loop.tsnot shown

Its text is not shown, modified.

modified:scripts/lib/smoke/loop.tsnot shown

Its text is not shown, modified.

modified:scripts/lib/swarm/views/counter.tsnot shown

Its text is not shown, modified.

modified:scripts/smoke.tsnot shown

Its text is not shown, modified.

modified:AGENTS.md+7 added-7 removed
11 unmodified lines
1213| # | Principle | Held by |14| --- | --- | --- |15| 1 | **Encode lessons in structure; prose is the last rung.** When a mistake repeats, make it unrepresentable, then a lint or a test. | No fence |16| 2 | **Parse at the boundary, trust inside.** Decode every external input (HTTP, git, DO RPC, WebSocket, rule facts, env) with Effect Schema; inside, use branded types (`AskId`, `LandedSha`, `PatchId`). Decode the Worker `env` once, in one Layer. | The Effect diagnostics at error in `tsconfig.base.json`; `anti-slop/no-unknown-parameters`, `anti-slop/no-widen-then-assert` and `anti-slop/require-safety-comment-for-type-assertion`; `apps/platform/test/platform.test.ts` (a bad env fails at start, decoded once in `apps/platform/src/platform.ts`); `apps/platform/test/bindings.test.ts` (the decoded bindings, vars and secrets equal each wrangler.jsonc block's, the `AI` binding, `DRAFT_LIMIT`, `DRAFT_MODEL`, `PUBLIC_WEB_URL`, the code store's `CODE_CACHE` and each stage's own metrics dataset, `METRICS`, among them, and each port's factory takes its binding as the generated Env types it, without a cast); `packages/project/test/code-history.test.ts` (a kept code-history value is decoded with Schema when read, and one that no longer decodes is computed again); `packages/project/test/code.test.ts` (a kept commit that no longer decodes is computed again); `apps/web/test/dev-fixtures.test.ts` (the dev world's fixture record is decoded through the protocol's schemas when the world is built, so every case reads only a record that decodes); `apps/web/test/server-params.test.ts` (a project route's server handler is handed the project's full name once, as Start's params parse it, never parsed again); `apps/web/test/theme.test.ts` (the theme preference is decoded with Schema when read from `localStorage`, and a value it never wrote, or storage the browser refuses, reads as the system's own) |17| 3 | **Refusals are a closed `Schema.TaggedError` union and a public contract.** Handle them with `Match.exhaustive` or `catchTags`. Each carries a `retryable` and a `next` command fixed per tag, an optional `at`, and no `message` field. A `_tag` is renamed only with an alias. `protocol/render` is the one renderer for git `remote:`, CLI and MCP text. Stage-1 refusals accumulate. | `packages/protocol/test/refusal.test.ts` and `packages/protocol/test/render.test.ts` (every tag, the code reads' and drafting's `UnknownPath`, `UnknownRevision`, `UnknownProposal`, `ProposalClosed` and `DraftInProgress` included; a limit's refusal names its kind and its wait, and a ref outside `refs/heads/` reads as one the platform writes); `packages/agent-kit/test/full-llms.test.ts` (every tag in the union has a row in `/llms-full.txt`); `packages/protocol/test/mcp.test.ts` (a refusal from tools/call keeps its tag); `anti-slop-effect/prefer-effect-match` and `anti-slop-effect/no-manual-tag-comparison`; `packages/gate/test/shape.test.ts` (one push hears every stage-1 refusal at once); `apps/platform/test/mcp.test.ts` (each refusing MCP contract comes back as its exact refusal, `draftAsk`, `showProposal` and a code read's `UnknownPath` included); `apps/platform/test/workflows/draft.test.ts` (past the draft limit, `CapReached`); `apps/cli/test/policy.test.ts`; `apps/cli/test/local/check.test.ts` (the local check gives the gateway's stage-1 refusals for the same commit); `packages/protocol/test/exit-code.test.ts` (each tag's CLI exit code is pinned, 75 exactly when it is retryable); `packages/telemetry/test/defects.test.ts` (a refusal is never reported as an error, and a defect is reported once, at Error, with its cause and stack, however many boundaries it crosses), with `apps/platform/test/telemetry.test.ts` (the routers, a Project DO call and a Workflow instance each report a defect once, and neither the DO's caller nor a Workflow step that met it reports it again) and `apps/sandbox/test/telemetry.test.ts` (a sandbox job's defect is the platform's to report), and `apps/sandbox/test/check-logs.test.ts` (a check's phases reach the logs by their size alone, never their text, so an answer's failing test makes no Issue); `packages/config/test/legacy-projects.test.ts` (the same alias rule for a project's address: the forty projects made before owners keep their keys as aliases of their full names, the two examples and the import plan's, each key and each name once) |18| 4 | **One schema, many surfaces.** Change `packages/protocol`; every surface derives from it. Projections live only in `apps/*/src/surfaces.ts`. The CLI's command list is `commandDocs` in `@repo/agent-kit`, which the platform's skill, the CLI's MCP prompt and the web's `llms.txt` all read. | `apps/cli/test/commands-doc.test.ts` (the command list against the real CLI's commands, flags and positionals, `policy`, `ask draft` and `proposal` included); `packages/protocol/test/mcp.test.ts` (every MCP tool's schemas, with no JSON Schema leak, the policy and drafting contracts included; the five capped code reads are tools, `showCommit` and `listPaths` are not); `packages/agent-kit/test/install-channels.test.ts` and `apps/web/test/agents.test.tsx` (every snippet, command and link on the Install page is `@repo/agent-kit`'s, and the old `/agents` answers a 301 to `/install`); `packages/agent-kit/test/docs.test.ts` and `apps/web/test/docs.test.tsx` (the `/docs` pages name only the CLI's commands with flags each takes and link only to pages that exist, the reference lists every command, refusal, event, MCP tool, limit, endpoint and imported project from its source, and the web draws each page and its Markdown from that one text); `apps/web/test/llms.test.ts` (`/` and `/<project>` asked for Markdown answer with the `llms.txt` texts, and their HTML names that Markdown as an alternate); `packages/agent-kit/test/full-llms.test.ts` (one `ProjectEvent` line per tag); `apps/platform/test/home.test.ts` (the platform's `/` in Markdown is the web's `llms.txt`, one text from `@repo/agent-kit`); `packages/protocol/test/project-name.test.ts` (`ProjectName` is the one parser of a project's name for every surface: lowercase, a legacy key read as its full name, encoded only in the full form, and a key that reads back to its name); per-package `allowedUnstableApis` with `unstableApiUsage` at error |16| 2 | **Parse at the boundary, trust inside.** Decode every external input (HTTP, git, DO RPC, WebSocket, rule facts, env) with Effect Schema; inside, use branded types (`AskId`, `LandedSha`, `PatchId`). Decode the Worker `env` once, in one Layer. | The Effect diagnostics at error in `tsconfig.base.json`; `anti-slop/no-unknown-parameters`, `anti-slop/no-widen-then-assert` and `anti-slop/require-safety-comment-for-type-assertion`; `apps/platform/test/platform.test.ts` (a bad env fails at start, decoded once in `apps/platform/src/platform.ts`); `apps/platform/test/bindings.test.ts` (the decoded bindings, vars and secrets equal each wrangler.jsonc block's, `POST_LIMIT`, `PUBLIC_WEB_URL`, the code store's `CODE_CACHE` and each stage's own metrics dataset, `METRICS`, among them, and each port's factory takes its binding as the generated Env types it, without a cast); `packages/project/test/code-history.test.ts` (a kept code-history value is decoded with Schema when read, and one that no longer decodes is computed again); `packages/project/test/code.test.ts` (a kept commit that no longer decodes is computed again); `apps/web/test/dev-fixtures.test.ts` (the dev world's fixture record is decoded through the protocol's schemas when the world is built, so every case reads only a record that decodes); `apps/web/test/server-params.test.ts` (a project route's server handler is handed the project's full name once, as Start's params parse it, never parsed again); `apps/web/test/theme.test.ts` (the theme preference is decoded with Schema when read from `localStorage`, and a value it never wrote, or storage the browser refuses, reads as the system's own) |17| 3 | **Refusals are a closed `Schema.TaggedError` union and a public contract.** Handle them with `Match.exhaustive` or `catchTags`. Each carries a `retryable` and a `next` command fixed per tag, an optional `at`, and no `message` field. A `_tag` is renamed only with an alias. `protocol/render` is the one renderer for git `remote:`, CLI and MCP text. Stage-1 refusals accumulate. | `packages/protocol/test/refusal.test.ts` and `packages/protocol/test/render.test.ts` (every tag, the code reads' `UnknownPath` and `UnknownRevision` and the discussions' `UnknownDiscussion` and `DiscussionClosed` included; a limit's refusal names its kind and its wait, and a ref outside `refs/heads/` reads as one the platform writes); `packages/agent-kit/test/full-llms.test.ts` (every tag in the union has a row in `/llms-full.txt`); `packages/protocol/test/mcp.test.ts` (a refusal from tools/call keeps its tag); `anti-slop-effect/prefer-effect-match` and `anti-slop-effect/no-manual-tag-comparison`; `packages/gate/test/shape.test.ts` (one push hears every stage-1 refusal at once); `apps/platform/test/mcp.test.ts` (each refusing MCP contract comes back as its exact refusal, `showDiscussion` and a code read's `UnknownPath` included); `apps/cli/test/policy.test.ts`; `apps/cli/test/local/check.test.ts` (the local check gives the gateway's stage-1 refusals for the same commit); `packages/protocol/test/exit-code.test.ts` (each tag's CLI exit code is pinned, 75 exactly when it is retryable); `packages/telemetry/test/defects.test.ts` (a refusal is never reported as an error, and a defect is reported once, at Error, with its cause and stack, however many boundaries it crosses), with `apps/platform/test/telemetry.test.ts` (the routers, a Project DO call and a Workflow instance each report a defect once, and neither the DO's caller nor a Workflow step that met it reports it again) and `apps/sandbox/test/telemetry.test.ts` (a sandbox job's defect is the platform's to report), and `apps/sandbox/test/check-logs.test.ts` (a check's phases reach the logs by their size alone, never their text, so an answer's failing test makes no Issue); `packages/config/test/legacy-projects.test.ts` (the same alias rule for a project's address: the forty projects made before owners keep their keys as aliases of their full names, the two examples and the import plan's, each key and each name once) |18| 4 | **One schema, many surfaces.** Change `packages/protocol`; every surface derives from it. Projections live only in `apps/*/src/surfaces.ts`. The CLI's command list is `commandDocs` in `@repo/agent-kit`, which the platform's skill, the CLI's MCP prompt and the web's `llms.txt` all read. | `apps/cli/test/commands-doc.test.ts` (the command list against the real CLI's commands, flags and positionals, `policy`, `ask open` and `discussion post` included); `packages/protocol/test/mcp.test.ts` (every MCP tool's schemas, with no JSON Schema leak, the policy and discussion contracts included; the five capped code reads are tools, `showCommit` and `listPaths` are not); `packages/agent-kit/test/install-channels.test.ts` and `apps/web/test/agents.test.tsx` (every snippet, command and link on the Install page is `@repo/agent-kit`'s, and the old `/agents` answers a 301 to `/install`); `packages/agent-kit/test/docs.test.ts` and `apps/web/test/docs.test.tsx` (the `/docs` pages name only the CLI's commands with flags each takes and link only to pages that exist, the reference lists every command, refusal, event, MCP tool, limit, endpoint and imported project from its source, and the web draws each page and its Markdown from that one text); `apps/web/test/llms.test.ts` (`/` and `/<project>` asked for Markdown answer with the `llms.txt` texts, and their HTML names that Markdown as an alternate); `packages/agent-kit/test/full-llms.test.ts` (one `ProjectEvent` line per tag); `apps/platform/test/home.test.ts` (the platform's `/` in Markdown is the web's `llms.txt`, one text from `@repo/agent-kit`); `packages/protocol/test/project-name.test.ts` (`ProjectName` is the one parser of a project's name for every surface: lowercase, a legacy key read as its full name, encoded only in the full form, and a key that reads back to its name); per-package `allowedUnstableApis` with `unstableApiUsage` at error |19| 5 | **The name lives only in `packages/brand`.** Internal packages use `@repo/*`. DO classes, Workflows, queues and databases carry job names. | `brand:check` (`scripts/brand.ts`, tested by `packages/brand/test/leaks.test.ts`); `apps/web/test/shell.test.tsx` (the footer's wordmark is `Brand.domain`, read from `@repo/brand`, never typed) |20| 6 | **Pure core, thin hosts.** Only `@repo/artifacts` calls Artifacts. Each beta dependency sits behind one job-named port with a `/memory` adapter in the owning package. Apps import packages only. Worker code stays free of `node:child_process`, `@effect/platform-bun` and OpenTUI. `rules` and `gate` run in both Workers and Bun. `alchemy/*` stays in `infra/`. No module-level mutable state in a package's `src/`. | Scoped `allowedUnstableApis`; `packages/artifacts/test/repo-host-contract.ts` (one RepoHost contract every adapter passes); `apps/platform/test/bindings.test.ts` and `apps/platform/test/worker-init.test.ts` (the Worker starts on its real adapters, composed in `apps/platform/src/ports.ts`); `apps/platform/test/router-build.test.ts` (both handlers are built when the Worker module loads, with no binding touched, and a layer that awaits a promise while it is built is refused there); `apps/web/test/production-bundle.test.ts` (no dev-world module in the web's production build, and no chunk every page preloads holds the Markdown renderer, under a gzip ceiling); `packages/config/test/cartridge.test.ts` (the visibility cartridge is plugged in by one marked line and reached by nothing else, so removing it is a deletion); `packages/drafting/test/memory.test.ts` (the `Drafter` port's `/memory` adapter, `packages/drafting/src/drafter/memory.ts`) and `packages/drafting/test/binding.test.ts` (its Workers AI adapter over the `AI` binding); `apps/platform/test/mailer.test.ts` (sign-in's `Mailer` port, its `/memory` adapter and its Email Service adapter over the `EMAIL` binding); `packages/project/test/code-store.test.ts` (the `CodeStore` port's `/memory` adapter, `packages/project/src/code-store/memory.ts`, and its R2 adapter over `CODE_CACHE`, whose failures are misses, never the read's); `packages/project/test/metrics.test.ts` (the `Metrics` port's `/memory` adapter, `packages/project/src/metrics/memory.ts`, and its Analytics Engine adapter over `METRICS`, which drops a point the dataset refuses and fails nothing; `apps/platform/test/worker-init.test.ts` writes through the Worker's own ports); `apps/platform/test/code-reads.test.ts` and `apps/web/test/dev-backend.test.ts` (the platform and the web's dev world answer the code reads and raw files alike, both through `@repo/project/code`); `packages/project/test/standing-posture.test.ts` (one helper, `withStandingPosture`, gives a listing each project's own posture, for the platform and the web's dev world alike, through the `StandingPostures` port whose default keeps nothing; its D1 adapter is the platform's); `packages/project/test/description.test.ts` and `packages/project/test/description-d1.test.ts` (the `ProjectDescriptions` port's `/memory` adapter, `packages/project/src/description/memory.ts`, and its D1 adapter, whose unreadable rows and missing table are misses); `apps/web/test/seeded.test.tsx` (a loader's read seeds a registry of its own page and leaves the registry every request shares as it was); `apps/web/test/shell.test.tsx` (no plain anchor between the web's pages: every link is the router's); `packages/telemetry/test/spans.test.ts` (the spans port: Effect's `Tracer`, bridged onto a Worker's `tracing` by `packages/telemetry/src/spans/binding.ts`, with its `/memory` adapter, `packages/telemetry/src/spans/memory.ts`, on which every span opens under the invocation's root, a sibling of the runtime's own, and an ended span is traced no more, as in workerd; only a Worker's composition imports `tracing` from `cloudflare:workers`). No fence: import direction and module-level state |21| 7 | **Deny by default for visibility.** Land the answer's tree, never the composed tree. Nothing from a layer enters a public tree. Snapshot before held-back files are written. Public-serving Workers have no private-namespace binding. Public commits, trailers, notes and errors name public paths only. | `PrivatePathInPublicTree`, one rule for the gate's stage 1 and the landing guard (`packages/gate/test/shape.test.ts`, `packages/visibility/test/guards.test.ts`); `apps/platform/test/visibility/layer-gateway.test.ts` (only a layer's readers clone it, every read is logged, a fork push cannot carry its paths); `apps/sandbox/test/held-back.test.ts` (egress off and the snapshot taken before any sealed file is written; one bit per area, no output); `packages/config/test/observability.test.ts` (a Checker's container logs are off in every stage, and every container sets its own; the platform's traces are kept in the account and sent to no destination, since the runtime's own spans record each Project DO statement's bound values and each fetch's full URL); `packages/config/test/alerts.test.ts` (an alert's query counts rows of its own stage's Workers and datasets, never a layer's or another stage's); `packages/telemetry/test/spans.test.ts` (a span carries only the listed ids onto a trace, never a repo, a path or a query, and Issues reads ids alone), `packages/telemetry/test/logger.test.ts` and `packages/telemetry/test/defects.test.ts` (no line, report or span carries a Worker secret or a write-only value, and where a Worker keeps a defect by its name, no line it logs carries the defect's text), with `apps/platform/test/telemetry.test.ts` (every secret the platform's env decodes, each session token included, and a route's or a Project DO's defect kept by its name and frames alone, since its text may name a layer's repo, on a report and on any line whose cause holds it, a warning's included), `apps/platform/test/sandbox-adapters.test.ts` (a sandbox job's defect logged by its name and frames alone), and `apps/sandbox/test/telemetry.test.ts` (a sandbox job's lines carry none of its tokens, and a Checker's span keeps a defect by its name alone, since its text may quote a sealed path); `apps/platform/test/visibility/held-back.test.ts` (the `Held-back:` trailer, the landing guards, no stored value in a note or a kept log); `apps/platform/test/bindings.test.ts`; `apps/sandbox/test/checker.test.ts` (no snapshot once the held-back slot is reached); `apps/web/test/env.test-d.ts` (the web's Env has no private-namespace, Artifacts or `CODE_CACHE` binding) and `apps/platform/test/env.test-d.ts` (only the platform's has both); `packages/project/test/code-raw.test.ts` and `apps/platform/test/raw.test.ts` (raw bytes under `nosniff` and the sandboxing CSP, refusals included); `apps/platform/test/code-reads.test.ts` (no code read's payload names a repo); `packages/project/test/code-history.test.ts` (the code store is keyed under the project's canonical repo alone and holds no landing); `apps/platform/test/w9-contracts.test.ts` (`projectPolicy` answers without the policy's layers or asks, and `packages/config/test/cartridge.test.ts` keeps the cartridge removable); `packages/drafting/test/prompt.test.ts` (a draft's prompt never carries a layer's name, repo, reason or paths); `apps/web/test/markdown.test.tsx` (a README's script, handlers, unsafe URLs, iframes, styles and forms never reach the page); `apps/platform/test/gateway.test.ts` and `packages/gate/test/parse.test.ts` (a fork takes branches only: its notes, tags and the platform's refs are refused); `packages/protocol/test/fork-address.test.ts` (a fork's address is a closed parse that never joins text into a ref path), with `packages/project/test/code.test.ts` and `apps/platform/test/code-reads.test.ts` (a fork is read only at the address of a claim fork the project lists, and a layer's repo, an unlisted fork or a repo's name is `UnknownRevision`); `packages/protocol/test/recent-landing.test.ts` and `packages/project/test/recent-landings-d1.test.ts` (a kept refusal is its tag and area alone); `packages/project/test/metrics.test.ts` (a metric names a project, a refusal's tag and area, a stage and a lane, with numbers: never a path, a command, a log or a held-back check); `apps/platform/test/visibility/posture-listing.test.ts` and `apps/platform/test/home.test.ts` (the project list and the platform's `/` show the posture the project's ledger shows); `apps/web/test/landing.test.tsx` (the landing's latest landings name each by its project, and a refused answer by its tag and its area alone, never a check's name, suite, lane, path or log) and `apps/web/test/explore.test.tsx` (each project's card shows the posture its listing gives); `apps/web/test/ledger.test.tsx` (the Visibility tab's ledger adds no path, check name or file name, and the tab's views import nothing from the visibility cartridge) and `apps/web/test/env.test.tsx` (its Environment shows no value and no control to set or read one, and the old `/env` and `/ledger` answer a 301 to the tab); `apps/web/test/home.test.tsx`, `apps/web/test/today.test.tsx` and `apps/web/test/edge-cache.test.ts` (`/inbox` is read with the reader's own session and kept by no cache, and the old `/home` and `/today` answer a 301 to it); `apps/web/test/theme.test.ts` and `apps/web/test/settings.test.tsx` (the theme preference lives in `localStorage` and never in a cookie, so it makes no page personal); `apps/platform/test/pages.test.ts` (the sign-in page, as an MCP client's consent, escapes every value a client supplies, and every sign-in form shown again escapes what the person typed); `apps/platform/test/oauth.test.ts` (no account is written, and no grant given, until its email is proved by a mailed code, and a password reset reads the same for an address no account has; the platform's own session is an HttpOnly, Secure, SameSite=Lax cookie that a changed seal, a missing account or a password reset turns into the plain sign-in page, and its sign-out goes only to the web's home); `apps/platform/test/gateway-owner.test.ts` (the gateway reads a full name, a source path, a legacy key or a fork's address to the repo its project's key names, and an owner alone or a name under a page's word to none) |22| 8 | **Deterministic and idempotent.** Rule evaluation sees frozen time and randomness and only injected facts. Re-running an operation converges. Check results are keyed by (tree SHA, check version), push events deduped by (repo, sha), and land requests carry a `requestId`. | `globalDate`, `globalRandom`, `globalTimers` and `cryptoRandomUUID` at error, with their in-Effect twins; `packages/rules/test/replay.test.ts`; `packages/project/test/project-store.contract.ts`; `packages/project/test/claim.model.test.ts` and `packages/project/test/landing.model.test.ts`; `apps/platform/test/workflows/answer.test.ts`; `apps/platform/test/workflows/on-push.test.ts`; `apps/platform/test/core-loop.test.ts`; `apps/platform/test/workflows/draft.test.ts` (a replayed draft round asks the model nothing more, and each round is its own instance); `packages/project/test/code.test.ts` (code reads cached by object id, only once finished, while `main` resolves every time, and a commit's diff kept by its SHA without its landing); `packages/project/test/drafting.model.test.ts` (a settle of a stale round changes nothing); `packages/project/test/import.test.ts` (a retried import adopts the repo it made, and a retried import keeps its source); `packages/project/test/code-history.test.ts` (a why and a path's history are kept by commit, path hash and algorithm version, and the store, a step from a kept ancestor and a whole walk agree); `packages/config/test/smoke-loop.test.ts` (smoke's throwaway project is in the ledger before init makes it, and a taken name stops before anything is made); `apps/web/test/events.test.ts` (the web's fold of a project's events gives the same map when an event is heard twice or out of order, and a replay that already holds a landing stamps nothing); `packages/project/test/standing-posture.test.ts` (a kept posture is read again only for the project whose event the projection applied, or once its instant has come); `packages/project/test/recent-landings-d1.test.ts` (the same rows heard again change nothing, and at most `RECENT_LANDINGS_CAP` rows are kept); `packages/project/test/description.test.ts` (a landed project is read once while its last landing stands); `apps/platform/test/well-known.test.ts` (the agent skills index is kept by its listing's projects and last landings, so while no listed project lands it wakes no project, and a landing reads again only its own skill); `packages/project/test/metrics.test.ts` (each landing, refusal, checked lane, wait before checks and draft round is written at most once, from the outbox of the commit that keeps it, however often its push, report or settle is heard, and when a call's settle and the alarm's both hold its row), with `packages/project/test/project-store.contract.ts` (of two acks of one outbox row, only the first takes it). No fence: one push deduped by (repo, sha) across the gateway's record and OnPush's |20| 6 | **Pure core, thin hosts.** Only `@repo/artifacts` calls Artifacts. Each beta dependency sits behind one job-named port with a `/memory` adapter in the owning package. Apps import packages only. Worker code stays free of `node:child_process`, `@effect/platform-bun` and OpenTUI. `rules` and `gate` run in both Workers and Bun. `alchemy/*` stays in `infra/`. No module-level mutable state in a package's `src/`. | Scoped `allowedUnstableApis`; `packages/artifacts/test/repo-host-contract.ts` (one RepoHost contract every adapter passes); `apps/platform/test/bindings.test.ts` and `apps/platform/test/worker-init.test.ts` (the Worker starts on its real adapters, composed in `apps/platform/src/ports.ts`); `apps/platform/test/router-build.test.ts` (both handlers are built when the Worker module loads, with no binding touched, and a layer that awaits a promise while it is built is refused there); `apps/web/test/production-bundle.test.ts` (no dev-world module in the web's production build, and no chunk every page preloads holds the Markdown renderer, under a gzip ceiling); `packages/config/test/cartridge.test.ts` (the visibility cartridge is plugged in by one marked line and reached by nothing else, so removing it is a deletion); `apps/platform/test/mailer.test.ts` (sign-in's `Mailer` port, its `/memory` adapter and its Email Service adapter over the `EMAIL` binding); `packages/project/test/code-store.test.ts` (the `CodeStore` port's `/memory` adapter, `packages/project/src/code-store/memory.ts`, and its R2 adapter over `CODE_CACHE`, whose failures are misses, never the read's); `packages/project/test/metrics.test.ts` (the `Metrics` port's `/memory` adapter, `packages/project/src/metrics/memory.ts`, and its Analytics Engine adapter over `METRICS`, which drops a point the dataset refuses and fails nothing; `apps/platform/test/worker-init.test.ts` writes through the Worker's own ports); `apps/platform/test/code-reads.test.ts` and `apps/web/test/dev-backend.test.ts` (the platform and the web's dev world answer the code reads and raw files alike, both through `@repo/project/code`); `packages/project/test/standing-posture.test.ts` (one helper, `withStandingPosture`, gives a listing each project's own posture, for the platform and the web's dev world alike, through the `StandingPostures` port whose default keeps nothing; its D1 adapter is the platform's); `packages/project/test/description.test.ts` and `packages/project/test/description-d1.test.ts` (the `ProjectDescriptions` port's `/memory` adapter, `packages/project/src/description/memory.ts`, and its D1 adapter, whose unreadable rows and missing table are misses); `apps/web/test/seeded.test.tsx` (a loader's read seeds a registry of its own page and leaves the registry every request shares as it was); `apps/web/test/shell.test.tsx` (no plain anchor between the web's pages: every link is the router's); `packages/telemetry/test/spans.test.ts` (the spans port: Effect's `Tracer`, bridged onto a Worker's `tracing` by `packages/telemetry/src/spans/binding.ts`, with its `/memory` adapter, `packages/telemetry/src/spans/memory.ts`, on which every span opens under the invocation's root, a sibling of the runtime's own, and an ended span is traced no more, as in workerd; only a Worker's composition imports `tracing` from `cloudflare:workers`). No fence: import direction and module-level state |21| 7 | **Deny by default for visibility.** Land the answer's tree, never the composed tree. Nothing from a layer enters a public tree. Snapshot before held-back files are written. Public-serving Workers have no private-namespace binding. Public commits, trailers, notes and errors name public paths only. | `PrivatePathInPublicTree`, one rule for the gate's stage 1 and the landing guard (`packages/gate/test/shape.test.ts`, `packages/visibility/test/guards.test.ts`); `apps/platform/test/visibility/layer-gateway.test.ts` (only a layer's readers clone it, every read is logged, a fork push cannot carry its paths); `apps/sandbox/test/held-back.test.ts` (egress off and the snapshot taken before any sealed file is written; one bit per area, no output); `packages/config/test/observability.test.ts` (a Checker's container logs are off in every stage, and every container sets its own; the platform's traces are kept in the account and sent to no destination, since the runtime's own spans record each Project DO statement's bound values and each fetch's full URL); `packages/config/test/alerts.test.ts` (an alert's query counts rows of its own stage's Workers and datasets, never a layer's or another stage's); `packages/telemetry/test/spans.test.ts` (a span carries only the listed ids onto a trace, never a repo, a path or a query, and Issues reads ids alone), `packages/telemetry/test/logger.test.ts` and `packages/telemetry/test/defects.test.ts` (no line, report or span carries a Worker secret or a write-only value, and where a Worker keeps a defect by its name, no line it logs carries the defect's text), with `apps/platform/test/telemetry.test.ts` (every secret the platform's env decodes, each session token included, and a route's or a Project DO's defect kept by its name and frames alone, since its text may name a layer's repo, on a report and on any line whose cause holds it, a warning's included), `apps/platform/test/sandbox-adapters.test.ts` (a sandbox job's defect logged by its name and frames alone), and `apps/sandbox/test/telemetry.test.ts` (a sandbox job's lines carry none of its tokens, and a Checker's span keeps a defect by its name alone, since its text may quote a sealed path); `apps/platform/test/visibility/held-back.test.ts` (the `Held-back:` trailer, the landing guards, no stored value in a note or a kept log); `apps/platform/test/bindings.test.ts`; `apps/sandbox/test/checker.test.ts` (no snapshot once the held-back slot is reached); `apps/web/test/env.test-d.ts` (the web's Env has no private-namespace, Artifacts or `CODE_CACHE` binding) and `apps/platform/test/env.test-d.ts` (only the platform's has both); `packages/project/test/code-raw.test.ts` and `apps/platform/test/raw.test.ts` (raw bytes under `nosniff` and the sandboxing CSP, refusals included); `apps/platform/test/code-reads.test.ts` (no code read's payload names a repo); `packages/project/test/code-history.test.ts` (the code store is keyed under the project's canonical repo alone and holds no landing); `apps/platform/test/w9-contracts.test.ts` (`projectPolicy` answers without the policy's layers or asks, and `packages/config/test/cartridge.test.ts` keeps the cartridge removable); `apps/web/test/markdown.test.tsx` (a README's script, handlers, unsafe URLs, iframes, styles and forms never reach the page); `apps/platform/test/gateway.test.ts` and `packages/gate/test/parse.test.ts` (a fork takes branches only: its notes, tags and the platform's refs are refused); `packages/protocol/test/fork-address.test.ts` (a fork's address is a closed parse that never joins text into a ref path), with `packages/project/test/code.test.ts` and `apps/platform/test/code-reads.test.ts` (a fork is read only at the address of a claim fork the project lists, and a layer's repo, an unlisted fork or a repo's name is `UnknownRevision`); `packages/protocol/test/recent-landing.test.ts` and `packages/project/test/recent-landings-d1.test.ts` (a kept refusal is its tag and area alone); `packages/project/test/metrics.test.ts` (a metric names a project, a refusal's tag and area, a stage and a lane, with numbers: never a path, a command, a log or a held-back check); `apps/platform/test/visibility/posture-listing.test.ts` and `apps/platform/test/home.test.ts` (the project list and the platform's `/` show the posture the project's ledger shows); `apps/web/test/landing.test.tsx` (the landing's latest landings name each by its project, and a refused answer by its tag and its area alone, never a check's name, suite, lane, path or log) and `apps/web/test/explore.test.tsx` (each project's card shows the posture its listing gives); `apps/web/test/ledger.test.tsx` (the Visibility tab's ledger adds no path, check name or file name, and the tab's views import nothing from the visibility cartridge) and `apps/web/test/env.test.tsx` (its Environment shows no value and no control to set or read one, and the old `/env` and `/ledger` answer a 301 to the tab); `apps/web/test/home.test.tsx`, `apps/web/test/today.test.tsx` and `apps/web/test/edge-cache.test.ts` (`/inbox` is read with the reader's own session and kept by no cache, and the old `/home` and `/today` answer a 301 to it); `apps/web/test/theme.test.ts` and `apps/web/test/settings.test.tsx` (the theme preference lives in `localStorage` and never in a cookie, so it makes no page personal); `apps/platform/test/pages.test.ts` (the sign-in page, as an MCP client's consent, escapes every value a client supplies, and every sign-in form shown again escapes what the person typed); `apps/platform/test/oauth.test.ts` (no account is written, and no grant given, until its email is proved by a mailed code, and a password reset reads the same for an address no account has; the platform's own session is an HttpOnly, Secure, SameSite=Lax cookie that a changed seal, a missing account or a password reset turns into the plain sign-in page, and its sign-out goes only to the web's home); `apps/platform/test/gateway-owner.test.ts` (the gateway reads a full name, a source path, a legacy key or a fork's address to the repo its project's key names, and an owner alone or a name under a page's word to none) |22| 8 | **Deterministic and idempotent.** Rule evaluation sees frozen time and randomness and only injected facts. Re-running an operation converges. Check results are keyed by (tree SHA, check version), push events deduped by (repo, sha), and land requests carry a `requestId`. | `globalDate`, `globalRandom`, `globalTimers` and `cryptoRandomUUID` at error, with their in-Effect twins; `packages/rules/test/replay.test.ts`; `packages/project/test/project-store.contract.ts`; `packages/project/test/claim.model.test.ts` and `packages/project/test/landing.model.test.ts`; `apps/platform/test/workflows/answer.test.ts`; `apps/platform/test/workflows/on-push.test.ts`; `apps/platform/test/core-loop.test.ts`; `packages/project/test/code.test.ts` (code reads cached by object id, only once finished, while `main` resolves every time, and a commit's diff kept by its SHA without its landing); `packages/project/test/import.test.ts` (a retried import adopts the repo it made, and a retried import keeps its source); `packages/project/test/code-history.test.ts` (a why and a path's history are kept by commit, path hash and algorithm version, and the store, a step from a kept ancestor and a whole walk agree); `packages/config/test/smoke-loop.test.ts` (smoke's throwaway project is in the ledger before init makes it, and a taken name stops before anything is made); `apps/web/test/events.test.ts` (the web's fold of a project's events gives the same map when an event is heard twice or out of order, and a replay that already holds a landing stamps nothing); `packages/project/test/standing-posture.test.ts` (a kept posture is read again only for the project whose event the projection applied, or once its instant has come); `packages/project/test/recent-landings-d1.test.ts` (the same rows heard again change nothing, and at most `RECENT_LANDINGS_CAP` rows are kept); `packages/project/test/description.test.ts` (a landed project is read once while its last landing stands); `apps/platform/test/well-known.test.ts` (the agent skills index is kept by its listing's projects and last landings, so while no listed project lands it wakes no project, and a landing reads again only its own skill); `packages/project/test/metrics.test.ts` (each landing, refusal, checked lane and wait before checks is written at most once, from the outbox of the commit that keeps it, however often its push or report is heard, and when a call's settle and the alarm's both hold its row), with `packages/project/test/project-store.contract.ts` (of two acks of one outbox row, only the first takes it). No fence: one push deduped by (repo, sha) across the gateway's record and OnPush's |23| 9 | **Effect v4 only.** Read `node_modules/effect/src` as API truth. Effect marks its unstable modules (`effect/http`, `effect/sql`, `effect/observability` and the rest) in place, with no `effect/unstable/*` path: one is off limits outside the paths its package's allow-list names. Off limits too: v3 `@effect/platform` and `@effect/cli`, and `effect/workflow` or `effect/cluster` on Workers. | `outdatedApi`; `unstableApiUsage` at error, with per-path `allowedUnstableApis` in `tsconfig.base.json`; `no-restricted-imports` |24| 10 | **Escapes need a reason.** Every `oxlint-disable`, `@effect-diagnostics` or `@ts-expect-error` carries its reason after `--`, and is added only where no idiomatic code does the job. | `check` fails on an unused directive. No fence: the reason |25| 11 | **`bun run verify` is the authority.** Deploy only to an explicit stage, after `verify`, with smoke after. A red gate is fixed, never deployed around. | `packages/config/test/verify.test.ts` (verify's steps); `infra/deploy.ts` refuses without a known stage, runs `verify` first and `scripts/smoke.ts` after, which fails on any exception or error-level line the stage's Workers logged since the first upload, or on a token that can't read them (`packages/config/test/deploy.test.ts`, `packages/config/test/smoke.test.ts`), and refuses every deploy while `infra/.recording` is there (`packages/config/test/recording.test.ts`) |26| 12 | **Lifecycles are pure transitions.** `transition(state, command, now)`. Per DO call: hydrate, transition, persist, settle. Deadlines run on DO alarms. Call them lifecycles. | `globalTimers` and `globalTimersInEffect`; `packages/project/test/claim.model.test.ts` and `packages/project/test/landing.model.test.ts` (model tests over effect/Arbitrary histories, each seen catching its planted bug); `packages/project/test/drafting.model.test.ts` (a proposal's `DraftCommand.DraftStarted` and `DraftSettled` over generated histories; a Ready round's files survive a later failed round); `apps/platform/test/project-do.test.ts`. No fence: `Effect.sleep` and `Effect.delay` in `packages/project/src` |26| 12 | **Lifecycles are pure transitions.** `transition(state, command, now)`. Per DO call: hydrate, transition, persist, settle. Deadlines run on DO alarms. Call them lifecycles. | `globalTimers` and `globalTimersInEffect`; `packages/project/test/claim.model.test.ts` and `packages/project/test/landing.model.test.ts` (model tests over effect/Arbitrary histories, each seen catching its planted bug); `apps/platform/test/project-do.test.ts`. No fence: `Effect.sleep` and `Effect.delay` in `packages/project/src` |2728## Verify2930`bun run verify` runs `lockfile:check`, `check`, `typecheck`, `test`, `brand:check` and `bytes:check`, and stops at the first failure. Run `bun run fix`, then `bun run verify`, before you stop. When a check fails, fix the cause. Loosening, skipping or disabling a check needs the maintainer's sign-off.
109 unmodified lines
modified:bun.locknot shown

Its text is not shown, modified.

modified:DESIGN.md+4 added-4 removed
275 unmodified lines
276277- Four shells (site, project, docs, focus), each named by its route, with no global rail and no generic right rail. The site, the docs and a focused page are ruled (the rails); a project is full-bleed.278- A project has one header and eight tabs, and opens on Overview.279- State is a mark, then a word, then a colour; red belongs to refusals, violet to sealed things, green to what is on main, olive to waiting, blue to checking. In a row the colour is the mark's; the word is ink, except Refused and Landed.280- Every action is a command to copy, shown once per screen. The only web controls that change anything are a maintainer's choices, proposing an ask (and asking the platform's agent to draft it), the theme preference, and signing in or out.280- Every action is a command to copy, shown once per screen. The only web controls that change anything are a maintainer's choices, the theme preference, and signing in or out.281- Light and dark follow the system setting, or its opposite by the reader's choice on `/settings` (ADR 0042).282- Motion carries state, never decoration: transitions of 120 to 200 ms, the landing's stamp, and the landing's music box, whose every move is a step of an answer through the gate.283284## Colors
114 unmodified lines
399| --- | --- | --- | --- | --- |400| `site` | `/`, `/explore`, `/asks`, `/install`, `/privacy`, `/terms` | centred, ruled, `--container-site` (1760 px), `--gutter-site` (32 px) | framed top bar | only the filters on `/asks` (`--column-filters`, 240 px), left of the list |401| `project` | `/:owner/:project/**`, `/inbox`, `/settings`, `/people/:handle` | fluid to `--container-project` (1600 px), `--gutter-project` (28 px) | full-bleed top bar, then the page header | only the about column on Overview (`--column-about`, 340 px) and the file tree on Code (`--column-tree`, 280 px) |402| `docs` | `/docs/**` | centred, ruled, `--container-site` (1760 px) | the site's top bar | nav tree `--column-docs-nav` (240 px), parted from the article by a rule its full height; the article at `--measure` (72ch) with "on this page" (`--column-docs-toc`, 220 px) beside it, hugging it, the rest of the frame paper |403| `focus` | sign-in, MCP consent, new project, new proposal | a centred, ruled card, `--container-focus` (400 px) | the wordmark only, in the framed bar | none |403| `focus` | sign-in, MCP consent, new project | a centred, ruled card, `--container-focus` (400 px) | the wordmark only, in the framed bar | none |404405A shell sets its gutter once, on its frame, and every bar and page inside it reads it: 16 px on a phone, 20 px from `tablet`, and from `shell` (1120 px) `--gutter-site` in the site, the docs and a focused page, or `--gutter-project` in a project.406407**Rails.** The site, the docs and a focused page are ruled: from `tablet`, the container stands `--frame-inset` (24 px) in from the viewport and carries a hairline down each edge, the page's full height (`RAILS` in `app-shell.tsx`), and the top bar is a box between them, `--frame-gap` (16 px) under the viewport's top, with a hairline over and under it. Everything inside (the frame, a section's rule, the footer's rule) runs rail to rail, and the gutter sits inside the rails, so content stands 32 px in from them. Below `tablet` the rails and the gap go: the bar keeps its rule underneath, and the page takes the phone's 16 px gutter. The top bar's height stays `--top-bar`, borders included, so what sticks under it reads `--stick-bar` unchanged, and when the bar sticks it sits flush at the top. The platform's sign-in pages are not ruled: at the card's width, rails and a boxed bar read as boxes in boxes, so they draw one centred column, the wordmark (linking the web's home) over the card and what leads elsewhere under it, the card a bordered surface from `tablet` and the page itself on a phone. The platform's own clients (the web and the CLI, told by their client ids) are asked no consent there; any other client's name, address and grant are said above the form, the grant behind a disclosure. A project has no rails.
42 unmodified lines
450- **Shape:** a hairline above, rail to rail, a row of plain links (Docs, Install, Settings, Privacy, Terms), then **the brand's domain in upper case** as a watermark: one line of display text in the UI sans, read from `@repo/brand` (`Brand.domain`), upper-cased with CSS, never typed (`brand:check` fails on the name outside `packages/brand`). It is drawn in the ink at a tenth of its strength (`text-foreground/10`), centred, and sized with container query units to fill the content's width exactly, at 600 with -0.04em tracking and a 0.9 line, standing whole on the page's bottom edge (the 0.9 line leaves 0.075em under the baseline, and nothing else), so the page ends in the name. It is the one type that scales with its box. No mark beside it. The size (12.131cqi) is the width over the line's measured width per em, noted in `footer.tsx`; measure again if the domain changes.451452### Project header and tabs453454- **Header:** the name (`owner / project`, the owner muted, both in the UI sans at Headline size), the posture (`PostureBadge`), the description (the README's first sentence), a facts row in UI type, muted (open asks, last landing, latest tag, licence if known, deciders), and three actions at the right: **Watch** (a popover: what already follows the project, this page and its events, plus `myr status --project` for your own claims and answers; the CLI has no watch command), **Clone** (a popover: the `git clone` URL, `myr claim <ask> --project`, and that forks come with a claim), **Contribute** (a popover: take an ask, propose an ask, read the policy). It never changes between tabs.455- **Tabs:** Overview · Code · Asks · Landings · Proposals · People · Policy · Visibility, each a text tab with its count in label type; the current one ink at 500 with a 2 px ink underline (the one current-tab style of the whole web), the rest muted. The header and tabs stick under the top bar together; on a phone the tabs scroll sideways inside their own strip.454- **Header:** the name (`owner / project`, the owner muted, both in the UI sans at Headline size), the posture (`PostureBadge`), the description (the README's first sentence), a facts row in UI type, muted (open asks, last landing, latest tag, licence if known, deciders), and three actions at the right: **Watch** (a popover: what already follows the project, this page and its events, plus `myr status --project` for your own claims and answers; the CLI has no watch command), **Clone** (a popover: the `git clone` URL, `myr claim <ask> --project`, and that forks come with a claim), **Contribute** (a popover: take an ask, start a discussion, read the policy). It never changes between tabs.455- **Tabs:** Overview · Code · Asks · Landings · Discussions · Policy · Visibility, each a text tab with its count in label type; the current one ink at 500 with a 2 px ink underline (the one current-tab style of the whole web), the rest muted. The header and tabs stick under the top bar together; on a phone the tabs scroll sideways inside their own strip.456- **Overview** (the default tab): open asks, recent landings and the README in the main column (its headings a level down, so the project's name stays the page's one h1); the about column (`--column-about`) with clone, how a change lands (the seven stages), who decides, a visibility summary and languages.457- **Code:** under the header, the code bar: a Files/History toggle, the revision picker (`main`, tags, and answers in claim forks, ADR 0043), the HEAD commit, Go to file and Clone; then the file tree in `--column-tree` beside every page of the tab. The history is git's first-parent log with the platform's landing record on each commit that has one, filtered to Landings, Answers, Ask openings or Every commit (Landings by default on main); the Landings tab opens that history of main filtered to its landings, and a commit's page sits under it.458- **Visibility:** posture, layers, held-back checks, the environment (once "Env shape") and the ledger, one tab.459
181 unmodified lines
modified:GLOSSARY.md+6 added-17 removed
27 unmodified lines
28The fork a claim is made of, at `<owner>/<name>--<ask>--<handle>`, to which the claimant pushes answers.29_Avoid_: branch, feature branch3031**Working fork**:32A person's own fork of a project, at `<owner>/<name>--me--<handle>`, that holds a maintainer's own changes before they land and a proposer's sealed answers.32A person's own fork of a project, at `<owner>/<name>--me--<handle>`, that holds a maintainer's own changes before they land.33_Avoid_: personal fork, scratch repo3435**Check**:36The predicate that judges an answer: the ask's own check plus the project's checks, run by the platform on the exact merged tree.
18 unmodified lines
55One or more members of the closed, typed union the platform returns instead of landing, all from the cheapest failing stage, each with a reason, a reproducing command, a next step, and whether retrying can help.56_Avoid_: rejection, error, failure, CI failure5758**Discussion**:59A public, freeform thread in a project, open to anyone not denounced, that lands nothing itself; a maintainer may turn it into a proposal.60_Avoid_: issue, forum topic, comments59A public, freeform thread in a project, open to anyone not denounced, that lands nothing itself; a maintainer may open an ask from it, which closes the thread as asked.60_Avoid_: issue, forum topic, comments, proposal, feature request6162**Proposal**:63A request to open an ask, or to flag an existing one, from anyone not denounced, or made by a maintainer from a discussion; it expires unless a maintainer accepts it.64_Avoid_: feature request, suggestion6566**Draft**:67An ask file and its check that the platform's agent wrote for a proposal, run red first before it is put to a maintainer. It lands only when a maintainer accepts it.68_Avoid_: AI suggestion, auto-ask6970**Sealed answer**:71An answer recorded with a proposal and judged after the ask opens, without the maintainer reading its diff.7262**Finish**:63A maintainer's own commits on a passing answer before it lands, re-checked and credited with Finished-by.64_Avoid_: review, nit, suggested change65
51 unmodified lines
117The accountable human who signs an answer; any agent works through their token.118_Avoid_: contributor (when meaning this role), agent identity119120**Maintainer**:132A person whose decisions open asks, accept proposals and finish answers for an area; a path may name several, and may ask that more than one of them agree.121A person whose decisions open asks and finish answers for an area; a path may name several, and may ask that more than one of them agree.122_Avoid_: decider, reviewer, approver, owner, delegate123124**Decision**:125One choice put to a project's maintainers, with its evidence and a safe default that is taken if nobody decides before it expires. Where a path asks for more than one maintainer, the choice takes effect once that many have chosen alike, and waits until then.
7 unmodified lines
133A person's own page on the web: the decisions waiting for them (their Today), the asks they hold with where each answer stands in the gate, and the asks they may take next. It is read with their session and kept by no cache.134_Avoid_: home, notifications, dashboard135136**Vouch**:148A line in the project's vouch file by which a member admits a person to claim and to submit sealed answers; it may carry the member's reason and the landing it followed, and it is read as a line, never counted.137A line in the project's vouch file by which a member admits a person to claim; it may carry the member's reason and the landing it followed, and it is read as a line, never counted.138_Avoid_: approval, whitelist, endorsement, trust score139140**Denouncement**:152A line in the project's vouch file that bars a person from making proposals and posting in discussions; it is shown as the line it is, never as a warning beside the person's name.141A line in the project's vouch file that bars a person from claiming and posting in discussions; it is shown as the line it is, never as a warning beside the person's name.142_Avoid_: ban, block, flag143144**Record**:145A person's landings by area and kind that stayed unreverted for 30 days, used only for trust rules, never shown as a score.
96 unmodified lines
modified:PRODUCT.md+8 added-8 removed
15 unmodified lines
16171. **Maintainers** keep a project. Their jobs:18 - say what the project wants, as asks: a file on main with a want, a territory and a check that fails on main, which opens only when the check is red first;19 - set how the project takes changes, as typed code in its config folder on main (maintainers, ask kinds, decision expiry, vouches, ratchets, the run block, visibility), read from the platform's last landing;20 - take the decisions on Today: open or decline a proposal, waive an escape, accept a posture change, finish a passing answer; doing nothing lets nothing in;21 - vouch for the people who may claim, each vouch a line that may say why and name the landing it followed, and denounce those who may not propose; a vouch is read as its line, never counted;20 - take the decisions on Today: waive an escape, accept a posture change, finish a passing answer; doing nothing lets nothing in;21 - vouch for the people who may claim, each vouch a line that may say why and name the landing it followed, and denounce those who may not claim or post; a vouch is read as its line, never counted;22 - keep checks of their own in a layer only they read, and set write-only env values from a terminal;23 - land their own changes through the same gate as anyone else.242. **Contributors** answer asks, often a newcomer looking for a first one. Their jobs:25 - find an ask they may take, on the front page, with `asks` or with `front`, each saying what done means before they start; some asks are held for newcomers, with a mentor named, and such an ask reads as held for them on every page and to every reader, never as closed to them;26 - claim it, which gives them a fork and an exclusive slot kept alive by pushing;27 - answer with plain git in that fork, run the gate's checks locally with `check`, push, and read the verdict where they already look (git's own output, `status`, the verdict note, the answer's page); each push the gate checks is a numbered round, and a verdict stays with its round when the next push comes;28 - propose an ask nobody wrote yet, as a proposal that expires unless a maintainer accepts it;28 - ask for something nobody wrote an ask for yet, in a discussion a maintainer may open an ask from;29 - own what lands: their name is on the commit, and their record is built from those commits.303. **Their harnesses**, the coding agents a person works through (Claude Code, OpenCode, Amp, pi, others). Their jobs: read the project's AGENTS.md block or skill, an ask as Markdown, `llms.txt` and the MCP tools; act only through their person's token; read refusals as typed JSON and run each one's `next`. An agent holds no account and no credit: the person's claim carries identity, and a landing discloses the agent apart (`Assisted-by`).3132Contributors meet four nouns, and only four: **ask**, **answer**, **check** and **refusal**. Everything else (decision, layer, ledger, posture, ratchet) is maintainer or platform vocabulary.
24 unmodified lines
57- **No inbound or two-way sync with another code host.** It would be a second way onto main that skips the gate. Sign-in uses the platform's own accounts, with Google as an option.58- **No model's opinion in the gate.** Checks are commands with exit statuses and counts; an answer is judged by them, and taste is a maintainer's finish.59- **No scores.** A person appears by handle and role; their record serves trust rules only and is never shown as a number, rank or leaderboard.60- **No overclaiming.** Held-back checks are hidden from people and agents, not from the code under test, so they are no security boundary. Myr is a prototype, not a whole forge; it makes no claim about speed or scale beyond measured, dated numbers.61- **No second way to land.** The web adds no form for what git or the CLI does. Its only writes are a maintainer's choices, proposing an ask (and asking the platform's agent to draft it), and signing in or out. Landed code and each landing's diff are public, as a clone already makes them; an answer that has not landed shows its diff only to the maintainer finishing it.61- **No second way to land.** The web adds no form for what git or the CLI does. Its only writes are a maintainer's choices and signing in or out. Landed code and each landing's diff are public, as a clone already makes them; an answer that has not landed shows its diff only to the maintainer finishing it.62- **No stacks of submissions.** A contributor's commits are not ordered into a stack that lands in parts; work is ordered by asks, and a family is the typed dependency, with a delete child that waits. A stack is a second ordering outside the gate.63- **No free labels.** Kinds and territories are typed; a label with no check behind it is work nobody asked for.64- **No discussion on rounds, and no reactions anywhere.** The gate's verdict is the only voice on a round.65- **No mirroring by a second push URL.** It is a second way onto main.
8 unmodified lines
74- Pages per job on the web:75 - **Landing** (`/`): what the gate does, the issue and pull-request flow beside the ask, answer and gate flow, the seven stages, and the latest landings and refused answers across projects. A signed-in reader goes on to the inbox.76 - **Explore** (`/explore`): every public project as a card with its posture, the projects taking answers first.77 - **Front page** (`/asks`): open asks across projects a viewer may take, grouped by project with each project's posture said once, in the group heading, filtered by kind, by open to take and by asks held for newcomers; a split family is one row with its children as a fan. The same list as Markdown by `Accept: text/markdown`.78 - **Project** (`/$project`, the Overview tab): a header that stays across the tabs (the name, the posture said once, a description, its facts and Watch, Clone and Contribute), then the tabs Overview, Code, Asks, Landings, Proposals, Discussions, People, Policy and Visibility. Overview holds its asks, recent landings and README, beside an about column with how a change lands here and who decides. The same as the project's `llms.txt` by `Accept: text/markdown`.78 - **Project** (`/$project`, the Overview tab): a header that stays across the tabs (the name, the posture said once, a description, its facts and Watch, Clone and Contribute), then the tabs Overview, Code, Asks, Landings, Discussions, Policy and Visibility. Overview holds its asks, recent landings and README, beside an about column with how a change lands here and who decides. The same as the project's `llms.txt` by `Accept: text/markdown`.79 - **Code** (`/$project/tree/…`, `blob/…`, `why/…`, `commits/…`, `commit/…`, `refs`): the files at any commit, tag or answer fork with a persistent tree, highlighted code with `#L` links, why each line is there, the landings by day, each commit's diff, and the refs; raw bytes under a sandboxing CSP.80 - **Asks** (`/$project/asks`): the project's open asks, each saying whether it is open to take.81 - **Ask** (`/$project/asks/$ask`): the want, the territory, the check, who may claim, and the commands; the same as Markdown by `Accept: text/markdown` or at `/$project/asks/$ask.md`.82 - **Answer** (`/$project/answers/$ask`): the outcome, the gate's stages, the rounds, the lanes, held-back results as one line per area, the refusal, and the landing. A waiting answer says the one thing the contributor needs; a landed one is told as a sentence first, then credits its people, and only then shows its sealed roots.83 - **Person** (`/people/$handle`): their credits by role and area, in words, never a number or a score.83 - **Policy** (`/$project/people`): who decides which paths, who is vouched for or denounced, the limits and the agent rules, read from the config folder at the landed commit, with the commands that change them.84 - **Discussions** (`/$project/discussions`, `/$project/discussions/$discussion`): a project's public, freeform threads, open to anyone not denounced, that land nothing themselves; each page shows its posts, the proposal a maintainer turned it into, and the command to post, since the web adds no form for it.85 - **Proposals** (`/$project/proposals/new`, `/$project/proposals/$proposal`): a want proposed from the web or the CLI, the platform's agent's draft if one was asked for (the ask file, the check, its red-first runs), and the decision it waits on.84 - **Policy** (`/$project/policy`; `/$project/people` moves here): who decides which paths, who is vouched for or denounced, the limits and the agent rules, read from the config folder at the landed commit, with the commands that change them.85 - **Discussions** (`/$project/discussions`, `/$project/discussions/$discussion`): a project's public, freeform threads, open to anyone not denounced, that land nothing themselves; each page shows its posts, the ask a maintainer opened from it, and the command to post, since the web adds no form for it.86 - **Inbox** (`/inbox`; `/home` and `/today` move here): the reader's own page. A maintainer's decisions in sections (due today, later), every open one, each with its evidence, safe default, expiry and one-tap choices whose consequence is written under each, with how many wait said as a sentence; the asks the reader holds and where each answer stands in the gate; the asks they may take next. Each decision has its own page (`/$project/decisions/$decision`), where a finish shows the answer's diff with refusals marked at their lines.87 - **Visibility** (`/$project/visibility`; `/$project/ledger` and `/$project/env` move here): the posture, each declared layer with its reason, each sealed area's count, authors, committed root and admission; the Environment, every item the project's committed `.env.schema` declares, parsed at the landed commit and never resolved, with who set a sensitive item's value and when, never a value; and the ledger, newest first.88 - **Settings** (`/settings`): the theme, the system's or its opposite, kept in this browser's `localStorage`, never a cookie.89 - **Sign-in** (`/auth/signin`): through the platform's own accounts; the session lives in an HttpOnly cookie the browser cannot read.
36 unmodified lines
modified:README.md+1 added-1 removed
75 unmodified lines
76- **Issues**: exceptions, failed invocations and error-level lines, grouped; each line keeps its ids.77- **Traces**, in all three. The runtime's own spans record each Durable Object SQL statement's bound values and each fetch's full URL, so the platform's traces hold the Project Durable Object's layer rows and sealed values (never a plain value). They stay in the account's own trace store, kept seven days: the platform's traces have no export destination, and no Issues automation sends them anywhere.78- **Query strings**, unredacted, so `?service=` on git and `?since=` on watch stay readable. A sign-in callback's one-time `code` and `state` show too.79- **Source maps**, uploaded by each deploy. Cloudflare remaps an uncaught exception's stack with them, but a defect the platform reports itself is logged as thrown, minified, and by its name and frames alone, never its text. To read its frames, build the deployed commit's map with `bunx wrangler deploy --dry-run --outdir <dir> --env <stage>` in `apps/platform`.80- **Metrics**: landings, refusals by tag and stage, checked lanes, the wait before checks and draft rounds, written by the platform's `METRICS` binding to the stage's Workers Analytics Engine dataset, `metrics_<stage>` with `_` for `-`. `packages/project/src/metrics/binding.ts` lays out its columns.80- **Metrics**: landings, refusals by tag and stage, checked lanes and the wait before checks, written by the platform's `METRICS` binding to the stage's Workers Analytics Engine dataset, `metrics_<stage>` with `_` for `-`. `packages/project/src/metrics/binding.ts` lays out its columns.8182A Checker container's own logs are off, since held-back checks run there; the Lander's are on. Nothing the code itself logs, traces or counts names a layer, a held-back check, a path or a value (principle 7); only the runtime's own platform spans above do.8384Read them in the dashboard, under each Worker's Observability tab and under Issues, or through the SQL API with `bun run ops`. Its token needs Account › Account Analytics › Read, and so does smoke: after a deploy it fails on any exception or error-level line the stage's Workers logged since the first upload, naming each Worker and its count.
52 unmodified lines