Skip to content
Myr

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

28 files+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.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";8import { Effect, FileSystem, Option, Path, Schema } from "effect";9import { Argument, Command, Flag } from "effect/cli";1011import { Output } from "../output.ts";12import { repoContext } from "../repo-context.ts";13import { projectOf, reportRefusals, usage, WorkingDirectory } from "./why.ts";1415const COMMAND = "ask open";1617type Payload = typeof OpenAsk.payloadSchema.Type;1819const Files = Schema.NonEmptyArray(ConfigFile);2021const decodePayload = Schema.decodeUnknownEffect(OpenAsk.payloadSchema);2223const encodePayload = Schema.encodeEffect(OpenAsk.payloadSchema);2425const encodeSuccess = Schema.encodeEffect(OpenAsk.successSchema);2627export const askFileOf = (ask: AskId) =>28 `${Brand.configDir}/asks/${ask}.ask.ts`;2930// 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.33const CHECK_PATH = /\bpath:\s*(?<quote>["'`])(?<path>[^"'`\n]+)\k<quote>/u;3435const readOr = (file: string, missing: string) =>36 Effect.flatMap(FileSystem.FileSystem, (fs) =>37 fs38 .readFileString(file)39 .pipe(Effect.catchTag("PlatformError", () => usage(missing)))40 );4142/** The ask's own file, then the check it names, both as the working tree has them. */43export const filesInTree = (root: string, ask: AskId) =>44 Effect.gen(function* () {45 const path = yield* Path.Path;46 const askFile = askFileOf(ask);4748 const askText = yield* readOr(49 path.join(root, askFile),50 `No ask file at ${askFile}: write the ask there, or pass --files.`51 );5253 const check = CHECK_PATH.exec(askText)?.groups?.path;5455 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 }6061 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 );6566 return [67 { content: askText, path: askFile },68 { content: checkText, path: check },69 ];70 });7172const 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}.`;7475 return { markdown: said, text: said };76};7778export 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;120121 if (!flags.yes && !dryRun) {122 return yield* new ApprovalNeeded({ command: COMMAND });123 }124125 const context = yield* Effect.option(126 repoContext(yield* WorkingDirectory)127 );128129 const project = yield* projectOf(flags.project, context);130131 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 });142143 const payload: Payload = yield* decodePayload({144 ask,145 files,146 project,147 }).pipe(Effect.catch((error) => usage(String(error))));148149 const output = yield* Output;150151 if (dryRun) {152 return yield* output.plan({153 command: COMMAND,154 json,155 payload: yield* Effect.orDie(encodePayload(payload)),156 });157 }158159 const client = yield* Client;160 const opened = yield* client.openAsk(payload);161162 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
modified:apps/cli/src/local/init.ts+48 added-11 removed
1import { Brand } from "@repo/brand";2import { findRunBlock } from "@repo/checks/finder";3import type { RepoFile } from "@repo/checks/finder";4import { PATH_PLACEHOLDER } from "@repo/checks/kinds";5import { ApprovalNeeded } from "@repo/protocol/cli";6import { Client } from "@repo/protocol/contracts";7import type { InitProject } from "@repo/protocol/contracts";8import { ProjectName, sourceNamespaceOf } from "@repo/protocol/ids";
13 unmodified lines
2223import { Credentials, gitHelperConfig } from "../credentials.ts";24import { endRefused, Output } from "../output.ts";25import { parseRemote, repoContext } from "../repo-context.ts";25import { projectFile } from "./project-file.ts";26import { ASKS_DIR, projectFile } from "./project-file.ts";2728const COMMAND = "init";2930const CONFIG = `${Brand.configDir}/project.ts`;
1 unmodified line
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.`;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), {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 });4546export class InitMisused extends Schema.TaggedError<InitMisused>()(47 "InitMisused",48 { reason: Schema.String }49) {
45 unmodified lines
95 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 lines
195 Effect.gen(function* () {196 const word = Option.getOrElse(given, () => fallback.short);197 const known = yield* profileOwner;198199 // 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);204205 const spelled = word.includes("/")206 ? word207 : `${Option.getOrElse(owner, () => "")}/${word}`;
107 unmodified lines
315 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);320321 yield* output.success({322 command: COMMAND,323 data: withLanded(
7 unmodified lines
331 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 lines
366 yield* imported(input, url, payload);367 }368 });369370const configLine = (atHead: boolean, inTree: boolean) => {371 if (atHead) {372 return `Kept ${CONFIG} as it is.`;373 }374375 return inTree376 ? `Committed ${CONFIG} as the work tree had it, alone.`377 : `Wrote ${CONFIG} and committed it alone.`;378};379380interface Found {381 readonly atHead: boolean;382 readonly commits: readonly string[];383 readonly hasRemote: boolean;384 readonly payload: Payload;385 readonly root: string;
4 unmodified lines
390 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;395371 if (writes.length === 0) {396 if (atHead) {397 yield* output.note(`kept ${CONFIG} as it is`);398 }399400 for (const file of writes) {
26 unmodified lines
427 yield* output.note(ran.stderr.trimEnd());428 }429 }430406 const config =407 writes.length === 0 ? `Kept ${CONFIG} as it is` : `Wrote ${CONFIG}`;431 const config = configLine(atHead, writes.length === 0);432433 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 ];442443 yield* output.success({444 command: COMMAND,
37 unmodified lines
482 inTree || atHead483 ? []484 : [{ content: projectFile(block.run, block.sources), path: CONFIG }];485486 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 }496497 const commits: readonly string[] = atHead ? [] : [CONFIG];498499 const hasRemote =500 (yield* run(root, ["git", "remote", "get-url", Brand.slug])).exitCode ===
15 unmodified lines
516 payload,517 };518519 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 });523524export const init = Command.make(COMMAND, flags, (input) =>
9 unmodified lines
modified:apps/cli/src/local/login.ts+15 added-4 removed
463 unmodified lines
464 (yield* stdoutIsTerminal)465 );466 });467468const viewOf = (said: string, commands: readonly (readonly string[])[]) => {468const 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];475476 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};486487const 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.`;489490export const login = Command.make(491 "login",492 {493 ...flags,
61 unmodified lines
555 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 lines
modified:apps/cli/src/local/project-file.ts+86 added-3 removed
modified:apps/cli/src/main.ts+12 added-2 removed
21 unmodified lines
22import { cliVersion } from "./version.ts";2324export 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 lines
51const isSharedUsage = Schema.is(52 Schema.Union([ApprovalNeeded, MissingValue, UnknownCommand])53);5455const isMissingValue = Schema.is(MissingValue);5657/** `asks` wants one project; outside a clone, the cross-project list is the answer. */58const 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;6465const signIn = [66 "Unauthenticated: the platform does not know who you are",67 ` next: ${Brand.cli} login`,68 " retryable: no",
13 unmodified lines
82 );83 }8485 if (isUsage(failure) || Schema.isSchemaError(failure)) {76 return Option.some(failure.message);86 return Option.some(hinted(failure) ?? failure.message);87 }8889 return isTransportFailure(failure)90 ? Option.map(noPlatformOf(failure), ({ message }) => message)
100 unmodified lines
modified:apps/cli/src/render.ts+57 added-5 removed
17 unmodified lines
18} from "@repo/protocol/contracts";19import type { Contract } from "@repo/protocol/contracts";20import { LandReceipt } from "@repo/protocol/domain/answer";21import type { AnswerReceipt } from "@repo/protocol/domain/answer";22import type { ClaimView } from "@repo/protocol/domain/claim";23import { DecisionSubject } from "@repo/protocol/domain/decision";24import { Outcome } from "@repo/protocol/domain/outcome";25import type {26 ImportSource,
5 unmodified lines
32import { receiptLine } from "@repo/protocol/render";33import { DateTime, Option, Result, Schema } from "effect";34import type { Rpc } from "effect/rpc";3536import { parseRemote, parseRepoName } from "./repo-context.ts";37import type { Remote } from "./repo-context.ts";3839const short = (sha: string) => sha.slice(0, 7);4041const when = (at: DateTime.Utc) => DateTime.formatIso(at);42
154 unmodified lines
197);198199const ask = viewOf(ShowAsk.successSchema, ({ brief }) => prose(brief));200197const 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. */202export 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}208209const sameProject = (held: ClaimView, url: string) =>210 Option.exists(parseRemote(url), ({ repo }) =>211 Option.exists(parseRepoName(repo), (ref) => ref.project === held.project)212 );213214/** Outside a repo, `remotes` is empty, so the receipt starts with a clone. */215export const placeOf = (held: ClaimView, remotes: readonly Remote[]): Place => {216 const named = remotes.find(({ name }) => name === Brand.slug);217218 if (named === undefined) {219 return {220 addRemote: true,221 inClone: remotes.some(({ url }) => sameProject(held, url)),222 remoteName: Brand.slug,223 };224 }225226 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};234235const 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);239240 return `git clone ${origin}/${canonical}.git && cd ${folder}`;241 });242243export 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 ];253254 return {255 markdown: [
15 unmodified lines
271 "Next:",272 ...steps.map((step) => ` ${step}`),273 ].join("\n"),274 };225});275};276277export const isClaimed = Schema.is(Claim.successSchema);278279const status = viewOf(Status.successSchema, ({ answers, claims, handle }) =>280 joined(281 prose(`Signed in as ${handle}.`),282 prose("Claims:"),
284 unmodified lines
567 isReceipt(success) && Outcome.guards.Refused(success.outcome)568 ? success.outcome.refusals569 : [];570571/** `claim`'s receipt looks at the repo it is printed in, so the CLI's surfaces add it. */572export const views = {520 claim,573 credits,574 finish: finished,575 frontPage: front,576 ledger,
16 unmodified lines
modified:apps/cli/src/repo-context.ts+10 added-5 removed
94 unmodified lines
95 ? Option.some({ origin, repo })96 : Option.none();97 });9899export interface Remote {100 readonly name: string;101 readonly url: string;102}103104export 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 lines
142 return { exitCode, stdout };143 })144 );145142const remotesOf = (listing: string) =>146const remotesOf = (listing: string): readonly Remote[] =>147 listing.split("\n").flatMap((line) => {148 const match = /^(?<name>\S+)\t(?<url>\S+) \(fetch\)$/u.exec(line);149150 return match?.groups?.name === undefined || match.groups.url === undefined
40 unmodified lines
191192 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 lines
modified:apps/cli/src/surfaces.ts+26 added-4 removed
7 unmodified lines
8 Contracts,9 surfaced,10 Surfaces,11} from "@repo/protocol/contracts";12import type { Contract } from "@repo/protocol/contracts";13import { toToolkit } from "@repo/protocol/mcp";14import {15 briefResources,16 skillIn,
13 unmodified lines
30} from "effect";31import { McpProtocol, McpServer } from "effect/ai";32import { Argument, Command, Flag } from "effect/cli";33import type { ChildProcessSpawner } from "effect/process";34import type { Rpc } from "effect/rpc";3536import { local } from "./local/index.ts";37import { Output } from "./output.ts";36import { refusalsIn, views } from "./render.ts";38import {39 claimReceipt,40 isClaimed,41 placeOf,42 refusalsIn,43 views,44} from "./render.ts";45import { repoContext } from "./repo-context.ts";46import { today } from "./tui/command.ts";47import { cliVersion } from "./version.ts";48
22 unmodified lines
71 readonly path: readonly [string, ...string[]];72 readonly command: Command.Command.Any;73}7467/** `env set` reads the value from stdin so it never passes through an argument list or a transcript. */68const 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. */76const wrapped = ["initProject", "openAsk", "setEnv", "today"];7778const remotesHere = Effect.map(79 Effect.option(Effect.flatMap(WorkingDirectory, repoContext)),80 Option.match({ onNone: () => [], onSome: ({ remotes }) => remotes })81);8283const 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;9192const 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});99100const groups = new Map([101 ["env", "Read a project's env shape, or set a write-only value."],
195 unmodified lines
added:apps/cli/test/local/ask-open.test.ts+299 added
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { Client, Contracts } from "@repo/protocol/contracts";5import type { OpenAsk } from "@repo/protocol/contracts";6import { Ask } from "@repo/protocol/domain/ask";7import { CheckSpec } from "@repo/protocol/domain/check";8import { Envelope } from "@repo/protocol/envelope";9import { LandedSha, RepoPath } from "@repo/protocol/ids";10import { NotRedFirst } from "@repo/protocol/refusal";11import { asTester, unanswered } from "@repo/protocol/testing";12import { gitOk } from "@repo/testkit/git";13import {14 Cause,15 Effect,16 Exit,17 FileSystem,18 Layer,19 Path,20 Ref,21 Runtime,22 Schema,23} from "effect";24import { CliOutput } from "effect/cli";25import { ChildProcess, ChildProcessSpawner } from "effect/process";26import { RpcTest } from "effect/rpc";27import { TestConsole } from "effect/testing";2829import { program } from "../../src/main.ts";30import { OutputPlain } from "../../src/output.ts";31import { SignedOut } from "../signed-out.ts";3233const PROJECT = "oscabriel/demo";3435const ASK = "fix-a";3637const ASK_FILE = `${Brand.configDir}/asks/${ASK}.ask.ts`;3839const CHECK = `test/asks/${ASK}.test.ts`;4041const 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");5152const checkText = 'it("is two", () => expect(a).toBe(2));\n';5354const landed = LandedSha.make("5555555555555555555555555555555555555555");5556const 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};7576const 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());8182 yield* gitOk(repo, "init", "--quiet", "--initial-branch=main");8384 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 }9091 return repo;92 });9394const startedIn = (repo: string) =>95 Layer.effect(ChildProcessSpawner.ChildProcessSpawner)(96 Effect.gen(function* () {97 const real = yield* ChildProcessSpawner.ChildProcessSpawner;98 const path = yield* Path.Path;99100 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));112113const 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 }));133134const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>135 Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));136137const 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));144145 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 );165166const decodeEnvelope = Schema.decodeEffect(167 Schema.fromJsonString(Envelope(Schema.Unknown))168);169170const argv = ["ask", "open", ASK, "--project", PROJECT, "--yes", "--json"];171172describe(`${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);180181 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 ]);192193 const envelope = yield* decodeEnvelope(ran.out.join("\n"));194195 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 );203204 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));210211 const given = [{ content: "given", path: ASK_FILE }];212213 const ran = yield* cli(repo, platform.layer, [214 ...argv,215 "--files",216 JSON.stringify(given),217 ]);218219 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 );226227 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);250251 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 );259260 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 });265266 const platform = yield* aPlatform(Effect.fail(new NotRedFirst({})));267268 const ran = yield* cli(repo, platform.layer, argv);269270 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 );275276 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));282283 const ran = yield* cli(repo, platform.layer, [284 "ask",285 "open",286 ASK,287 "--project",288 PROJECT,289 ]);290291 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 lines
314 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 );330331 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";337338 const platform = yield* aPlatform(339 Effect.succeed({340 project: ProjectName.make("oscabriel/demo"),341 remote: gateway,342 })343 );344345 const ran = yield* cli(machine, platform.layer, [346 "init",347 "--project",348 "oscabriel/demo",349 "--yes",350 "--no-push",351 ]);352353 expect(ran.code).toBe(0);354355 const said = ran.out.join("\n");356357 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 );365366 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;373374 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");382383 const platform = yield* aPlatform(created(machine));384385 const ran = yield* cli(machine, platform.layer, [386 "init",387 "--project",388 "oscabriel/demo",389 "--yes",390 "--json",391 ]);392393 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 lines
617 "--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 lines
941 { timeout: 30_000 }942 );943944 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 lines
956 "https://example.test/acme/widgets.git",957 []958 );959878 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 );965966 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 );975976 const machine = yield* aMachine;977978 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 );985986 yield* cli(machine, platform.layer, [987 "init",988 "--import",989 "https://github.com/Pallets/click.git",990 "--yes",991 "--json",992 ]);993994 const unknown = (yield* decodeCalls(yield* platform.calls)).map(995 ({ project }) => project996 );997998 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 );10051006 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 lines
modified:apps/cli/test/local/login.test.ts+4 added-1 removed
290 unmodified lines
291292 const { stderr, stdout } = yield* printed;293294 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_000
473 unmodified lines
modified:apps/cli/test/local/project-file.test.ts+45 added-2 removed
37 unmodified lines
38 "skipped .github/workflows/broken.yml: not YAML",39 ],40} as const;4142const 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];4748const 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];5253describe("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 lines
65 " // 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 });8384 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 });99100 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 );105106 expect(text).toContain(` unit: "cargo test",`);107 expect(text).toContain("skips test/asks/**");108 expect(text).not.toContain("--exclude");109 });110111 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 lines
127 "// 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 lines
modified:apps/cli/test/build.test.ts+1 added-1 removed
148 unmodified lines
149const spawning = { timeout: 60_000 };150151const 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 lines
added:apps/cli/test/claim-receipt.test.ts+195 added
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { Contracts } from "@repo/protocol/contracts";5import { ClaimView } from "@repo/protocol/domain/claim";6import { keyOf, ProjectName } from "@repo/protocol/ids";7import { unanswered } from "@repo/protocol/testing";8import { gitOk } from "@repo/testkit/git";9import { Effect, FileSystem, Layer, Schema } from "effect";1011import { claimReceipt, placeOf } from "../src/render.ts";12import { runProgram } from "./remote-server.ts";1314const platform = "https://platform.example.dev";1516const project = "oscabriel/datekit";1718const ask = "fix-week";1920const fork = `${platform}/${project}--${ask}--alice.git`;2122const 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});3536const stepsOf = (text: string | undefined) =>37 (text ?? "")38 .split("\n")39 .filter((line) => line.startsWith(" "))40 .map((line) => line.trim());4142describe(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 });5960 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 });7172 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 });8485 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});9394describe(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 });112113 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 });129130 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 });136137 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});143144const claiming = Layer.mergeAll(145 unanswered,146 Contracts.toLayerHandler("claim", () => Effect.succeed({ claim: held }))147);148149describe(`${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();155156 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 );171172 const argv = ["claim", ask, "--project", project];173174 const away = yield* runProgram(argv, {175 cwd: outside,176 handlers: claiming,177 });178179 const inside = yield* runProgram(argv, {180 cwd: clone,181 handlers: claiming,182 });183184 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
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { Client } from "@repo/protocol/contracts";5import { Effect, Layer } from "effect";5import { Effect, FileSystem, Layer } from "effect";6import { CliOutput, Command } from "effect/cli";7import { TestConsole } from "effect/testing";89import { Credentials } from "../src/credentials.ts";10import { root } from "../src/main.ts";10import { program, root } from "../src/main.ts";11import { OutputPlain } from "../src/output.ts";12import { WorkingDirectory } from "../src/surfaces.ts";13import { SignedOut } from "./signed-out.ts";1415const printed = Effect.map(TestConsole.logLines, (all) =>16 all.flatMap((chunk) => String(chunk).split("\n"))17);
25 unmodified lines
43 return trimmed.length > 0 ? [trimmed] : [];44 });45};4647describe(`${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();5455 yield* Effect.exit(program(["asks"])).pipe(56 Effect.provideService(WorkingDirectory, dir)57 );5859 const said = (yield* TestConsole.errorLines).map(String).join("\n");6061 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});7778describe(`${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;8283 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 lines
modified:apps/cli/test/repo-context.test.ts+1 added
151 unmodified lines
152153 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 lines
modified:apps/cli/test/surfaces.test.ts+3 added-3 removed
186 unmodified lines
187 );188189 const paths = entries.map(({ path: words }) => words.join(" "));190191 // `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 lines
205 );206 });207208 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 });212213 it("leaves init and env set to their local commands", () => {
413 unmodified lines
modified:apps/web/src/features/import/import-form.tsx+1 added-1 removed
173 unmodified lines
174 return "The address names it: the project keeps its source's account.";175 }176177 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};181182const NameHint = ({
216 unmodified lines
modified:apps/web/src/features/import/prefill.ts+2 added-1 removed
41 unmodified lines
4243export const ownerOfHandle = (handle: Handle): Option.Option<Owner> =>44 decodeOwner(handle.toLowerCase());4546/** The handle first, so an import is the importer's own by default; the source namespace stays on offer. */47export 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 ]);5556export const sourceUrlOf = (project: ProjectName) => `https://${project}`;57
22 unmodified lines
modified:apps/web/test/import.test.tsx+5 added-7 removed
87 unmodified lines
88 const markup = signedIn();8990 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 lines
147 });148});149150describe(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 });157158 it("offers the handle alone when the host is not on the list", () => {
274 unmodified lines
433434 yield* Effect.tryPromise(() => router.load());435436 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 );444445 it.live("draws a refusal as the platform gave it, under the form", () =>
23 unmodified lines
modified:packages/agent-kit/src/docs/run-a-project.ts+2 added-2 removed
13 unmodified lines
14 `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 lines
modified:packages/agent-kit/src/command-doc.ts+11 added
68 unmodified lines
69 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 lines
modified:packages/agent-kit/test/command-doc.test.ts+2 added
88 unmodified lines
89 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 lines
175176 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 lines
567 posix: true,568 });569 });570571 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 });575576 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 lines
modified:packages/protocol/src/cli.ts+15 added-7 removed
90 unmodified lines
91 readonly fields: Readonly<Record<string, string>>;92 readonly values: Effect.Effect<Readonly<Record<string, string>>, never, R>;93}9495/** A view is pure, or looks around first (the repo the command stands in) with the defaults' services. */96export type Render<Success, R> = (97 success: Success98) => Option.Option<View> | Effect.Effect<Option.Option<View>, never, R>;99100export 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}106102export type Views<Rpcs extends Rpc.Any> = Readonly<103 Record<string, (success: Rpc.Success<Rpcs>) => Option.Option<View>>107export type Views<Rpcs extends Rpc.Any, R = never> = Readonly<108 Record<string, Render<Rpc.Success<Rpcs>, R>>109>;110111export class ApprovalNeeded extends Schema.TaggedError<ApprovalNeeded>()(112 "ApprovalNeeded",
441 unmodified lines
554 }555556 const data = yield* Effect.orDie(encodeSuccess(success));557553 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);562563 const view = Option.getOrElse(564 Effect.isEffect(rendered) ? yield* rendered : rendered,565 () => asJson(JSON.stringify(data, null, 2))566 );567568 return yield* output.success({ command, data, json, view });
11 unmodified lines
580581export 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 lines
modified:scripts/lib/release/install-script.ts+2 added
26 unmodified lines
27 `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 lines
87 '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 lines
modified:GLOSSARY.md+1 added-1 removed
87 unmodified lines
88The commit the platform itself last landed on main; the only commit a project's rules are read from.89_Avoid_: HEAD, tip of main9091**Import**:92A 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`.92A 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), sync9495**Outcome**:96Where an offered answer stands: Checking, Landed, WaitingOnParent, AwaitingFinish, AwaitingDecision or Refused; only Refused carries refusals, and waiting is not a refusal.
159 unmodified lines