Merge cli/init-and-ask-open 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 bf24bbf, b68e5c9 · Browse files · 28 files·+1186 added−68 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
28 files+1186 added−68 removed
- tests:+723 added−22 removed
- other:+463 added−46 removed
Provenance
- Commit
6be06d3- Tree
8a54e34- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
bf24bbf- Parent 2
b68e5c9
28 files changed+1186 added−68 removed
added:apps/cli/src/local/ask-open.ts+173 added
1+// Stands in for the `openAsk` contract: with no --files, the ask file and2+// the check it names are read from the working tree.3+import { Brand } from "@repo/brand";4+import { ApprovalNeeded } from "@repo/protocol/cli";5+import { Client, OpenAsk } from "@repo/protocol/contracts";6+import { ConfigFile } from "@repo/protocol/domain/common";7+import { AskId, ProjectName } from "@repo/protocol/ids";8+import { Effect, FileSystem, Option, Path, Schema } from "effect";9+import { Argument, Command, Flag } from "effect/cli";10+11+import { Output } from "../output.ts";12+import { repoContext } from "../repo-context.ts";13+import { projectOf, reportRefusals, usage, WorkingDirectory } from "./why.ts";14+15+const COMMAND = "ask open";16+17+type Payload = typeof OpenAsk.payloadSchema.Type;18+19+const Files = Schema.NonEmptyArray(ConfigFile);20+21+const decodePayload = Schema.decodeUnknownEffect(OpenAsk.payloadSchema);22+23+const encodePayload = Schema.encodeEffect(OpenAsk.payloadSchema);24+25+const encodeSuccess = Schema.encodeEffect(OpenAsk.successSchema);26+27+export const askFileOf = (ask: AskId) =>28+ `${Brand.configDir}/asks/${ask}.ask.ts`;29+30+// The ask names its check as one string literal, `path: "test/asks/x.test.ts"`,31+// as the SDK's `kinds.*.ask({ path })` takes it; the platform evaluates the32+// file itself before it lands anything.33+const CHECK_PATH = /\bpath:\s*(?<quote>["'`])(?<path>[^"'`\n]+)\k<quote>/u;34+35+const readOr = (file: string, missing: string) =>36+ Effect.flatMap(FileSystem.FileSystem, (fs) =>37+ fs38+ .readFileString(file)39+ .pipe(Effect.catchTag("PlatformError", () => usage(missing)))40+ );41+42+/** The ask's own file, then the check it names, both as the working tree has them. */43+export const filesInTree = (root: string, ask: AskId) =>44+ Effect.gen(function* () {45+ const path = yield* Path.Path;46+ const askFile = askFileOf(ask);47+48+ const askText = yield* readOr(49+ path.join(root, askFile),50+ `No ask file at ${askFile}: write the ask there, or pass --files.`51+ );52+53+ const check = CHECK_PATH.exec(askText)?.groups?.path;54+55+ if (check === undefined) {56+ return yield* usage(57+ `${askFile} names no check: give it a path, as in path: "test/asks/${ask}.test.ts", or pass --files.`58+ );59+ }60+61+ const checkText = yield* readOr(62+ path.join(root, check),63+ `${askFile} names the check ${check}, which is not in the working tree: write the failing test there, or pass --files.`64+ );65+66+ return [67+ { content: askText, path: askFile },68+ { content: checkText, path: check },69+ ];70+ });71+72+const viewOf = (ask: AskId, project: ProjectName, landed: string) => {73+ const said = `Opened ${ask} in ${project}; its file landed as ${landed.slice(0, 7)}. Anyone admitted may now take it: ${Brand.cli} claim ${ask} --project ${project}.`;74+75+ return { markdown: said, text: said };76+};77+78+export const askOpen = Command.make(79+ "open",80+ {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+ dryRun: Flag.Boolean("dry-run").pipe(86+ Flag.withDefault(false),87+ Flag.withDescription("Print the payload it would send, and send nothing")88+ ),89+ files: Flag.String("files").pipe(90+ Flag.withSchema(Schema.fromJsonString(Files)),91+ Flag.withMetavar("JSON"),92+ Flag.optional,93+ Flag.withDescription(94+ `The files to land, [{path, content}]; left out, ${Brand.configDir}/asks/<ask>.ask.ts and the check it names are read from the working tree`95+ )96+ ),97+ json: Flag.Boolean("json").pipe(98+ Flag.withDefault(false),99+ Flag.withDescription(100+ "Print one versioned JSON envelope on stdout, and nothing else there"101+ )102+ ),103+ project: Flag.String("project").pipe(104+ Flag.withSchema(ProjectName),105+ Flag.optional,106+ Flag.withDescription(107+ "The project; the repo's platform remote names it when left out"108+ )109+ ),110+ yes: Flag.Boolean("yes").pipe(111+ Flag.withDefault(false),112+ Flag.withDescription(113+ "Approve it: it runs only with --yes, since a person approves it first"114+ )115+ ),116+ },117+ (flags) =>118+ Effect.gen(function* () {119+ const { ask, dryRun, json } = flags;120+121+ if (!flags.yes && !dryRun) {122+ return yield* new ApprovalNeeded({ command: COMMAND });123+ }124+125+ const context = yield* Effect.option(126+ repoContext(yield* WorkingDirectory)127+ );128+129+ const project = yield* projectOf(flags.project, context);130+131+ const files = yield* Option.match(flags.files, {132+ onNone: () =>133+ Option.match(context, {134+ onNone: () =>135+ usage(136+ `Not inside a git repo: run ${Brand.cli} ${COMMAND} in the project's clone, or pass --files.`137+ ),138+ onSome: ({ root }) => filesInTree(root, ask),139+ }),140+ onSome: Effect.succeed,141+ });142+143+ const payload: Payload = yield* decodePayload({144+ ask,145+ files,146+ project,147+ }).pipe(Effect.catch((error) => usage(String(error))));148+149+ const output = yield* Output;150+151+ if (dryRun) {152+ return yield* output.plan({153+ command: COMMAND,154+ json,155+ payload: yield* Effect.orDie(encodePayload(payload)),156+ });157+ }158+159+ const client = yield* Client;160+ const opened = yield* client.openAsk(payload);161+162+ return yield* output.success({163+ command: COMMAND,164+ data: yield* Effect.orDie(encodeSuccess(opened)),165+ json,166+ view: viewOf(ask, project, opened.landed),167+ });168+ }).pipe(reportRefusals(COMMAND, flags.json))169+).pipe(170+ 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. It runs only with --yes: a person approves it.`172+ )173+);modified:apps/cli/src/local/index.ts+2 added
123456710 unmodified lines181920212223import type { Command } from "effect/cli";
import { askOpen } from "./ask-open.ts";import { check } from "./check.ts";import { envSet } from "./env-set.ts";import { init } from "./init.ts";import { login, logout } from "./login.ts";10 unmodified lines { command: init, path: ["init"] }, { command: check, path: ["check"] }, { command: why, path: ["why"] }, { command: envSet, path: ["env", "set"] }, { command: askOpen, path: ["ask", "open"] },] as const satisfies readonly LocalEntry[];modified:apps/cli/src/local/init.ts+48 added-11 removed
1 import { Brand } from "@repo/brand";2 import { findRunBlock } from "@repo/checks/finder";3 import type { RepoFile } from "@repo/checks/finder";4+import { PATH_PLACEHOLDER } from "@repo/checks/kinds";5 import { ApprovalNeeded } from "@repo/protocol/cli";6 import { Client } from "@repo/protocol/contracts";7 import type { InitProject } from "@repo/protocol/contracts";8 import { ProjectName, sourceNamespaceOf } from "@repo/protocol/ids";13 unmodified lines22 23 import { Credentials, gitHelperConfig } from "../credentials.ts";24 import { endRefused, Output } from "../output.ts";25 import { parseRemote, repoContext } from "../repo-context.ts";25-import { projectFile } from "./project-file.ts";26+import { ASKS_DIR, projectFile } from "./project-file.ts";27 28 const COMMAND = "init";29 30 const CONFIG = `${Brand.configDir}/project.ts`;1 unmodified line32 const SUBJECT = `Add ${CONFIG}: the run block ${Brand.cli} ${COMMAND} found`;33 34 const PENDING = { origin: "<platform>", remote: "<remote>" } as const;35 36+const 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.`;37+38+/** The CLI knows the platform's address alone; the web shows the project at the same path. */39+const pageLine = (project: string, remote: string) =>40+ Option.match(parseRemote(remote), {41+ onNone: () => `The web shows it at /${project}.`,42+ onSome: ({ origin }) =>43+ `Its address: ${origin}/${project} on the platform; the web shows it at /${project}.`,44+ });45+46 export class InitMisused extends Schema.TaggedError<InitMisused>()(47 "InitMisused",48 { reason: Schema.String }49 ) {45 unmodified lines95 Flag.withDescription("Print machine-readable JSON")96 ),97 project: Flag.String("project").pipe(98 Flag.withDescription(88- "The project's name, <owner>/<name>; a bare name is yours (<your handle>/<name>). By default this repo's folder, or an import's source path."99+ "The project's name, <owner>/<name>; a bare name is yours (<your handle>/<name>). By default this repo's folder, or an import's last URL segment, under your handle."100 ),101 Flag.optional102 ),103 push: Flag.Boolean("push").pipe(91 unmodified lines195 Effect.gen(function* () {196 const word = Option.getOrElse(given, () => fallback.short);197 const known = yield* profileOwner;198 199+ // An import is yours by default; its source namespace names it only200+ // when no handle is known here, or when --project spells it out.201 const owner = Option.isSome(given)202 ? known190- : Option.orElse(fallback.owner, () => known);203+ : Option.orElse(known, () => fallback.owner);204 205 const spelled = word.includes("/")206 ? word207 : `${Option.getOrElse(owner, () => "")}/${word}`;107 unmodified lines315 Effect.gen(function* () {316 const output = yield* Output;317 const reply = yield* makeProject(payload, input.json);318 const clone = `git clone ${reply.remote}`;319+ const page = pageLine(reply.project, reply.remote);320 321 yield* output.success({322 command: COMMAND,323 data: withLanded(7 unmodified lines331 reply.landed332 ),333 json: input.json,334 view: {321- markdown: `Imported ${url} as project **${reply.project}**. Clone it with:\n\n\`\`\`sh\n${clone}\n\`\`\``,322- text: `Imported ${url} as project ${reply.project}. Clone it with:\n ${clone}`,335+ markdown: `Imported ${url} as project **${reply.project}**. Clone it with:\n\n\`\`\`sh\n${clone}\n\`\`\`\n\n${page}\n\n${NEXT}`,336+ text: `Imported ${url} as project ${reply.project}. Clone it with:\n ${clone}\n${page}\n${NEXT}`,337 },338 });339 });340 25 unmodified lines366 yield* imported(input, url, payload);367 }368 });369 370+const configLine = (atHead: boolean, inTree: boolean) => {371+ if (atHead) {372+ return `Kept ${CONFIG} as it is.`;373+ }374+375+ return inTree376+ ? `Committed ${CONFIG} as the work tree had it, alone.`377+ : `Wrote ${CONFIG} and committed it alone.`;378+};379+380 interface Found {381+ readonly atHead: boolean;382 readonly commits: readonly string[];383 readonly hasRemote: boolean;384 readonly payload: Payload;385 readonly root: string;4 unmodified lines390 Effect.gen(function* () {391 const fs = yield* FileSystem.FileSystem;392 const path = yield* Path.Path;393 const output = yield* Output;369- const { commits, hasRemote, payload, root, writes } = found;394+ const { atHead, commits, hasRemote, payload, root, writes } = found;395 371- if (writes.length === 0) {396+ if (atHead) {397 yield* output.note(`kept ${CONFIG} as it is`);398 }399 400 for (const file of writes) {26 unmodified lines427 yield* output.note(ran.stderr.trimEnd());428 }429 }430 406- const config =407- writes.length === 0 ? `Kept ${CONFIG} as it is` : `Wrote ${CONFIG}`;431+ const config = configLine(atHead, writes.length === 0);432 433 const done = [434 `Made project ${reply.project} at ${reply.remote}.`,411- commits.length === 0 ? `${config}.` : `${config} and committed it alone.`,435+ config,436 input.push437 ? `Pushed HEAD to its main through the remote ${Brand.slug}.`438 : `Push when ready: git push ${Brand.slug} HEAD:main`,439+ pageLine(reply.project, reply.remote),440+ NEXT,441 ];442 443 yield* output.success({444 command: COMMAND,37 unmodified lines482 inTree || atHead483 ? []484 : [{ content: projectFile(block.run, block.sources), path: CONFIG }];485 486+ if (487+ writes.length > 0 &&488+ block.run.test?.includes(PATH_PLACEHOLDER) !== true489+ ) {490+ yield* Output.use((output) =>491+ output.note(492+ `No command that runs one test file was found, so ${CONFIG} takes run.fromCI. A red-first ask needs a test command with ${PATH_PLACEHOLDER}, as in test: "vitest run ${PATH_PLACEHOLDER}": add it to run before you open one.`493+ )494+ );495+ }496+497 const commits: readonly string[] = atHead ? [] : [CONFIG];498 499 const hasRemote =500 (yield* run(root, ["git", "remote", "get-url", Brand.slug])).exitCode ===15 unmodified lines516 payload,517 };518 519 if (yield* approved(input, plan)) {483- yield* made(input, { commits, hasRemote, payload, root, writes });520+ yield* made(input, { atHead, commits, hasRemote, payload, root, writes });521 }522 });523 524 export const init = Command.make(COMMAND, flags, (input) =>9 unmodified linesmodified:apps/cli/src/local/login.ts+15 added-4 removed
463 unmodified lines464 (yield* stdoutIsTerminal)465 );466 });467 468-const viewOf = (said: string, commands: readonly (readonly string[])[]) => {468+const viewOf = (469+ said: string,470+ commands: readonly (readonly string[])[],471+ next?: string472+) => {473 const lines = commands.map((argv) => typed(argv));474+ const after = next === undefined ? [] : [next];475 476 return {472- markdown:477+ markdown: [478 lines.length === 0479 ? said480 : `${said}\n\n\`\`\`sh\n${lines.join("\n")}\n\`\`\``,481+ ...after,482+ ].join("\n\n"),476- text: [said, ...lines.map((line) => ` ${line}`)].join("\n"),483+ text: [said, ...lines.map((line) => ` ${line}`), ...after].join("\n"),484 };485 };486 487+const nextAfterLogin = (handle: string) =>488+ `Next: ${Brand.cli} front to find an ask, or ${Brand.cli} init --project ${handle.toLowerCase()}/<name> in a repo of yours.`;489+490 export const login = Command.make(491 "login",492 {493 ...flags,61 unmodified lines555 view: viewOf(556 given.noGitConfig557 ? `Logged in to ${url} as ${handle} (profile ${name}). git's config is unchanged; for git to use this login, run:`558 : `Logged in to ${url} as ${handle} (profile ${name}). git now asks ${Brand.cli} for this platform's token; its global config got:`,549- commands559+ commands,560+ nextAfterLogin(handle)561 ),562 });563 })564 ).pipe(91 unmodified linesmodified:apps/cli/src/local/project-file.ts+86 added-3 removed
4 unmodified lines56789101112131415161728 unmodified lines46474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311454555611511611711811912012112212312412512612712812913013113213313413 unmodified lines14814915015115215315415515617 unmodified lines1741751761771781791801811821831841851861871881891901911929 unmodified lines4 unmodified linestype Value = string | readonly string[];
const KEYS = ["setup", "test", "doctor", "image", "setupEgress"] as const;
/** Where `init` suggests an ask's failing test goes, so the unit lane can leave it out. */export const ASKS_DIR = "test/asks";
const ASKS_GLOB = `${ASKS_DIR}/**`;
const keyOf = (name: string) => /^[A-Za-z_$][\w$]*$/u.test(name) ? name : JSON.stringify(name);
const oneLine = (text: string) => text.replaceAll(/\s+/gu, " ").trim();28 unmodified lines
const rules = (names: string) => `import { ${names} } from "${Brand.cliPackage}/rules";`;
// Runners whose flag leaves a folder out, by the word that starts the test// command (after any package runner).const RUNNER = /^(?:(?:npx|bunx|pnpm|pnpm exec|yarn|yarn exec) )?(?<tool>bun test|vitest|jest|mocha|pytest)\b/u;
const SKIPS = new Map([ ["bun test", `--path-ignore-patterns='${ASKS_GLOB}'`], ["jest", `--testPathIgnorePatterns '${ASKS_DIR}/'`], ["mocha", `--ignore '${ASKS_GLOB}'`], ["pytest", `--ignore=${ASKS_DIR}`], ["vitest", `--exclude '${ASKS_GLOB}'`],]);
const toolOf = (command: string) => RUNNER.exec(command)?.groups?.tool;
const ASKS_TRAP = [ "An open ask's test fails on main until it is answered, so the suite", "every answer must keep green leaves the asks' tests to their own lane.",] as const;
const ASKS_UNKNOWN = [ "An open ask's test fails on main until it is answered, so the suite", "every answer must keep green must leave the asks' tests out: give this", `lane the runner's flag that skips ${ASKS_GLOB}, or every answer's unit`, "lane is red while another ask is open.",] as const;
/** * The unit lane with the asks' tests left out, as the runner spells it: the * lane's own command when it calls the runner, else the test command without * its placeholder, which is what the lane's package script runs. */const unitLane = (unit: string, test: string | undefined) => { const runner = test?.replace(` ${PATH_PLACEHOLDER}`, "").trim(); const own = toolOf(unit); const tool = own ?? (runner === undefined ? undefined : toolOf(runner)); const skip = tool === undefined ? undefined : SKIPS.get(tool);
return skip === undefined ? { command: unit, note: ASKS_UNKNOWN } : { command: `${own === undefined ? runner : unit} ${skip}`, note: ASKS_TRAP, };};
const VOUCH = [ 'Anyone not denounced in vouched.td may claim an ask; "forCode" admits', "only the people vouched for there, which a maintainer lands with vouch.",] as const;
const vouchLines = [ ...VOUCH.map((line) => ` // ${line}`), ' vouch: "bansOnly",',];
const explicit = ( run: Partial<RunBlockEncoded>, sources: readonly string[]) => { const entry = (indent: string, part: string, key: string, value: Value) => [ ...sourcesOf(sources, part).map((source) => comment(indent, source)), `${indent}${keyOf(key)}: ${JSON.stringify(value)},`, ];
const lanes = Object.entries(run.checks ?? {}).flatMap(([lane, command]) => entry(" ", `checks.${lane}`, lane, command) ); const lanes = Object.entries(run.checks ?? {}).flatMap(([lane, command]) => { if (lane !== "unit") { return entry(" ", `checks.${lane}`, lane, command); }
const { command: excluded, note } = unitLane(command, run.test);
return [ ...sourcesOf(sources, `checks.${lane}`).map((source) => comment(" ", source) ), ...note.map((line) => ` // ${line}`), ` ${keyOf(lane)}: ${JSON.stringify(excluded)},`, ]; });
return [ rules("project"), "", comment(13 unmodified lines ...(lanes.length === 0 ? [" checks: {},"] : [" checks: {", ...lanes, " },"]), " },", ...vouchLines, "});", "", ];};17 unmodified lines ({ part, value }) => `// ${part}: ${oneLine(JSON.stringify(value))} (${oneLine(sourcesOf(sources, part).join("; "))})` ), ...others(sources, parts).map((source) => comment("", source)), comment( "", `A red-first ask needs a test command with ${PATH_PLACEHOLDER}; once one is here, give the unit` ), comment( "", `lane the runner's flag that skips ${ASKS_GLOB}, or every answer's unit lane is red while another ask is open.` ), "export default project({", " run: run.fromCI,", ...vouchLines, "});", "", ];};9 unmodified linesmodified:apps/cli/src/main.ts+12 added-2 removed
21 unmodified lines22 import { cliVersion } from "./version.ts";23 24 export const banner = [25 "Start here:",26- ` ${Brand.cli} asks list the open asks you could take`,26+ ` ${Brand.cli} front list the open asks across every project`,27 ` ${Brand.cli} claim take one; you get a fork to push your answer to`,28 ` ${Brand.cli} check run the gate's checks locally before you push`,29 ].join("\n");30 20 unmodified lines51 const isSharedUsage = Schema.is(52 Schema.Union([ApprovalNeeded, MissingValue, UnknownCommand])53 );54 55+const isMissingValue = Schema.is(MissingValue);56+57+/** `asks` wants one project; outside a clone, the cross-project list is the answer. */58+const hinted = (failure: Failure) =>59+ isMissingValue(failure) &&60+ failure.command === "asks" &&61+ failure.flag === "--project"62+ ? `${failure.message}; ${Brand.cli} front lists every project's`63+ : undefined;64+65 const signIn = [66 "Unauthenticated: the platform does not know who you are",67 ` next: ${Brand.cli} login`,68 " retryable: no",13 unmodified lines82 );83 }84 85 if (isUsage(failure) || Schema.isSchemaError(failure)) {76- return Option.some(failure.message);86+ return Option.some(hinted(failure) ?? failure.message);87 }88 89 return isTransportFailure(failure)90 ? Option.map(noPlatformOf(failure), ({ message }) => message)100 unmodified linesmodified:apps/cli/src/render.ts+57 added-5 removed
17 unmodified lines18 } from "@repo/protocol/contracts";19 import type { Contract } from "@repo/protocol/contracts";20 import { LandReceipt } from "@repo/protocol/domain/answer";21 import type { AnswerReceipt } from "@repo/protocol/domain/answer";22+import type { ClaimView } from "@repo/protocol/domain/claim";23 import { DecisionSubject } from "@repo/protocol/domain/decision";24 import { Outcome } from "@repo/protocol/domain/outcome";25 import type {26 ImportSource,5 unmodified lines32 import { receiptLine } from "@repo/protocol/render";33 import { DateTime, Option, Result, Schema } from "effect";34 import type { Rpc } from "effect/rpc";35 36+import { parseRemote, parseRepoName } from "./repo-context.ts";37+import type { Remote } from "./repo-context.ts";38+39 const short = (sha: string) => sha.slice(0, 7);40 41 const when = (at: DateTime.Utc) => DateTime.formatIso(at);42 154 unmodified lines197 );198 199 const ask = viewOf(ShowAsk.successSchema, ({ brief }) => prose(brief));200 197-const claim = viewOf(Claim.successSchema, ({ claim: held }) => {201+/** Where the receipt is read: in a clone of the project or not, and what the fork's remote may be called. */202+export interface Place {203+ readonly inClone: boolean;204+ readonly remoteName: string;205+ /** False when a remote of that name already points at the fork. */206+ readonly addRemote: boolean;207+}208+209+const sameProject = (held: ClaimView, url: string) =>210+ Option.exists(parseRemote(url), ({ repo }) =>211+ Option.exists(parseRepoName(repo), (ref) => ref.project === held.project)212+ );213+214+/** Outside a repo, `remotes` is empty, so the receipt starts with a clone. */215+export const placeOf = (held: ClaimView, remotes: readonly Remote[]): Place => {216+ const named = remotes.find(({ name }) => name === Brand.slug);217+218+ if (named === undefined) {219+ return {220+ addRemote: true,221+ inClone: remotes.some(({ url }) => sameProject(held, url)),222+ remoteName: Brand.slug,223+ };224+ }225+226+ return named.url === held.remote227+ ? { addRemote: false, inClone: true, remoteName: Brand.slug }228+ : {229+ addRemote: true,230+ inClone: remotes.some(({ url }) => sameProject(held, url)),231+ remoteName: `${Brand.slug}-${held.ask}`,232+ };233+};234+235+const cloneOf = (held: ClaimView) =>236+ Option.map(parseRemote(held.remote), ({ origin, repo }) => {237+ const [canonical = repo] = repo.split("--");238+ const folder = canonical.slice(canonical.lastIndexOf("/") + 1);239+240+ return `git clone ${origin}/${canonical}.git && cd ${folder}`;241+ });242+243+export const claimReceipt = (held: ClaimView, place: Place): View => {244 const steps = [199- `git remote add ${Brand.slug} ${held.remote}`,245+ ...(place.inClone ? [] : Option.toArray(cloneOf(held))),246+ ...(place.addRemote247+ ? [`git remote add ${place.remoteName} ${held.remote}`]248+ : []),249+ `git fetch ${place.remoteName}`,250 `${Brand.cli} check`,201- `git push ${Brand.slug} HEAD:main`,251+ `git push ${place.remoteName} HEAD:main`,252 ];253 254 return {255 markdown: [15 unmodified lines271 "Next:",272 ...steps.map((step) => ` ${step}`),273 ].join("\n"),274 };225-});275+};276 277+export const isClaimed = Schema.is(Claim.successSchema);278+279 const status = viewOf(Status.successSchema, ({ answers, claims, handle }) =>280 joined(281 prose(`Signed in as ${handle}.`),282 prose("Claims:"),284 unmodified lines567 isReceipt(success) && Outcome.guards.Refused(success.outcome)568 ? success.outcome.refusals569 : [];570 571+/** `claim`'s receipt looks at the repo it is printed in, so the CLI's surfaces add it. */572 export const views = {520- claim,573 credits,574 finish: finished,575 frontPage: front,576 ledger,16 unmodified linesmodified:apps/cli/src/repo-context.ts+10 added-5 removed
94 unmodified lines95 ? Option.some({ origin, repo })96 : Option.none();97 });98 99+export interface Remote {100+ readonly name: string;101+ readonly url: string;102+}103+104 export interface RepoContext {105 readonly root: string;101- readonly remote: Option.Option<{102- readonly name: string;103- readonly url: string;104- }>;106+ readonly remote: Option.Option<Remote>;107+ /** Every remote the repo has, as `git remote -v` lists them. */108+ readonly remotes: readonly Remote[];109 readonly origin: Option.Option<string>;110 readonly repo: Option.Option<RepoRef>;111 }112 29 unmodified lines142 return { exitCode, stdout };143 })144 );145 142-const remotesOf = (listing: string) =>146+const remotesOf = (listing: string): readonly Remote[] =>147 listing.split("\n").flatMap((line) => {148 const match = /^(?<name>\S+)\t(?<url>\S+) \(fetch\)$/u.exec(line);149 150 return match?.groups?.name === undefined || match.groups.url === undefined40 unmodified lines191 192 return {193 origin: Option.map(parsed, ({ origin }) => origin),194 remote,195+ remotes,196 repo: Option.flatMap(parsed, ({ repo }) => parseRepoName(repo)),197 root: top.stdout.trim(),198 };199 }).pipe(2 unmodified linesmodified:apps/cli/src/surfaces.ts+26 added-4 removed
7 unmodified lines8 Contracts,9 surfaced,10 Surfaces,11 } from "@repo/protocol/contracts";12+import type { Contract } from "@repo/protocol/contracts";13 import { toToolkit } from "@repo/protocol/mcp";14 import {15 briefResources,16 skillIn,13 unmodified lines30 } from "effect";31 import { McpProtocol, McpServer } from "effect/ai";32 import { Argument, Command, Flag } from "effect/cli";33 import type { ChildProcessSpawner } from "effect/process";34+import type { Rpc } from "effect/rpc";35 36 import { local } from "./local/index.ts";37 import { Output } from "./output.ts";36-import { refusalsIn, views } from "./render.ts";38+import {39+ claimReceipt,40+ isClaimed,41+ placeOf,42+ refusalsIn,43+ views,44+} from "./render.ts";45 import { repoContext } from "./repo-context.ts";46 import { today } from "./tui/command.ts";47 import { cliVersion } from "./version.ts";48 22 unmodified lines71 readonly path: readonly [string, ...string[]];72 readonly command: Command.Command.Any;73 }74 67-/** `env set` reads the value from stdin so it never passes through an argument list or a transcript. */68-const wrapped = ["initProject", "setEnv", "today"];75+/** `env set` reads the value from stdin so it never passes through an argument list or a transcript; `ask open` reads its files from the working tree. */76+const wrapped = ["initProject", "openAsk", "setEnv", "today"];77 78+const remotesHere = Effect.map(79+ Effect.option(Effect.flatMap(WorkingDirectory, repoContext)),80+ Option.match({ onNone: () => [], onSome: ({ remotes }) => remotes })81+);82+83+const claim = (success: Rpc.Success<Contract>) =>84+ isClaimed(success)85+ ? Effect.map(remotesHere, (remotes) =>86+ Option.some(87+ claimReceipt(success.claim, placeOf(success.claim, remotes))88+ )89+ )90+ : Effect.succeedNone;91+92 const projected = toCommands(Contracts, Effect.service(Client), {93 defaults: fromRepoContext,94 exclude: wrapped,95 output: Effect.service(Output),96 refusalsIn,75- views,97+ views: { ...views, claim },98 });99 100 const groups = new Map([101 ["env", "Read a project's env shape, or set a write-only value."],195 unmodified linesadded:apps/cli/test/local/ask-open.test.ts+299 added
1+import { NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { Brand } from "@repo/brand";4+import { Client, Contracts } from "@repo/protocol/contracts";5+import type { OpenAsk } from "@repo/protocol/contracts";6+import { Ask } from "@repo/protocol/domain/ask";7+import { CheckSpec } from "@repo/protocol/domain/check";8+import { Envelope } from "@repo/protocol/envelope";9+import { LandedSha, RepoPath } from "@repo/protocol/ids";10+import { NotRedFirst } from "@repo/protocol/refusal";11+import { asTester, unanswered } from "@repo/protocol/testing";12+import { gitOk } from "@repo/testkit/git";13+import {14+ Cause,15+ Effect,16+ Exit,17+ FileSystem,18+ Layer,19+ Path,20+ Ref,21+ Runtime,22+ Schema,23+} from "effect";24+import { CliOutput } from "effect/cli";25+import { ChildProcess, ChildProcessSpawner } from "effect/process";26+import { RpcTest } from "effect/rpc";27+import { TestConsole } from "effect/testing";28+29+import { program } from "../../src/main.ts";30+import { OutputPlain } from "../../src/output.ts";31+import { SignedOut } from "../signed-out.ts";32+33+const PROJECT = "oscabriel/demo";34+35+const ASK = "fix-a";36+37+const ASK_FILE = `${Brand.configDir}/asks/${ASK}.ask.ts`;38+39+const CHECK = `test/asks/${ASK}.test.ts`;40+41+const askText = [42+ `import { kinds, territory } from "${Brand.cliPackage}/rules";`,43+ "",44+ "export default kinds.fix.ask({",45+ ` path: "${CHECK}",`,46+ ' territory: territory.paths("src/a.ts"),',47+ ' want: "a is two",',48+ "});",49+ "",50+].join("\n");51+52+const checkText = 'it("is two", () => expect(a).toBe(2));\n';53+54+const landed = LandedSha.make("5555555555555555555555555555555555555555");55+56+const opened: typeof OpenAsk.successSchema.Type = {57+ ask: Schema.decodeSync(Ask)({58+ askedBy: "oscabriel",59+ blockedBy: [],60+ brief: { want: "a is two" },61+ check: Schema.encodeSync(CheckSpec)(62+ CheckSpec.cases.RedThenGreen.make({ path: RepoPath.make(CHECK) })63+ ),64+ file: ASK_FILE,65+ id: ASK,66+ kind: "fix",67+ openedAt: "2026-10-07T12:00:00.000Z",68+ openedIn: landed,69+ project: PROJECT,70+ state: "open",71+ territory: { module: ".", paths: ["src/a.ts"] },72+ }),73+ landed,74+};75+76+const aRepo = (files: Readonly<Record<string, string>>) =>77+ Effect.gen(function* () {78+ const fs = yield* FileSystem.FileSystem;79+ const path = yield* Path.Path;80+ const repo = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());81+82+ yield* gitOk(repo, "init", "--quiet", "--initial-branch=main");83+84+ for (const [file, content] of Object.entries(files)) {85+ yield* fs.makeDirectory(path.dirname(path.join(repo, file)), {86+ recursive: true,87+ });88+ yield* fs.writeFileString(path.join(repo, file), content);89+ }90+91+ return repo;92+ });93+94+const startedIn = (repo: string) =>95+ Layer.effect(ChildProcessSpawner.ChildProcessSpawner)(96+ Effect.gen(function* () {97+ const real = yield* ChildProcessSpawner.ChildProcessSpawner;98+ const path = yield* Path.Path;99+100+ return ChildProcessSpawner.make((command) =>101+ real.spawn(102+ ChildProcess.isStandardCommand(command)103+ ? ChildProcess.make(command.command, command.args, {104+ ...command.options,105+ cwd: path.resolve(repo, command.options.cwd ?? "."),106+ })107+ : command108+ )109+ );110+ })111+ ).pipe(Layer.provide(NodeServices.layer));112+113+const aPlatform = (114+ reply: Effect.Effect<typeof OpenAsk.successSchema.Type, NotRedFirst>115+) =>116+ Effect.map(Ref.make<readonly unknown[]>([]), (calls) => ({117+ calls: Ref.get(calls),118+ layer: Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(119+ Layer.provide([120+ Layer.mergeAll(121+ unanswered,122+ Contracts.toLayerHandler("openAsk", (payload) =>123+ Effect.andThen(124+ Ref.update(calls, (all) => [...all, payload]),125+ reply126+ )127+ )128+ ),129+ asTester,130+ ])131+ ),132+ }));133+134+const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>135+ Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));136+137+const cli = (138+ repo: string,139+ platform: Layer.Layer<Client>,140+ argv: readonly string[]141+) =>142+ Effect.gen(function* () {143+ const exit = yield* Effect.exit(program(argv));144+145+ return {146+ code: exitCodeOf(exit),147+ err: (yield* TestConsole.errorLines).flatMap((chunk) =>148+ String(chunk).split("\n")149+ ),150+ out: (yield* TestConsole.logLines).map(String),151+ };152+ }).pipe(153+ Effect.provide(154+ Layer.mergeAll(155+ NodeServices.layer,156+ TestConsole.layer,157+ CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),158+ OutputPlain,159+ platform,160+ SignedOut,161+ startedIn(repo)162+ )163+ )164+ );165+166+const decodeEnvelope = Schema.decodeEffect(167+ Schema.fromJsonString(Envelope(Schema.Unknown))168+);169+170+const argv = ["ask", "open", ASK, "--project", PROJECT, "--yes", "--json"];171+172+describe(`${Brand.cli} ask open`, () => {173+ it.live(174+ "reads the ask file and the check it names from the working tree, and sends both",175+ () =>176+ Effect.gen(function* () {177+ const repo = yield* aRepo({ [ASK_FILE]: askText, [CHECK]: checkText });178+ const platform = yield* aPlatform(Effect.succeed(opened));179+ const ran = yield* cli(repo, platform.layer, argv);180+181+ expect(ran.code).toBe(0);182+ expect(yield* platform.calls).toStrictEqual([183+ {184+ ask: ASK,185+ files: [186+ { content: askText, path: ASK_FILE },187+ { content: checkText, path: CHECK },188+ ],189+ project: PROJECT,190+ },191+ ]);192+193+ const envelope = yield* decodeEnvelope(ran.out.join("\n"));194+195+ expect(envelope).toMatchObject({196+ command: "ask open",197+ data: { landed },198+ ok: true,199+ });200+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),201+ { timeout: 30_000 }202+ );203+204+ it.live(205+ "takes --files over the working tree, reading nothing",206+ () =>207+ Effect.gen(function* () {208+ const repo = yield* aRepo({});209+ const platform = yield* aPlatform(Effect.succeed(opened));210+211+ const given = [{ content: "given", path: ASK_FILE }];212+213+ const ran = yield* cli(repo, platform.layer, [214+ ...argv,215+ "--files",216+ JSON.stringify(given),217+ ]);218+219+ expect(ran.code).toBe(0);220+ expect(yield* platform.calls).toStrictEqual([221+ { ask: ASK, files: given, project: PROJECT },222+ ]);223+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),224+ { timeout: 30_000 }225+ );226+227+ it.live.each([228+ {229+ files: {},230+ names: ASK_FILE,231+ what: "no ask file",232+ },233+ {234+ files: { [ASK_FILE]: askText.replace(` path: "${CHECK}",\n`, "") },235+ names: "names no check",236+ what: "an ask file naming no path",237+ },238+ {239+ files: { [ASK_FILE]: askText },240+ names: CHECK,241+ what: "a check the tree lacks",242+ },243+ ])(244+ "with $what, exits 2 naming what is missing, and calls nothing",245+ ({ files, names }) =>246+ Effect.gen(function* () {247+ const repo = yield* aRepo(files);248+ const platform = yield* aPlatform(Effect.succeed(opened));249+ const ran = yield* cli(repo, platform.layer, argv);250+251+ expect({252+ calls: yield* platform.calls,253+ code: ran.code,254+ said: ran.err.filter((line) => line.includes(names)).length,255+ }).toStrictEqual({ calls: [], code: 2, said: 1 });256+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),257+ { timeout: 30_000 }258+ );259+260+ it.live(261+ "prints the platform's refusal with its tag and exits as a refusal does",262+ () =>263+ Effect.gen(function* () {264+ const repo = yield* aRepo({ [ASK_FILE]: askText, [CHECK]: checkText });265+266+ const platform = yield* aPlatform(Effect.fail(new NotRedFirst({})));267+268+ const ran = yield* cli(repo, platform.layer, argv);269+270+ expect(ran.code).not.toBe(0);271+ expect(ran.out.join("\n")).toContain("NotRedFirst");272+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),273+ { timeout: 30_000 }274+ );275+276+ it.live(277+ "without --yes exits 2 naming --yes, and reads and calls nothing",278+ () =>279+ Effect.gen(function* () {280+ const repo = yield* aRepo({});281+ const platform = yield* aPlatform(Effect.succeed(opened));282+283+ const ran = yield* cli(repo, platform.layer, [284+ "ask",285+ "open",286+ ASK,287+ "--project",288+ PROJECT,289+ ]);290+291+ expect({292+ calls: yield* platform.calls,293+ code: ran.code,294+ said: ran.err.filter((line) => line.includes("--yes")).length,295+ }).toStrictEqual({ calls: [], code: 2, said: 1 });296+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),297+ { timeout: 30_000 }298+ );299+});modified:apps/cli/test/local/init.test.ts+127 added-5 removed
313 unmodified lines314 remote: machine.remote,315 remotes: Brand.slug,316 staged: "notes.md",317 });318+ expect({319+ kept: ran.err.filter((line) => line.includes("kept")),320+ subject: (yield* gitOk(321+ machine.repo,322+ "log",323+ "-1",324+ "--format=%s"325+ )).includes(CONFIG),326+ }).toStrictEqual({ kept: [], subject: true });327+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),328+ { timeout: 30_000 }329+ );330+331+ it.live(332+ "ends with the project's address and the next step: an ask file, its test and ask open",333+ () =>334+ Effect.gen(function* () {335+ const machine = yield* aMachine;336+ const gateway = "https://platform.example.test/oscabriel/demo.git";337+338+ const platform = yield* aPlatform(339+ Effect.succeed({340+ project: ProjectName.make("oscabriel/demo"),341+ remote: gateway,342+ })343+ );344+345+ const ran = yield* cli(machine, platform.layer, [346+ "init",347+ "--project",348+ "oscabriel/demo",349+ "--yes",350+ "--no-push",351+ ]);352+353+ expect(ran.code).toBe(0);354+355+ const said = ran.out.join("\n");356+357+ expect(said).toContain("https://platform.example.test/oscabriel/demo");358+ expect(said).toContain(359+ `Next: write an ask in ${Brand.configDir}/asks/<ask>.ask.ts`360+ );361+ expect(said).toContain(`${Brand.cli} ask open <ask>`);362+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),363+ { timeout: 30_000 }364+ );365+366+ it.live(367+ "warns that red-first asks need a test command with {path} when it writes run.fromCI",368+ () =>369+ Effect.gen(function* () {370+ const fs = yield* FileSystem.FileSystem;371+ const path = yield* Path.Path;372+ const machine = yield* aMachine;373+374+ yield* fs.writeFileString(375+ path.join(machine.repo, "package.json"),376+ JSON.stringify({377+ name: "oscabriel/demo",378+ scripts: { lint: "oxlint" },379+ })380+ );381+ yield* gitOk(machine.repo, "commit", "--quiet", "-am", "No tests");382+383+ const platform = yield* aPlatform(created(machine));384+385+ const ran = yield* cli(machine, platform.layer, [386+ "init",387+ "--project",388+ "oscabriel/demo",389+ "--yes",390+ "--json",391+ ]);392+393+ expect(ran.code).toBe(0);394 expect(319- yield* gitOk(machine.repo, "log", "-1", "--format=%s")320- ).toContain(CONFIG);395+ ran.err.filter(396+ (line) => line.includes("{path}") && line.includes("run.fromCI")397+ )398+ ).toHaveLength(1);399+ expect((yield* state(machine)).config).toStrictEqual(400+ Option.some(expect.stringContaining("run: run.fromCI"))401+ );402 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),403 { timeout: 30_000 }404 );405 211 unmodified lines617 "--name-only",618 "--format=",619 "HEAD"620 ),621+ kept: ran.err.filter((line) => line.includes("kept")),622 onPlatform: (yield* git(machine.bare, "show", `main:${CONFIG}`))623 .stdout,542- }).toStrictEqual({ committed: CONFIG, onPlatform: mine });624+ }).toStrictEqual({ committed: CONFIG, kept: [], onPlatform: mine });625 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),626 { timeout: 30_000 }627 );628 312 unmodified lines941 { timeout: 30_000 }942 );943 944 it.live(863- "names an import from a known host by its source path, and any other by the handle",945+ "names an import under the handle, after the URL's last segment, whatever its host",946 () =>947 Effect.gen(function* () {948 const known = yield* importSends(949 "bob",6 unmodified lines956 "https://example.test/acme/widgets.git",957 []958 );959 878- expect(known).toStrictEqual(["github.com/pallets/click"]);960+ expect(known).toStrictEqual(["bob/click"]);961 expect(other).toStrictEqual(["bob/widgets"]);962 }),963 { timeout: 30_000 }964 );965 966 it.live(967+ "keeps the source namespace when --project spells it, or when no handle is known",968+ () =>969+ Effect.gen(function* () {970+ const spelled = yield* importSends(971+ "bob",972+ "https://github.com/pallets/click",973+ ["--project", "github.com/pallets/click"]974+ );975+976+ const machine = yield* aMachine;977+978+ const platform = yield* aPlatform(979+ Effect.succeed({980+ project: ProjectName.make("github.com/pallets/click"),981+ remote:982+ "https://platform.example.test/github.com/pallets/click.git",983+ })984+ );985+986+ yield* cli(machine, platform.layer, [987+ "init",988+ "--import",989+ "https://github.com/Pallets/click.git",990+ "--yes",991+ "--json",992+ ]);993+994+ const unknown = (yield* decodeCalls(yield* platform.calls)).map(995+ ({ project }) => project996+ );997+998+ expect({ spelled, unknown }).toStrictEqual({999+ spelled: ["github.com/pallets/click"],1000+ unknown: ["github.com/pallets/click"],1001+ });1002+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),1003+ { timeout: 30_000 }1004+ );1005+1006+ it.live(1007 "refuses a bare --project with no handle known, a usage error naming the full form",1008 () =>1009 Effect.gen(function* () {1010 const machine = yield* aMachine;18 unmodified linesmodified:apps/cli/test/local/login.test.ts+4 added-1 removed
290 unmodified lines291 292 const { stderr, stdout } = yield* printed;293 294 expect(stdout.map((line) => line.trim())).toStrictEqual(295- expect.arrayContaining(helperLines(url))295+ expect.arrayContaining([296+ ...helperLines(url),297+ `Next: ${Brand.cli} front to find an ask, or ${Brand.cli} init --project alice/<name> in a repo of yours.`,298+ ])299 );300 expect([...stdout, ...stderr].join("\n")).not.toContain(given);301 }).pipe(Effect.scoped, Effect.provide(testServices)),302 30_000473 unmodified linesmodified:apps/cli/test/local/project-file.test.ts+45 added-2 removed
37 unmodified lines38 "skipped .github/workflows/broken.yml: not YAML",39 ],40 } as const;41 42+const vouch = [43+ ' // Anyone not denounced in vouched.td may claim an ask; "forCode" admits',44+ " // only the people vouched for there, which a maintainer lands with vouch.",45+ ' vouch: "bansOnly",',46+];47+48+const asksTrap = [49+ " // An open ask's test fails on main until it is answered, so the suite",50+ " // every answer must keep green leaves the asks' tests to their own lane.",51+];52+53 describe("the proposed project file", () => {43- it("writes each command the finder found, with where it was found", () => {54+ it("writes each command the finder found, with where it was found, the unit lane without the asks' tests, and a vouch mode anyone may claim under", () => {55 expect(projectFile(found.run, found.sources)).toBe(56 [57 `import { project } from "${Brand.cliPackage}/rules";`,58 "",6 unmodified lines65 " // test from package.json",66 ` test: "vitest run {path}",`,67 " checks: {",68 " // checks.unit from package.json",58- ` unit: "bun run test",`,69+ ...asksTrap,70+ ` unit: "vitest run --exclude 'test/asks/**'",`,71 " // checks.lint from package.json",72 ` lint: "bun run lint",`,73 " // checks.types from package.json",74 ` types: "bun run typecheck",`,75 " },",76 " },",77+ ...vouch,78 "});",79 "",80 ].join("\n")81 );82 });83 84+ it("appends the skip to a unit lane that calls the runner itself, keeping its flags", () => {85+ expect(86+ projectFile(87+ { checks: { unit: "bun test --coverage" }, test: "bun test {path}" },88+ []89+ )90+ ).toContain(91+ ` unit: "bun test --coverage --path-ignore-patterns='test/asks/**'",`92+ );93+ expect(94+ projectFile({ checks: { unit: "npm test" }, test: "npx jest {path}" }, [])95+ ).toContain(96+ ` unit: "npx jest --testPathIgnorePatterns 'test/asks/'",`97+ );98+ });99+100+ it("explains the trap instead when the runner's skip flag is unknown", () => {101+ const text = projectFile(102+ { checks: { unit: "cargo test" }, test: "cargo test {path}" },103+ []104+ );105+106+ expect(text).toContain(` unit: "cargo test",`);107+ expect(text).toContain("skips test/asks/**");108+ expect(text).not.toContain("--exclude");109+ });110+111 it("is the same text for the same commands, in whatever order the keys come", () => {112 // `checks` moves from first to last.113 const { checks, ...rest } = found.run;114 const reordered = { ...rest, checks };12 unmodified lines127 "// the platform reads the run block from CI at each landing. It found:",128 `// setup: "npm install" (setup inferred from package.json)`,129 `// checks.lint: "npm run lint" (checks.lint from package.json)`,130 "// skipped .github/workflows/broken.yml: not YAML",131+ "// A red-first ask needs a test command with {path}; once one is here, give the unit",132+ "// lane the runner's flag that skips test/asks/**, or every answer's unit lane is red while another ask is open.",133 "export default project({",134 " run: run.fromCI,",135+ ...vouch,136 "});",137 "",138 ].join("\n")139 );122 unmodified linesmodified:apps/cli/test/build.test.ts+1 added-1 removed
148 unmodified lines149 const spawning = { timeout: 60_000 };150 151 const banner = [152 "Start here:",153- `${Brand.cli} asks list the open asks you could take`,153+ `${Brand.cli} front list the open asks across every project`,154 `${Brand.cli} claim take one; you get a fork to push your answer to`,155 `${Brand.cli} check run the gate's checks locally before you push`,156 ];157 366 unmodified linesadded:apps/cli/test/claim-receipt.test.ts+195 added
1+import { NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { Brand } from "@repo/brand";4+import { Contracts } from "@repo/protocol/contracts";5+import { ClaimView } from "@repo/protocol/domain/claim";6+import { keyOf, ProjectName } from "@repo/protocol/ids";7+import { unanswered } from "@repo/protocol/testing";8+import { gitOk } from "@repo/testkit/git";9+import { Effect, FileSystem, Layer, Schema } from "effect";10+11+import { claimReceipt, placeOf } from "../src/render.ts";12+import { runProgram } from "./remote-server.ts";13+14+const platform = "https://platform.example.dev";15+16+const project = "oscabriel/datekit";17+18+const ask = "fix-week";19+20+const fork = `${platform}/${project}--${ask}--alice.git`;21+22+const held = Schema.decodeUnknownSync(ClaimView)({23+ ask,24+ base: "4444444444444444444444444444444444444444",25+ checkCommand: "bun test test/asks/fix-week.test.ts",26+ claimant: "alice",27+ fork: `${keyOf(ProjectName.make(project))}--${ask}--alice`,28+ lapsesAt: "2026-10-08T12:00:00.000Z",29+ openedAt: "2026-10-07T12:00:00.000Z",30+ project,31+ remote: fork,32+ state: "live",33+ warnsAt: "2026-10-07T14:00:00.000Z",34+});35+36+const stepsOf = (text: string | undefined) =>37+ (text ?? "")38+ .split("\n")39+ .filter((line) => line.startsWith(" "))40+ .map((line) => line.trim());41+42+describe(placeOf, () => {43+ it("outside any clone of the project, starts with a clone and names the remote by the brand", () => {44+ expect(placeOf(held, [])).toStrictEqual({45+ addRemote: true,46+ inClone: false,47+ remoteName: Brand.slug,48+ });49+ expect(50+ placeOf(held, [51+ { name: "origin", url: "https://github.com/someone/other.git" },52+ ])53+ ).toStrictEqual({54+ addRemote: true,55+ inClone: false,56+ remoteName: Brand.slug,57+ });58+ });59+60+ it("in a clone of the project, or of one of its forks, clones nothing", () => {61+ expect(62+ placeOf(held, [{ name: "origin", url: `${platform}/${project}.git` }])63+ .inClone64+ ).toBeTruthy();65+ expect(66+ placeOf(held, [67+ { name: "origin", url: `${platform}/${project}--me--bob.git` },68+ ]).inClone69+ ).toBeTruthy();70+ });71+72+ it("names the remote after the ask when one of the brand's name already points elsewhere", () => {73+ expect(74+ placeOf(held, [75+ { name: "origin", url: `${platform}/${project}.git` },76+ { name: Brand.slug, url: `${platform}/${project}.git` },77+ ])78+ ).toStrictEqual({79+ addRemote: true,80+ inClone: true,81+ remoteName: `${Brand.slug}-${ask}`,82+ });83+ });84+85+ it("adds no remote when the brand's already points at the fork", () => {86+ expect(placeOf(held, [{ name: Brand.slug, url: fork }])).toStrictEqual({87+ addRemote: false,88+ inClone: true,89+ remoteName: Brand.slug,90+ });91+ });92+});93+94+describe(claimReceipt, () => {95+ it("outside a clone: clone, add the remote, fetch, check, push", () => {96+ expect(97+ stepsOf(98+ claimReceipt(held, {99+ addRemote: true,100+ inClone: false,101+ remoteName: Brand.slug,102+ }).text103+ )104+ ).toStrictEqual([105+ `git clone ${platform}/${project}.git && cd datekit`,106+ `git remote add ${Brand.slug} ${fork}`,107+ `git fetch ${Brand.slug}`,108+ `${Brand.cli} check`,109+ `git push ${Brand.slug} HEAD:main`,110+ ]);111+ });112+113+ it("in a clone whose brand remote points elsewhere: the ask's own remote, no clone", () => {114+ expect(115+ stepsOf(116+ claimReceipt(held, {117+ addRemote: true,118+ inClone: true,119+ remoteName: `${Brand.slug}-${ask}`,120+ }).text121+ )122+ ).toStrictEqual([123+ `git remote add ${Brand.slug}-${ask} ${fork}`,124+ `git fetch ${Brand.slug}-${ask}`,125+ `${Brand.cli} check`,126+ `git push ${Brand.slug}-${ask} HEAD:main`,127+ ]);128+ });129+130+ it("puts the same steps in the markdown's shell block", () => {131+ const view = claimReceipt(held, {132+ addRemote: false,133+ inClone: true,134+ remoteName: Brand.slug,135+ });136+137+ expect(view.markdown).toContain(138+ ["```sh", `git fetch ${Brand.slug}`, `${Brand.cli} check`].join("\n")139+ );140+ expect(view.markdown).not.toContain("git clone");141+ });142+});143+144+const claiming = Layer.mergeAll(145+ unanswered,146+ Contracts.toLayerHandler("claim", () => Effect.succeed({ claim: held }))147+);148+149+describe(`${Brand.cli} claim's receipt`, () => {150+ it.live("reads the repo it is printed in", () =>151+ Effect.gen(function* () {152+ const fs = yield* FileSystem.FileSystem;153+ const outside = yield* fs.makeTempDirectoryScoped();154+ const clone = yield* fs.makeTempDirectoryScoped();155+156+ yield* gitOk(clone, "init", "--quiet");157+ yield* gitOk(158+ clone,159+ "remote",160+ "add",161+ "origin",162+ `${platform}/${project}.git`163+ );164+ yield* gitOk(165+ clone,166+ "remote",167+ "add",168+ Brand.slug,169+ `${platform}/${project}.git`170+ );171+172+ const argv = ["claim", ask, "--project", project];173+174+ const away = yield* runProgram(argv, {175+ cwd: outside,176+ handlers: claiming,177+ });178+179+ const inside = yield* runProgram(argv, {180+ cwd: clone,181+ handlers: claiming,182+ });183+184+ expect({185+ away: away.out186+ .join("\n")187+ .includes(`git clone ${platform}/${project}.git`),188+ inside: inside.out189+ .join("\n")190+ .includes(`git push ${Brand.slug}-${ask} HEAD:main`),191+ insideClones: inside.out.join("\n").includes("git clone"),192+ }).toStrictEqual({ away: true, inside: true, insideClones: false });193+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))194+ );195+});modified:apps/cli/test/main.test.ts+36 added-3 removed
1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Brand } from "@repo/brand";4 import { Client } from "@repo/protocol/contracts";5-import { Effect, Layer } from "effect";5+import { Effect, FileSystem, Layer } from "effect";6 import { CliOutput, Command } from "effect/cli";7 import { TestConsole } from "effect/testing";8 9 import { Credentials } from "../src/credentials.ts";10-import { root } from "../src/main.ts";10+import { program, root } from "../src/main.ts";11 import { OutputPlain } from "../src/output.ts";12+import { WorkingDirectory } from "../src/surfaces.ts";13+import { SignedOut } from "./signed-out.ts";14 15 const printed = Effect.map(TestConsole.logLines, (all) =>16 all.flatMap((chunk) => String(chunk).split("\n"))17 );25 unmodified lines43 return trimmed.length > 0 ? [trimmed] : [];44 });45 };46 47+describe(`${Brand.cli} asks outside a clone`, () => {48+ it.live(49+ "says which flag it needs, and that front lists every project's",50+ () =>51+ Effect.gen(function* () {52+ const fs = yield* FileSystem.FileSystem;53+ const dir = yield* fs.makeTempDirectoryScoped();54+55+ yield* Effect.exit(program(["asks"])).pipe(56+ Effect.provideService(WorkingDirectory, dir)57+ );58+59+ const said = (yield* TestConsole.errorLines).map(String).join("\n");60+61+ expect(said).toContain("asks needs --project");62+ expect(said).toContain(`${Brand.cli} front lists every project's`);63+ }).pipe(64+ Effect.scoped,65+ Effect.provide(66+ Layer.mergeAll(67+ TestConsole.layer,68+ CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),69+ Layer.mock(Client)({}),70+ SignedOut,71+ OutputPlain72+ ).pipe(Layer.provideMerge(NodeServices.layer))73+ )74+ )75+ );76+});77+78 describe(`${Brand.cli} --help`, () => {79 it.effect("opens with the start-here banner, before the command list", () =>80 Effect.gen(function* () {81 const lines = yield* help;82 83 expect(section(lines, "DESCRIPTION")).toStrictEqual([84 "Start here:",52- `${Brand.cli} asks list the open asks you could take`,85+ `${Brand.cli} front list the open asks across every project`,86 `${Brand.cli} claim take one; you get a fork to push your answer to`,87 `${Brand.cli} check run the gate's checks locally before you push`,88 ]);89 expect(lines.indexOf("DESCRIPTION")).toBeLessThan(31 unmodified linesmodified:apps/cli/test/repo-context.test.ts+1 added
151 unmodified lines152 153 expect(context).toStrictEqual({154 origin: Option.some(platform),155 remote: Option.some({ name: "origin", url }),156+ remotes: [{ name: "origin", url }],157 repo: Option.some({158 ask: AskId.make("fix-week"),159 handle: Handle.make("alice"),160 kind: "claim",40 unmodified linesmodified:apps/cli/test/surfaces.test.ts+3 added-3 removed
186 unmodified lines187 );188 189 const paths = entries.map(({ path: words }) => words.join(" "));190 191- // `init` and `env set` are the local commands that wrap their contracts.192- expect(paths).toHaveLength(onCli.length - 2 + local.length + 1);191+ // `init`, `env set` and `ask open` are the local commands that wrap their contracts.192+ expect(paths).toHaveLength(onCli.length - 3 + local.length + 1);193 expect(new Set(paths).size).toBe(paths.length);194 expect(paths).toStrictEqual(195 expect.arrayContaining([196 "asks",8 unmodified lines205 );206 });207 208 it("puts ask open, ask draft and ask flag under ask, and env shape beside env set", () => {209- expect(subcommandsOf(top("ask"))).toStrictEqual(["open", "draft", "flag"]);209+ expect(subcommandsOf(top("ask"))).toStrictEqual(["draft", "flag", "open"]);210 expect(subcommandsOf(top("env"))).toStrictEqual(["shape", "set"]);211 });212 213 it("leaves init and env set to their local commands", () => {413 unmodified linesmodified:apps/web/src/features/import/import-form.tsx+1 added-1 removed
173 unmodified lines174 return "The address names it: the project keeps its source's account.";175 }176 177 return choices.length > 1178- ? "The URL's own account, or your handle."178+ ? "Your handle, or the URL's own account, which keeps the source's name."179 : "Your handle: this URL's host is not one a project may be owned by.";180 };181 182 const NameHint = ({216 unmodified linesmodified:apps/web/src/features/import/prefill.ts+2 added-1 removed
41 unmodified lines42 43 export const ownerOfHandle = (handle: Handle): Option.Option<Owner> =>44 decodeOwner(handle.toLowerCase());45 46+/** The handle first, so an import is the importer's own by default; the source namespace stays on offer. */47 export const ownerChoices = (48 handle: Option.Option<Handle>,49 url: string50 ): readonly Owner[] =>51 Array.dedupe([51- ...Option.toArray(Option.flatMap(prefillFrom(url).owner, ownerOfNamespace)),52 ...Option.toArray(Option.flatMap(handle, ownerOfHandle)),53+ ...Option.toArray(Option.flatMap(prefillFrom(url).owner, ownerOfNamespace)),54 ]);55 56 export const sourceUrlOf = (project: ProjectName) => `https://${project}`;57 22 unmodified linesmodified:apps/web/test/import.test.tsx+5 added-7 removed
87 unmodified lines88 const markup = signedIn();89 90 expect(inputNamed(markup, "url")).toContain(`value="${CLICK}"`);91 expect(inputNamed(markup, "branch")).toContain('value=""');92- expect(inputNamed(markup, "owner")).toContain('value="github.com/pallets"');92+ expect(inputNamed(markup, "owner")).toContain('value="oscabriel"');93 expect(inputNamed(markup, "name")).toContain('value="click"');94 expect(markup).toMatch(/<button[^>]*type="submit"[^>]*>Import<\/button>/u);95 });96 50 unmodified lines147 });148 });149 150 describe(ownerChoices, () => {151- it("puts the source namespace first when the host is on the list, then the handle", () => {151+ it("puts the handle first, then the source namespace when the host is on the list", () => {152 expect(ownerChoices(oscabriel, CLICK)).toStrictEqual([153- "github.com/pallets",153 "oscabriel",154+ "github.com/pallets",155 ]);156 });157 158 it("offers the handle alone when the host is not on the list", () => {274 unmodified lines433 434 yield* Effect.tryPromise(() => router.load());435 436 expect(sent).toStrictEqual([437- { import: { url: CLICK }, project: "github.com/pallets/click" },437+ { import: { url: CLICK }, project: "oscabriel/click" },438 ]);439 // Where the hook's `navigate` goes: a router with no window to440 // move only builds the location, as `navigate` does first.441- expect(router.buildLocation(to).publicHref).toBe(442- "/github.com/pallets/click"443- );441+ expect(router.buildLocation(to).publicHref).toBe("/oscabriel/click");442 })443 );444 445 it.live("draws a refusal as the platform gave it, under the form", () =>23 unmodified linesmodified:packages/agent-kit/src/docs/run-a-project.ts+2 added-2 removed
13 unmodified lines14 `In a repo of your own, ${cli("init --project <owner>/<name>")} makes it a project: it finds the repo's checks (its test and lint commands, and its CI), writes the config folder, ${code(`${dir}/`)}, and pushes. You are the project's first maintainer.`,15 "",16 "## How a project is named",17 "",18- `A project's name is its owner, then a short name: ${code("<owner>/<name>")}, as in ${code("oscabriel/datekit")}. The name is the project's address everywhere: ${code("--project")} takes it, the web shows the project at ${code("/<owner>/<name>")}, and git clones it from ${code("<platform>/<owner>/<name>.git")}. You make projects under your own handle; a bare word, as in ${cli("init --project datekit")}, is taken as yours, under the handle ${cli("login")} kept. Owning a namespace is the right to make projects in it and nothing more: who decides stays with the config folder.`,18+ `A project's name is its owner, then a short name: ${code("<owner>/<name>")}, as in ${code("oscabriel/datekit")}. The name is the project's address everywhere: ${code("--project")} takes it, the web shows the project at ${code("/<owner>/<name>")}, and git clones it from ${code("<platform>/<owner>/<name>.git")}. You make projects under your own handle; a bare word, as in ${cli("init --project datekit")}, is taken as yours, under the handle ${cli("login")} kept, and so is an import left unnamed. Owning a namespace is the right to make projects in it and nothing more: who decides stays with the config folder.`,19 "",20 "## Import a repo",21 "",22- `To bring a public repo over HTTPS: ${cli("init --import <url>")}, with ${code("--branch")} when its default branch is not the one you want. A repo from ${sourceHosts.map((host) => code(host)).join(", ")} is named after its source namespace, ${code("<host>/<account>/<name>")}, so ${code("https://github.com/pallets/click")} becomes ${code("github.com/pallets/click")}; a repo from any other host is named under your handle, after the URL's last segment. ${code("--project")} names it otherwise, a bare word again under your handle. On the web, [Import a repo](/import) does the same, and the web address of such a name nobody has imported yet, such as ${code("/github.com/pallets/click")}, offers the import. You are an import's first maintainer, as of any project.`,22+ `To bring a public repo over HTTPS: ${cli("init --import <url>")}, with ${code("--branch")} when its default branch is not the one you want. The import is yours: it is named under your handle, after the URL's last segment, so ${code("https://github.com/pallets/click")} becomes ${code("<your handle>/click")}, and the project's page says where it was imported from. ${code("--project")} names it otherwise: a bare word again under your handle, or, for a repo from ${sourceHosts.map((host) => code(host)).join(", ")}, its source namespace, ${code("<host>/<account>/<name>")}, as in ${code("github.com/pallets/click")}, which keeps the source's account as the owner. On the web, [Import a repo](/import) does the same, with the source namespace offered beside your handle, and the web address of such a name nobody has imported yet, such as ${code("/github.com/pallets/click")}, offers the import under it. You are an import's first maintainer, as of any project.`,23 "",24 "## The config folder",25 "",26 `How the project takes changes is TypeScript on \`main\`, in ${code(`${dir}/`)}. The platform reads it only from the commit it last landed, in a sandbox with no network and frozen time, so it changes the way everything else does: by a landing.`,91 unmodified linesmodified:packages/agent-kit/src/command-doc.ts+11 added
68 unmodified lines69 summary:70 "Make this repo, or a public HTTPS repo, a project: find its checks, write its config and push.",71 },72 {73+ contract: "openAsk",74+ flags: ["--files", "--project", "--yes", "--dry-run", "--json"],75+ needsApproval: true,76+ path: ["ask", "open"],77+ positional: ["ask"],78+ readOnly: false,79+ source: "local",80+ summary:81+ "Open an ask by landing its file and its check, read from the ask's own file under the config folder's asks/ and the path it names unless --files gives them, once the check fails on main by an assertion, twice in the same way.",82+ },83+ {84 flags: [85 "--ask",86 "--project",87 "--base",146 unmodified linesmodified:packages/agent-kit/test/command-doc.test.ts+2 added
88 unmodified lines89 it("includes each hand-written command the CLI has", () => {90 expect(91 localCommandDocs.map(({ path }) => path.join(" ")).toSorted()92 ).toStrictEqual([93+ "ask open",94 "check",95 "credential",96 "env set",97 "hook",77 unmodified lines175 176 it("gives a contract a hand-written command calls no row of its own", () => {177 expect(calling(docs, "initProject")).toStrictEqual(["init (local)"]);178 expect(calling(docs, "setEnv")).toStrictEqual(["env set (local)"]);179+ expect(calling(docs, "openAsk")).toStrictEqual(["ask open (local)"]);180 });181 });modified:packages/config/test/release.test.ts+5 added
566 unmodified lines567 posix: true,568 });569 });570 571+ it("ends by naming the next step, login on the brand's own platform host", () => {572+ expect(script).toContain(`platform='https://git.${Brand.domain}'`);573+ expect(script).toContain('echo "next: $name login --url $platform"');574+ });575+576 const install = (files: Readonly<Record<string, string>>) =>577 Effect.gen(function* () {578 const fs = yield* FileSystem.FileSystem;579 const path = yield* Path.Path;167 unmodified linesmodified:packages/protocol/src/cli.ts+15 added-7 removed
90 unmodified lines91 readonly fields: Readonly<Record<string, string>>;92 readonly values: Effect.Effect<Readonly<Record<string, string>>, never, R>;93 }94 95+/** A view is pure, or looks around first (the repo the command stands in) with the defaults' services. */96+export type Render<Success, R> = (97+ success: Success98+) => Option.Option<View> | Effect.Effect<Option.Option<View>, never, R>;99+100 export interface ToCommandOptions<Success, OutputR, DefaultsR> {101 readonly output: Effect.Effect<CommandOutput, never, OutputR>;102 readonly defaults?: Defaults<DefaultsR> | undefined;98- readonly render?: ((success: Success) => Option.Option<View>) | undefined;103+ readonly render?: Render<Success, DefaultsR> | undefined;104 readonly refusalsIn?: ((success: Success) => readonly Refusal[]) | undefined;105 }106 102-export type Views<Rpcs extends Rpc.Any> = Readonly<103- Record<string, (success: Rpc.Success<Rpcs>) => Option.Option<View>>107+export type Views<Rpcs extends Rpc.Any, R = never> = Readonly<108+ Record<string, Render<Rpc.Success<Rpcs>, R>>109 >;110 111 export class ApprovalNeeded extends Schema.TaggedError<ApprovalNeeded>()(112 "ApprovalNeeded",441 unmodified lines554 }555 556 const data = yield* Effect.orDie(encodeSuccess(success));557 553- const view = Option.getOrElse(558+ const rendered =559 options.render === undefined555- ? Option.none()556- : options.render(success),560+ ? Option.none<View>()561+ : options.render(success);562+563+ const view = Option.getOrElse(564+ Effect.isEffect(rendered) ? yield* rendered : rendered,565 () => asJson(JSON.stringify(data, null, 2))566 );567 568 return yield* output.success({ command, data, json, view });11 unmodified lines580 581 export interface ToCommandsOptions<Rpcs extends Rpc.Any, OutputR, DefaultsR> {582 readonly output: Effect.Effect<CommandOutput, never, OutputR>;583 readonly defaults?: Defaults<DefaultsR> | undefined;576- readonly views?: Views<Rpcs> | undefined;584+ readonly views?: Views<Rpcs, DefaultsR> | undefined;585 readonly refusalsIn?:586 | ((success: Rpc.Success<Rpcs>) => readonly Refusal[])587 | undefined;588 readonly exclude: readonly string[];29 unmodified linesmodified:scripts/lib/release/install-script.ts+2 added
26 unmodified lines27 `base=${quoted(input.baseUrl)}`,28 `version=${quoted(input.version)}`,29 `slug=${quoted(brand.slug)}`,30 `name=${quoted(brand.cli)}`,31+ `platform=${quoted(`https://git.${brand.domain}`)}`,32 `helper=${quoted(brand.gitCredentialHelper)}`,33 `dir="\${${installDir}:-$HOME/.local/bin}"`,34 "",35 "fail() {",51 unmodified lines87 'mv -f "$tmp/$asset" "$dir/$name"',88 'ln -sf "$name" "$dir/$helper"',89 "",90 'echo "installed $name $version as $dir/$name, with $helper beside it"',91+ 'echo "next: $name login --url $platform"',92 'case ":$PATH:" in',93 ' *":$dir:"*) ;;',94 ' *) echo "add $dir to your PATH to run $name" ;;',95 "esac",3 unmodified linesmodified:GLOSSARY.md+1 added-1 removed
87 unmodified lines88 The commit the platform itself last landed on main; the only commit a project's rules are read from.89 _Avoid_: HEAD, tip of main90 91 **Import**:92-A project adopted from a public repo: a read-only copy, not run by its upstream maintainers, whose first `main` is the source branch's tip. The source, its address and branch, stays on the project's record and is shown as where it was imported from; by default the project is named after its source namespace (the Run a project guide has the whole rule). It is made from the CLI's `init --import` or the web's `/import`.92+A project adopted from a public repo: a read-only copy, not run by its upstream maintainers, whose first `main` is the source branch's tip. The source, its address and branch, stays on the project's record and is shown as where it was imported from; by default the project is named under the importer's handle, after the URL's last segment, with the source namespace on offer instead (the Run a project guide has the whole rule). It is made from the CLI's `init --import` or the web's `/import`.93 _Avoid_: mirror, fork (of the source), sync94 95 **Outcome**:96 Where an offered answer stands: Checking, Landed, WaitingOnParent, AwaitingFinish, AwaitingDecision or Refused; only Refused carries refusals, and waiting is not a refusal.159 unmodified lines