From af3a586b9533603cccff437ba4825e62bf1da737 Mon Sep 17 00:00:00 2001 From: FreshlyBrewedCode Date: Sun, 13 Sep 2026 09:57:26 +0000 Subject: [PATCH] fix(cli): resolve the GitHub repo and host from the project, not the working directory A github-backed project now records the host it was initialised against in project.toml, alongside the repo. Reads resolve the host from the project (recorded host, else the git remote resolved in the project root, never the invocation directory), so `wayful --project ` works from an unrelated checkout or a non-git directory. `wayful init` also checks for existing local state before touching the remote, and now reports the backend, repository, and host it bound to. Adds `wayful doctor`: resolves repository, host, credential source, wayful labels, and the rate-limit budget for a project, or names the piece that is wrong. Filesystem projects report what applies without failing. Closes #79 --- packages/cli/src/backend/ProjectStore.ts | 8 ++ packages/cli/src/backend/filesystem/decode.ts | 13 +++ .../filesystem/layer/ops/project-type.test.ts | 60 +++++++++++++ .../backend/filesystem/layer/ops/project.ts | 22 +++++ .../src/backend/github/credentials.test.ts | 25 ++++++ .../cli/src/backend/github/credentials.ts | 42 ++++++--- .../cli/src/backend/github/doctor.test.ts | 87 +++++++++++++++++++ packages/cli/src/backend/github/doctor.ts | 61 +++++++++++++ .../cli/src/backend/github/mapStore.test.ts | 16 ++++ .../cli/src/backend/github/remote.test.ts | 16 +++- packages/cli/src/backend/github/remote.ts | 33 +++---- packages/cli/src/backend/github/repo.test.ts | 83 ++++++++++++++++++ packages/cli/src/backend/github/repo.ts | 40 ++++++--- packages/cli/src/cli/cli.test.ts | 4 +- packages/cli/src/cli/cli.ts | 2 + packages/cli/src/cli/commands/doctor.test.ts | 34 ++++++++ packages/cli/src/cli/commands/doctor.ts | 54 ++++++++++++ .../cli/src/cli/commands/init-github.test.ts | 62 ++++++++++++- packages/cli/src/cli/commands/init.ts | 48 +++++++--- packages/cli/src/domain/model.ts | 7 ++ packages/cli/test/support/github/spawner.ts | 12 ++- packages/cli/test/support/github/store.ts | 9 +- 22 files changed, 682 insertions(+), 56 deletions(-) create mode 100644 packages/cli/src/backend/github/doctor.test.ts create mode 100644 packages/cli/src/backend/github/doctor.ts create mode 100644 packages/cli/src/backend/github/repo.test.ts create mode 100644 packages/cli/src/cli/commands/doctor.test.ts create mode 100644 packages/cli/src/cli/commands/doctor.ts diff --git a/packages/cli/src/backend/ProjectStore.ts b/packages/cli/src/backend/ProjectStore.ts index 40dcbae..8b88664 100644 --- a/packages/cli/src/backend/ProjectStore.ts +++ b/packages/cli/src/backend/ProjectStore.ts @@ -14,16 +14,24 @@ export interface ProjectHandle { readonly backend: ProjectBackend; /** Only present when `backend` is "github"; `owner/name`. */ readonly repo?: string; + /** + * The host recorded at init; absent on projects that predate the key, which + * fall back to the git remote resolved in `root`. + */ + readonly host?: string; } export class ProjectStore extends Context.Service< ProjectStore, { + /** Whether `directory` already holds wayful state, checked before any remote work. */ + readonly projectExists: (directory: string) => Effect.Effect; readonly initProject: (options: { readonly directory: string; readonly description: string; readonly backend?: ProjectBackend; readonly repo?: string; + readonly host?: string; }) => Effect.Effect; readonly openProject: ( hint: Option.Option, diff --git a/packages/cli/src/backend/filesystem/decode.ts b/packages/cli/src/backend/filesystem/decode.ts index 70588c5..0fa18ed 100644 --- a/packages/cli/src/backend/filesystem/decode.ts +++ b/packages/cli/src/backend/filesystem/decode.ts @@ -18,6 +18,10 @@ const fail = (message: string): never => { // leading/trailing/doubled); repo names additionally allow `.` and `_`. export const REPO_PATTERN = /^[A-Za-z0-9](?:-?[A-Za-z0-9])*\/[A-Za-z0-9._-]+$/; +// A GitHub host: a DNS name, optionally dotted (`github.example.com`), never a +// URL, port, or path. +export const HOST_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/; + export function decodeProjectMetadata(data: unknown): ProjectMetadata { if (!data || typeof data !== "object" || Array.isArray(data)) fail("malformed project metadata."); const record = data as Record; @@ -26,6 +30,7 @@ export function decodeProjectMetadata(data: unknown): ProjectMetadata { "description", "backend", "repo", + "host", "created_at", "updated_at", ]); @@ -50,6 +55,13 @@ export function decodeProjectMetadata(data: unknown): ProjectMetadata { } else if (backend === "github") { fail(`project backend "github" requires repo.`); } + let host: string | undefined; + if (record.host !== undefined) { + if (backend !== "github") fail(`project host requires backend "github".`); + if (typeof record.host !== "string" || !HOST_PATTERN.test(record.host)) + fail(`project host must be a valid hostname.`); + host = record.host as string; + } const createdAt = timestamp(record.created_at, "project created_at"); const updatedAt = timestamp(record.updated_at, "project updated_at"); return { @@ -57,6 +69,7 @@ export function decodeProjectMetadata(data: unknown): ProjectMetadata { description: record.description as string, backend, repo, + host, created_at: createdAt, updated_at: updatedAt, }; diff --git a/packages/cli/src/backend/filesystem/layer/ops/project-type.test.ts b/packages/cli/src/backend/filesystem/layer/ops/project-type.test.ts index ef90657..0bb7854 100644 --- a/packages/cli/src/backend/filesystem/layer/ops/project-type.test.ts +++ b/packages/cli/src/backend/filesystem/layer/ops/project-type.test.ts @@ -107,4 +107,64 @@ describe("FileSystemBackend: project and type round-trips", () => { expect(project.backend).toBe("github"); expect(project.repo).toBe("acme/widgets"); }); + + test("initProject persists the github host, and openProject round-trips it", async () => { + const directory = await temporaryDirectory(); + const project = await run( + Effect.gen(function* () { + const b = yield* backend(); + yield* b.initProject({ + directory, + description: "", + backend: "github", + repo: "acme/widgets", + host: "github.example.com", + }); + return yield* b.openProject(Option.some(directory)); + }), + ); + expect(project.backend).toBe("github"); + expect(project.host).toBe("github.example.com"); + }); + + test("openProject tolerates a github project with no recorded host, for the fallback", async () => { + const directory = await temporaryDirectory(); + const project = await run( + Effect.gen(function* () { + const b = yield* backend(); + yield* b.initProject({ + directory, + description: "", + backend: "github", + repo: "acme/widgets", + }); + return yield* b.openProject(Option.some(directory)); + }), + ); + expect(project.host).toBeUndefined(); + }); + + test("rejects a host on a filesystem project and a malformed host", async () => { + const cases: Array<{ + readonly backend: "filesystem" | "github"; + readonly host: string; + readonly repo?: string; + }> = [ + { backend: "filesystem", host: "github.com" }, + { backend: "github", host: "has a space", repo: "acme/widgets" }, + { backend: "github", host: "", repo: "acme/widgets" }, + ]; + for (const { backend: targetBackend, host, repo } of cases) { + const directory = await temporaryDirectory(); + const error = await runFailure( + Effect.gen(function* () { + const b = yield* backend(); + yield* b.initProject({ directory, description: "", backend: targetBackend, repo, host }); + return yield* b.openProject(Option.some(directory)); + }), + ); + expect(error).toBeInstanceOf(WayfulError); + expect((error as WayfulError).message).toContain("host"); + } + }); }); diff --git a/packages/cli/src/backend/filesystem/layer/ops/project.ts b/packages/cli/src/backend/filesystem/layer/ops/project.ts index 2bce4b7..e0ce069 100644 --- a/packages/cli/src/backend/filesystem/layer/ops/project.ts +++ b/packages/cli/src/backend/filesystem/layer/ops/project.ts @@ -31,17 +31,37 @@ export function makeProjectOps(fs: FileSystem.FileSystem, path: Path.Path) { return yield* fail("no Wayful project found; run 'wayful init' first."); }); + // Walks upward like `discoverProjectRoot`, so `init` refuses anywhere inside + // an existing project rather than nesting a second one. + const projectExists = (directory: string): Effect.Effect => + Effect.gen(function* () { + let current = path.resolve(directory); + while (true) { + const exists = yield* fs + .exists(path.join(current, ".wayful")) + .pipe(Effect.mapError(accessError)); + if (exists) return true; + const parent = path.dirname(current); + if (parent === current) return false; + current = parent; + } + }); + return { + projectExists, + initProject: ({ directory, description, backend = "filesystem", repo, + host, }: { readonly directory: string; readonly description: string; readonly backend?: ProjectBackend; readonly repo?: string; + readonly host?: string; }) => Effect.gen(function* () { const root = path.resolve(directory); @@ -61,6 +81,7 @@ export function makeProjectOps(fs: FileSystem.FileSystem, path: Path.Path) { description, backend, ...(repo !== undefined ? { repo } : {}), + ...(host !== undefined ? { host } : {}), created_at: now, updated_at: now, }), @@ -91,6 +112,7 @@ export function makeProjectOps(fs: FileSystem.FileSystem, path: Path.Path) { description: metadata.description, backend: metadata.backend, repo: metadata.repo, + host: metadata.host, }; }), }; diff --git a/packages/cli/src/backend/github/credentials.test.ts b/packages/cli/src/backend/github/credentials.test.ts index ab4ebe2..5a330b1 100644 --- a/packages/cli/src/backend/github/credentials.test.ts +++ b/packages/cli/src/backend/github/credentials.test.ts @@ -131,6 +131,31 @@ describe("GithubCredentials", () => { expect(result.message).toBe("run 'gh auth login', or set GH_TOKEN"); }); + test("resolve reports the environment variable the token came from", async () => { + process.env.GITHUB_TOKEN = "github-token"; + const credential = await runWithSpawner( + Effect.gen(function* () { + const credentials = yield* GithubCredentials; + return yield* credentials.resolve("github.com"); + }), + () => Effect.fail(fakeSpawnFailure("should not be called")), + ); + expect(credential.source).toBe("GITHUB_TOKEN"); + expect(Redacted.value(credential.token)).toBe("github-token"); + }); + + test("resolve reports `gh auth token` when it falls back to the CLI", async () => { + const credential = await runWithSpawner( + Effect.gen(function* () { + const credentials = yield* GithubCredentials; + return yield* credentials.resolve("github.com"); + }), + () => Effect.succeed("cli-token\n"), + ); + expect(credential.source).toBe("gh auth token"); + expect(Redacted.value(credential.token)).toBe("cli-token"); + }); + test("never includes the resolved token in the missing-credentials error, even when other hosts had one cached", async () => { const secret = "super-secret-token-value"; const result = await runWithSpawner( diff --git a/packages/cli/src/backend/github/credentials.ts b/packages/cli/src/backend/github/credentials.ts index d9448dd..6af59c6 100644 --- a/packages/cli/src/backend/github/credentials.ts +++ b/packages/cli/src/backend/github/credentials.ts @@ -5,6 +5,23 @@ import { WayfulError } from "@domain/errors"; const MISSING_CREDENTIALS_MESSAGE = "run 'gh auth login', or set GH_TOKEN"; +/** An environment variable the credential chain consults, in precedence order. */ +export type GithubCredentialEnvVar = "WAYFUL_GITHUB_TOKEN" | "GH_TOKEN" | "GITHUB_TOKEN"; + +export const GITHUB_TOKEN_ENV_VARS: readonly GithubCredentialEnvVar[] = [ + "WAYFUL_GITHUB_TOKEN", + "GH_TOKEN", + "GITHUB_TOKEN", +]; + +/** Where a resolved token came from, for `wayful doctor` to report. */ +export type GithubCredentialSource = GithubCredentialEnvVar | "gh auth token"; + +export interface ResolvedCredential { + readonly token: Redacted.Redacted; + readonly source: GithubCredentialSource; +} + const envToken = (name: string) => Config.option(Config.redacted(name)) .parse(ConfigProvider.fromEnv()) @@ -13,7 +30,11 @@ const envToken = (name: string) => export class GithubCredentials extends Context.Service< GithubCredentials, { - /** Resolves a bearer token for `host`; never reads `~/.config/gh/hosts.yml` directly. */ + /** + * Resolves a bearer token for `host` alongside the place it came from; + * never reads `~/.config/gh/hosts.yml` directly. + */ + readonly resolve: (host: string) => Effect.Effect; readonly token: (host: string) => Effect.Effect, WayfulError>; } >()("wayful/GithubCredentials") {} @@ -44,19 +65,20 @@ export const GithubCredentialsLayer = Layer.effect( return resolved; }); - const token = (host: string) => + const resolve = (host: string): Effect.Effect => Effect.gen(function* () { - const fromEnv = Option.firstSomeOf([ - yield* envToken("WAYFUL_GITHUB_TOKEN"), - yield* envToken("GH_TOKEN"), - yield* envToken("GITHUB_TOKEN"), - ]); - if (Option.isSome(fromEnv)) return fromEnv.value; + for (const name of GITHUB_TOKEN_ENV_VARS) { + const value = yield* envToken(name); + if (Option.isSome(value)) return { token: value.value, source: name }; + } const fromCli = yield* fromGhCli(host); - if (Option.isSome(fromCli)) return fromCli.value; + if (Option.isSome(fromCli)) return { token: fromCli.value, source: "gh auth token" }; return yield* new WayfulError({ message: MISSING_CREDENTIALS_MESSAGE }); }); - return GithubCredentials.of({ token }); + const token = (host: string) => + resolve(host).pipe(Effect.map((credential) => credential.token)); + + return GithubCredentials.of({ resolve, token }); }), ); diff --git a/packages/cli/src/backend/github/doctor.test.ts b/packages/cli/src/backend/github/doctor.test.ts new file mode 100644 index 0000000..5baaa6a --- /dev/null +++ b/packages/cli/src/backend/github/doctor.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, test } from "bun:test"; +import { Effect, Option } from "effect"; + +import { GithubCredentials } from "@backend/github/credentials"; +import { diagnoseGithub } from "@backend/github/doctor"; +import type { GithubHarnessOptions } from "@test/support/github/store"; +import { runGithub } from "@test/support/github/store"; +import { jsonResponse } from "@test/support/github/issues"; +import type { ProjectHandle } from "@backend/ProjectStore"; +import { WayfulError } from "@domain/errors"; + +function project(overrides: Partial = {}): ProjectHandle { + return { + root: "/projects/wayful", + description: "", + backend: "github", + repo: "acme/widgets", + host: "github.example.com", + ...overrides, + }; +} + +const permissionsResponse = jsonResponse( + 200, + { permissions: { push: true } }, + { + "x-ratelimit-limit": "5000", + "x-ratelimit-remaining": "4999", + "x-ratelimit-reset": "1700000000", + "x-ratelimit-resource": "core", + }, +); + +describe("diagnoseGithub", () => { + test("resolves the repository, host, credential, labels, and rate limit", async () => { + let requested = ""; + const diagnosis = await runGithub( + (request) => { + requested = request.url; + return permissionsResponse; + }, + diagnoseGithub(project(), ["task", "research"]), + ); + expect(requested).toBe("https://github.example.com/api/v3/repos/acme/widgets"); + expect(diagnosis.repository).toBe("acme/widgets"); + expect(diagnosis.host).toBe("github.example.com"); + expect(diagnosis.credential).toBe("GH_TOKEN"); + expect(diagnosis.labels).toEqual([ + "wayful:map", + "wayful:step", + "wayful:goal", + "wayful:blocked", + "wayful:type/task", + "wayful:type/research", + ]); + expect(Option.getOrThrow(diagnosis.rateLimit)).toEqual({ + limit: 5000, + remaining: 4999, + reset: 1700000000, + resource: "core", + }); + }); + + test("names an unusable credential as the problem", async () => { + const credentials: GithubCredentials["Service"] = { + resolve: () => + Effect.fail(new WayfulError({ message: "run 'gh auth login', or set GH_TOKEN" })), + token: () => + Effect.fail(new WayfulError({ message: "run 'gh auth login', or set GH_TOKEN" })), + }; + const options: GithubHarnessOptions = { credentials }; + const error = await runGithub( + () => jsonResponse(200, { permissions: { push: true } }), + diagnoseGithub(project(), []).pipe(Effect.flip), + options, + ); + expect(error.message).toBe("github credential: run 'gh auth login', or set GH_TOKEN"); + }); + + test("names the token when it cannot reach the repository", async () => { + const error = await runGithub( + () => jsonResponse(404, { message: "Not Found" }), + diagnoseGithub(project(), []).pipe(Effect.flip), + ); + expect(error.message).toContain("github token cannot access acme/widgets"); + }); +}); diff --git a/packages/cli/src/backend/github/doctor.ts b/packages/cli/src/backend/github/doctor.ts new file mode 100644 index 0000000..8e6b691 --- /dev/null +++ b/packages/cli/src/backend/github/doctor.ts @@ -0,0 +1,61 @@ +import { Effect, Option } from "effect"; +import type { ChildProcessSpawner } from "effect/unstable/process"; + +import { verifyAccess } from "@backend/github/api"; +import { GithubCredentials, type GithubCredentialSource } from "@backend/github/credentials"; +import { GithubHttp, type RateLimit } from "@backend/github/http"; +import { wayfulLabels } from "@backend/github/labels"; +import { resolveRepoRef } from "@backend/github/repo"; +import type { ProjectHandle } from "@backend/ProjectStore"; +import { WayfulError } from "@domain/errors"; + +/** + * Everything a github-backed project needs, resolved in one place. A healthy + * project yields this; the first missing piece fails with a `WayfulError` that + * names it, so a first-run failure is readable instead of an opaque HTTP + * status. + */ +export interface GithubDiagnosis { + readonly repository: string; + readonly host: string; + readonly credential: GithubCredentialSource; + readonly labels: readonly string[]; + readonly rateLimit: Option.Option; +} + +/** + * Resolves the repository, host, credential, labels, and rate-limit budget of + * a github-backed project. Credential resolution is wrapped so an unusable + * credential is named as such rather than surfacing as a bare missing-token + * message; the access check then names the token if it cannot reach the repo. + */ +export function diagnoseGithub( + project: ProjectHandle, + typeNames: readonly string[], +): Effect.Effect< + GithubDiagnosis, + WayfulError, + GithubCredentials | ChildProcessSpawner.ChildProcessSpawner | GithubHttp +> { + return Effect.gen(function* () { + const ref = yield* resolveRepoRef(project); + const credentials = yield* GithubCredentials; + const credential = yield* credentials + .resolve(ref.host) + .pipe( + Effect.mapError( + (error) => new WayfulError({ message: `github credential: ${error.message}` }), + ), + ); + yield* verifyAccess(ref, credential.token); + const http = yield* GithubHttp; + const rateLimit = yield* http.rateLimit; + return { + repository: `${ref.owner}/${ref.repo}`, + host: ref.host, + credential: credential.source, + labels: wayfulLabels(typeNames).map((label) => label.name), + rateLimit, + }; + }); +} diff --git a/packages/cli/src/backend/github/mapStore.test.ts b/packages/cli/src/backend/github/mapStore.test.ts index 02abd78..7645919 100644 --- a/packages/cli/src/backend/github/mapStore.test.ts +++ b/packages/cli/src/backend/github/mapStore.test.ts @@ -144,6 +144,22 @@ describe("GithubMapStore: listMaps", () => { expect(maps).toEqual([metadata("alpha", "first")]); }); + test("addresses the host recorded on the project, not the working directory's remote", async () => { + let seen = ""; + await run( + (request) => { + seen = request.url; + return jsonResponse(200, []); + }, + Effect.gen(function* () { + const store = yield* MapStore; + yield* store.listMaps({ ...project, host: "github.example.com" }); + }), + { remote: "git@github.com:acme/widgets.git" }, + ); + expect(new URL(seen).host).toBe("github.example.com"); + }); + test("sorts maps by name", async () => { const maps = await run( () => diff --git a/packages/cli/src/backend/github/remote.test.ts b/packages/cli/src/backend/github/remote.test.ts index c76b8ed..e32892c 100644 --- a/packages/cli/src/backend/github/remote.test.ts +++ b/packages/cli/src/backend/github/remote.test.ts @@ -57,7 +57,7 @@ describe("resolveOriginRemote", () => { expect(invocation).toEqual(["git", "remote", "get-url", "origin"]); return Effect.succeed("git@github.com:acme/widgets.git\n"); }); - const result = await Effect.runPromise(resolveOriginRemote.pipe(Effect.provide(layer))); + const result = await Effect.runPromise(resolveOriginRemote().pipe(Effect.provide(layer))); expect(result).toEqual(Option.some({ host: "github.com", owner: "acme", repo: "widgets" })); }); @@ -65,13 +65,23 @@ describe("resolveOriginRemote", () => { const layer = stubChildProcessSpawner(() => Effect.fail(fakeSpawnFailure("fatal: No such remote")), ); - const result = await Effect.runPromise(resolveOriginRemote.pipe(Effect.provide(layer))); + const result = await Effect.runPromise(resolveOriginRemote().pipe(Effect.provide(layer))); expect(result).toEqual(Option.none()); }); test("resolves to none when git prints nothing", async () => { const layer = stubChildProcessSpawner(() => Effect.succeed("\n")); - const result = await Effect.runPromise(resolveOriginRemote.pipe(Effect.provide(layer))); + const result = await Effect.runPromise(resolveOriginRemote().pipe(Effect.provide(layer))); expect(result).toEqual(Option.none()); }); + + test("runs git in the requested directory", async () => { + let cwd: string | undefined; + const layer = stubChildProcessSpawner((_invocation, options) => { + cwd = options.cwd; + return Effect.succeed(""); + }); + await Effect.runPromise(resolveOriginRemote("/project/root").pipe(Effect.provide(layer))); + expect(cwd).toBe("/project/root"); + }); }); diff --git a/packages/cli/src/backend/github/remote.ts b/packages/cli/src/backend/github/remote.ts index 76be7e4..3c4153f 100644 --- a/packages/cli/src/backend/github/remote.ts +++ b/packages/cli/src/backend/github/remote.ts @@ -27,20 +27,21 @@ export function parseGitRemoteUrl(url: string): Option.Option { * Resolves and parses the `origin` remote's URL via `git remote get-url * origin`, the one shell-out this needs — `.git/config` isn't parsed * directly since remote URL rewriting (`insteadOf`, worktree-local - * overrides) only git itself resolves correctly. Absent a usable origin (no - * remote, not a git repository, git unavailable, or an unparseable URL) - * resolves to `None` rather than failing, so a caller can fall back to an - * explicit `--repo` flag. + * overrides) only git itself resolves correctly. `cwd` is the directory git + * runs in; callers pass the project root so resolution never depends on the + * invocation directory. Absent a usable origin (no remote, not a git + * repository, git unavailable, or an unparseable URL) resolves to `None` + * rather than failing, so a caller can fall back to an explicit `--repo` flag + * or the default host. */ -export const resolveOriginRemote: Effect.Effect< - Option.Option, - never, - ChildProcessSpawner.ChildProcessSpawner -> = Effect.gen(function* () { - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const output = yield* spawner - .string(ChildProcess.make("git", ["remote", "get-url", "origin"])) - .pipe(Effect.orElseSucceed(() => "")); - const url = output.trim(); - return url ? parseGitRemoteUrl(url) : Option.none(); -}); +export const resolveOriginRemote = ( + cwd?: string, +): Effect.Effect, never, ChildProcessSpawner.ChildProcessSpawner> => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const output = yield* spawner + .string(ChildProcess.make("git", ["remote", "get-url", "origin"], cwd ? { cwd } : undefined)) + .pipe(Effect.orElseSucceed(() => "")); + const url = output.trim(); + return url ? parseGitRemoteUrl(url) : Option.none(); + }); diff --git a/packages/cli/src/backend/github/repo.test.ts b/packages/cli/src/backend/github/repo.test.ts new file mode 100644 index 0000000..74f73e0 --- /dev/null +++ b/packages/cli/src/backend/github/repo.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, test } from "bun:test"; +import { Effect, Redacted } from "effect"; + +import type { GithubCredentials } from "@backend/github/credentials"; +import { resolveRepo, resolveRepoRef } from "@backend/github/repo"; +import type { ProjectHandle } from "@backend/ProjectStore"; +import { fakeSpawnFailure, stubChildProcessSpawner } from "@test/support/github/spawner"; + +function project(overrides: Partial = {}): ProjectHandle { + return { + root: "/projects/wayful", + description: "", + backend: "github", + repo: "acme/widgets", + ...overrides, + }; +} + +describe("resolveRepoRef", () => { + test("uses the host recorded in the project and never shells out to git", async () => { + let gitCalls = 0; + const layer = stubChildProcessSpawner((invocation) => { + if (invocation[0] === "git") gitCalls++; + return Effect.succeed("git@github.com:acme/widgets.git\n"); + }); + const ref = await Effect.runPromise( + resolveRepoRef(project({ host: "github.example.com" })).pipe(Effect.provide(layer)), + ); + expect(ref).toEqual({ host: "github.example.com", owner: "acme", repo: "widgets" }); + expect(gitCalls).toBe(0); + }); + + test("falls back to the git remote resolved in the project root, not the working directory", async () => { + let cwd: string | undefined; + const layer = stubChildProcessSpawner((invocation, options) => { + expect(invocation).toEqual(["git", "remote", "get-url", "origin"]); + cwd = options.cwd; + return Effect.succeed("git@github.enterprise.test:acme/widgets.git\n"); + }); + const ref = await Effect.runPromise( + resolveRepoRef(project({ root: "/elsewhere/checkout" })).pipe(Effect.provide(layer)), + ); + expect(ref.host).toBe("github.enterprise.test"); + expect(cwd).toBe("/elsewhere/checkout"); + }); + + test("defaults to github.com when no host is recorded and no remote resolves", async () => { + const layer = stubChildProcessSpawner(() => Effect.fail(fakeSpawnFailure("no remote"))); + const ref = await Effect.runPromise(resolveRepoRef(project()).pipe(Effect.provide(layer))); + expect(ref.host).toBe("github.com"); + }); + + test("fails for a project that is not configured for github", async () => { + const result = await Effect.runPromise( + Effect.flip( + resolveRepoRef(project({ backend: "filesystem", repo: undefined })).pipe( + Effect.provide(stubChildProcessSpawner(() => Effect.succeed(""))), + ), + ), + ); + expect(result.message).toBe("project is not configured for the github backend."); + }); +}); + +describe("resolveRepo", () => { + test("resolves the token against the project's recorded host", async () => { + const requested: string[] = []; + const credentials: GithubCredentials["Service"] = { + resolve: () => Effect.die("not used"), + token: (host) => { + requested.push(host); + return Effect.succeed(Redacted.make("test-token")); + }, + }; + const resolved = await Effect.runPromise( + resolveRepo(project({ host: "github.example.com" }), credentials).pipe( + Effect.provide(stubChildProcessSpawner(() => Effect.succeed(""))), + ), + ); + expect(requested).toEqual(["github.example.com"]); + expect(Redacted.value(resolved.token)).toBe("test-token"); + }); +}); diff --git a/packages/cli/src/backend/github/repo.ts b/packages/cli/src/backend/github/repo.ts index e2e232c..343b366 100644 --- a/packages/cli/src/backend/github/repo.ts +++ b/packages/cli/src/backend/github/repo.ts @@ -12,24 +12,42 @@ export interface ResolvedRepo { } /** - * The repo a github-backed project addresses, plus the token that may write to - * it. The host comes from the git remote (defaulting to `github.com`), so an - * enterprise checkout resolves its own API base; the token then resolves - * against that host. + * The host a github-backed project addresses. The host recorded at init always + * wins; a project that predates the key falls back to the git remote resolved + * in the *project root* — never the invocation directory — and finally to + * `github.com`. Resolving in the project root is what lets `--project` target + * a project from an unrelated checkout: the host travels with the project. */ -export function resolveRepo( +export function resolveRepoRef( project: ProjectHandle, - credentials: GithubCredentials["Service"], -): Effect.Effect { +): Effect.Effect { return Effect.gen(function* () { if (project.backend !== "github" || project.repo === undefined) return yield* new WayfulError({ message: "project is not configured for the github backend.", }); const [owner, repo] = project.repo.split("/"); - const remote = yield* resolveOriginRemote; - const host = Option.match(remote, { onNone: () => "github.com", onSome: (r) => r.host }); - const token = yield* credentials.token(host); - return { ref: { host, owner: owner!, repo: repo! }, token }; + let host = project.host; + if (host === undefined) { + const remote = yield* resolveOriginRemote(project.root); + host = Option.match(remote, { onNone: () => "github.com", onSome: (r) => r.host }); + } + return { host, owner: owner!, repo: repo! }; + }); +} + +/** + * The repo a github-backed project addresses, plus the token that may write to + * it. The host is `resolveRepoRef`'s, so an enterprise project resolves its own + * API base; the token then resolves against that host. + */ +export function resolveRepo( + project: ProjectHandle, + credentials: GithubCredentials["Service"], +): Effect.Effect { + return Effect.gen(function* () { + const ref = yield* resolveRepoRef(project); + const token = yield* credentials.token(ref.host); + return { ref, token }; }); } diff --git a/packages/cli/src/cli/cli.test.ts b/packages/cli/src/cli/cli.test.ts index d72ad5f..4ff6b25 100644 --- a/packages/cli/src/cli/cli.test.ts +++ b/packages/cli/src/cli/cli.test.ts @@ -114,7 +114,9 @@ describe("project and context contracts", () => { test("init creates versioned, timestamped metadata and the generic task type, then refuses overwrite", async () => { const project = await temporaryDirectory(); - expect(invoke(["init", "--description", "Refresh the site"], project).exitCode).toBe(0); + const initialized = invoke(["init", "--description", "Refresh the site"], project); + expect(initialized.exitCode).toBe(0); + expect(initialized.stdout).toContain("backend: filesystem"); const projectToml = await readFile(join(project, ".wayful", "project.toml"), "utf8"); expect(projectToml).toContain(`format_version = ${CURRENT_FORMAT_VERSION}`); expect(projectToml).toContain('backend = "filesystem"'); diff --git a/packages/cli/src/cli/cli.ts b/packages/cli/src/cli/cli.ts index 874451f..a129441 100644 --- a/packages/cli/src/cli/cli.ts +++ b/packages/cli/src/cli/cli.ts @@ -2,6 +2,7 @@ import { Command } from "effect/unstable/cli"; import { artifactCommand } from "@cli/commands/artifact"; import { contextCommand } from "@cli/commands/context"; +import { doctorCommand } from "@cli/commands/doctor"; import { goalCommand } from "@cli/commands/goal"; import { initCommand } from "@cli/commands/init"; import { labelCommand } from "@cli/commands/label"; @@ -21,6 +22,7 @@ export const cli = wayfulRoot.pipe( goalCommand, typeCommand, labelCommand, + doctorCommand, uiCommand, serveCommand, ]), diff --git a/packages/cli/src/cli/commands/doctor.test.ts b/packages/cli/src/cli/commands/doctor.test.ts new file mode 100644 index 0000000..2d13b34 --- /dev/null +++ b/packages/cli/src/cli/commands/doctor.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, test } from "bun:test"; +import { Option } from "effect"; + +import { rateLimitLine } from "@cli/commands/doctor"; +import { makeCliHarness } from "@test/support/cli-harness"; + +const { invoke, projectFixture } = makeCliHarness(); + +describe("wayful doctor", () => { + test("reports a filesystem project without failing for absent GitHub configuration", async () => { + const project = await projectFixture(); + const result = invoke(["doctor"], project); + expect(result.exitCode).toBe(0); + expect(result.stderr).toBe(""); + expect(result.stdout).toContain(`Project: ${project}`); + expect(result.stdout).toContain("Backend: filesystem"); + expect(result.stdout).toContain("GitHub: not applicable (filesystem backend)"); + }); +}); + +describe("rateLimitLine", () => { + test("renders the budget with its reset time", () => { + const line = rateLimitLine( + Option.some({ limit: 5000, remaining: 12, reset: 1700000000, resource: "core" }), + ); + expect(line).toBe( + `Rate limit: 12/5000 core remaining (resets at ${new Date(1700000000 * 1000).toISOString()})`, + ); + }); + + test("says so when the access check reported no budget", () => { + expect(rateLimitLine(Option.none())).toBe("Rate limit: not reported by the access check"); + }); +}); diff --git a/packages/cli/src/cli/commands/doctor.ts b/packages/cli/src/cli/commands/doctor.ts new file mode 100644 index 0000000..ff7c8bd --- /dev/null +++ b/packages/cli/src/cli/commands/doctor.ts @@ -0,0 +1,54 @@ +import { Console, DateTime, Effect, Option } from "effect"; +import { Command } from "effect/unstable/cli"; + +import { diagnoseGithub } from "@backend/github/doctor"; +import type { RateLimit } from "@backend/github/http"; +import { ProjectStore } from "@backend/ProjectStore"; +import { resolveProject, strict } from "@/scope"; +import { handle } from "@cli/render"; +import { wayfulRoot } from "@cli/root"; + +const formatReset = (epochSeconds: number): string => + epochSeconds > 0 + ? DateTime.formatIso(DateTime.makeUnsafe(epochSeconds * 1000)) + : "the next reset window"; + +/** The one-line rate-limit budget, or a note that the check did not report one. */ +export function rateLimitLine(rateLimit: Option.Option): string { + if (Option.isNone(rateLimit)) return "Rate limit: not reported by the access check"; + const budget = rateLimit.value; + return `Rate limit: ${budget.remaining}/${budget.limit} ${budget.resource} remaining (resets at ${formatReset(budget.reset)})`; +} + +export const doctorCommand = Command.make("doctor", {}, () => + handle( + false, + Effect.gen(function* () { + const root = yield* wayfulRoot; + const projectStore = yield* ProjectStore; + const project = yield* resolveProject(root.project); + yield* Console.log(`Project: ${project.root}`); + yield* Console.log(`Backend: ${project.backend}`); + + if (project.backend !== "github") { + yield* Console.log("GitHub: not applicable (filesystem backend)"); + return; + } + + const types = yield* strict(yield* projectStore.listTypes(project)); + const diagnosis = yield* diagnoseGithub( + project, + types.map((type) => type.name), + ); + yield* Console.log(`Repository: ${diagnosis.repository}`); + yield* Console.log(`Host: ${diagnosis.host}`); + yield* Console.log(`Credential: ${diagnosis.credential}`); + yield* Console.log(`Labels: ${diagnosis.labels.join(", ")}`); + yield* Console.log(rateLimitLine(diagnosis.rateLimit)); + }), + ), +).pipe( + Command.withDescription( + "Diagnose a project's backend, repository, credential, labels, and budget", + ), +); diff --git a/packages/cli/src/cli/commands/init-github.test.ts b/packages/cli/src/cli/commands/init-github.test.ts index c590c98..88729f5 100644 --- a/packages/cli/src/cli/commands/init-github.test.ts +++ b/packages/cli/src/cli/commands/init-github.test.ts @@ -1,7 +1,9 @@ import { describe, expect, test } from "bun:test"; -import { mkdir } from "node:fs/promises"; +import { mkdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; +import { initializedMessage } from "@cli/commands/init"; +import { CURRENT_FORMAT_VERSION } from "@domain/model"; import { expectCommandError, makeCliHarness } from "@test/support/cli-harness"; const { temporaryDirectory, invoke } = makeCliHarness(); @@ -59,4 +61,62 @@ describe("init --backend github", () => { expectCommandError(result); expect(result.stderr).toContain("run 'gh auth login', or set GH_TOKEN"); }); + + test("refuses an existing project before touching the remote", async () => { + const project = await temporaryDirectory(); + await mkdir(join(project, ".wayful"), { recursive: true }); + await writeFile( + join(project, ".wayful", "project.toml"), + `format_version = ${CURRENT_FORMAT_VERSION}\ndescription = "Existing"\nbackend = "filesystem"\ncreated_at = "2024-01-01T00:00:00.000Z"\nupdated_at = "2024-01-01T00:00:00.000Z"\n`, + ); + const result = invoke( + ["init", "--backend", "github", "--repo", "acme/widgets"], + project, + await unauthenticatedEnvironment(), + ); + expectCommandError(result); + expect(result.stderr).toContain("Wayful state already exists"); + // Reaching the remote would have failed on the missing credential instead. + expect(result.stderr).not.toContain("gh auth login"); + }); + + test("refuses from a subdirectory of an existing project", async () => { + const project = await temporaryDirectory(); + await mkdir(join(project, ".wayful"), { recursive: true }); + await writeFile( + join(project, ".wayful", "project.toml"), + `format_version = ${CURRENT_FORMAT_VERSION}\ndescription = "Existing"\nbackend = "filesystem"\ncreated_at = "2024-01-01T00:00:00.000Z"\nupdated_at = "2024-01-01T00:00:00.000Z"\n`, + ); + const nested = join(project, "nested"); + await mkdir(nested, { recursive: true }); + const result = invoke( + ["init", "--backend", "github", "--repo", "acme/widgets"], + nested, + await unauthenticatedEnvironment(), + ); + expectCommandError(result); + expect(result.stderr).toContain("Wayful state already exists"); + expect(result.stderr).not.toContain("gh auth login"); + }); +}); + +describe("initializedMessage", () => { + test("names the backend for a filesystem project", () => { + expect(initializedMessage({ directory: "/work", backend: "filesystem" })).toBe( + "Initialized Wayful project (backend: filesystem) in /work.", + ); + }); + + test("names the backend, repository, and host for a github project", () => { + expect( + initializedMessage({ + directory: "/work", + backend: "github", + repo: "acme/widgets", + host: "github.example.com", + }), + ).toBe( + "Initialized Wayful project (backend: github, repository: acme/widgets, host: github.example.com) in /work.", + ); + }); }); diff --git a/packages/cli/src/cli/commands/init.ts b/packages/cli/src/cli/commands/init.ts index 1848b76..ecd2a5b 100644 --- a/packages/cli/src/cli/commands/init.ts +++ b/packages/cli/src/cli/commands/init.ts @@ -10,9 +10,29 @@ import { WAYFUL_LABELS } from "@backend/github/labels"; import { resolveOriginRemote } from "@backend/github/remote"; import { WayfulError } from "@domain/errors"; import { nonEmpty } from "@domain/identifier"; +import type { ProjectBackend } from "@domain/model"; +import { fail } from "@/scope"; import { handle } from "@cli/render"; import { wayfulRoot } from "@cli/root"; +const EXISTING_PROJECT_MESSAGE = "Wayful state already exists; refusing to overwrite it."; + +/** + * The human report `wayful init` prints, naming the backend it bound the + * project to and, for github, the repository and host. + */ +export function initializedMessage(options: { + readonly directory: string; + readonly backend: ProjectBackend; + readonly repo?: string; + readonly host?: string; +}): string { + const details = [`backend: ${options.backend}`]; + if (options.repo !== undefined) details.push(`repository: ${options.repo}`); + if (options.host !== undefined) details.push(`host: ${options.host}`); + return `Initialized Wayful project (${details.join(", ")}) in ${options.directory}.`; +} + export const initCommand = Command.make( "init", { @@ -43,20 +63,27 @@ export const initCommand = Command.make( onSome: (value) => liftSync(() => nonEmpty(value, "project description")), }); + if (backend !== "github" && Option.isSome(repo)) + return yield* new WayfulError({ message: "--repo requires --backend github." }); + if (backend === "github" && Option.isSome(repo) && !REPO_PATTERN.test(repo.value)) + return yield* new WayfulError({ + message: `--repo must be in the form "owner/name".`, + }); + + // Checked before any remote work: a repeat init must leave the remote + // untouched rather than verifying access and creating labels first. + if (yield* projectStore.projectExists(directory)) + return yield* fail(EXISTING_PROJECT_MESSAGE); + if (backend !== "github") { - if (Option.isSome(repo)) - return yield* new WayfulError({ message: "--repo requires --backend github." }); yield* projectStore.initProject({ directory, description: resolvedDescription, backend }); - yield* Console.log("Initialized Wayful project."); + yield* Console.log(initializedMessage({ directory, backend })); return; } - if (Option.isSome(repo) && !REPO_PATTERN.test(repo.value)) - return yield* new WayfulError({ - message: `--repo must be in the form "owner/name".`, - }); - - const remote = yield* resolveOriginRemote; + // The remote is read in the directory being initialised, not the + // process working directory, so the recorded host matches the project. + const remote = yield* resolveOriginRemote(directory); const host = Option.match(remote, { onNone: () => "github.com", onSome: (r) => r.host }); const ownerName = yield* Option.match(repo, { onSome: (value) => Effect.succeed(value), @@ -82,8 +109,9 @@ export const initCommand = Command.make( description: resolvedDescription, backend, repo: ownerName, + host, }); - yield* Console.log("Initialized Wayful project."); + yield* Console.log(initializedMessage({ directory, backend, repo: ownerName, host })); }), ), ).pipe(Command.withDescription("Initialize a Wayful project")); diff --git a/packages/cli/src/domain/model.ts b/packages/cli/src/domain/model.ts index 76e2123..00c94f4 100644 --- a/packages/cli/src/domain/model.ts +++ b/packages/cli/src/domain/model.ts @@ -12,6 +12,13 @@ export interface ProjectMetadata { readonly backend: ProjectBackend; /** Only present (and required) when `backend` is "github"; `owner/name`. */ readonly repo?: string; + /** + * The GitHub host the project was initialised against, recorded at init so a + * project always addresses the host it was bound to, regardless of the + * invocation directory. Absent on projects created before this key existed; + * those fall back to the git remote resolved in the project root. + */ + readonly host?: string; readonly created_at: string; readonly updated_at: string; } diff --git a/packages/cli/test/support/github/spawner.ts b/packages/cli/test/support/github/spawner.ts index bd5c002..c7c8863 100644 --- a/packages/cli/test/support/github/spawner.ts +++ b/packages/cli/test/support/github/spawner.ts @@ -1,6 +1,6 @@ import { Effect, Layer, PlatformError, Stream } from "effect"; import { ChildProcessSpawner } from "effect/unstable/process"; -import type { Command } from "effect/unstable/process/ChildProcess"; +import type { Command, CommandOptions } from "effect/unstable/process/ChildProcess"; const notImplemented = () => Effect.die(new Error("not stubbed")); const streamNotImplemented = () => Stream.die(new Error("not stubbed")); @@ -8,6 +8,9 @@ const streamNotImplemented = () => Stream.die(new Error("not stubbed")); const commandOf = (command: Command): readonly string[] => command["_tag"] === "StandardCommand" ? [command.command, ...command.args] : []; +const optionsOf = (command: Command): CommandOptions => + command["_tag"] === "StandardCommand" ? command.options : {}; + /** A fake failure a stubbed command can return, mirroring a real spawn failure. */ export const fakeSpawnFailure = (description: string): PlatformError.PlatformError => PlatformError.systemError({ @@ -24,7 +27,10 @@ export const fakeSpawnFailure = (description: string): PlatformError.PlatformErr * so callers can match on the exact invocation. */ export function stubChildProcessSpawner( - respond: (invocation: readonly string[]) => Effect.Effect, + respond: ( + invocation: readonly string[], + options: CommandOptions, + ) => Effect.Effect, ) { return Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, @@ -34,7 +40,7 @@ export function stubChildProcessSpawner( streamString: streamNotImplemented, streamLines: streamNotImplemented, lines: notImplemented, - string: (command) => respond(commandOf(command)), + string: (command) => respond(commandOf(command), optionsOf(command)), }), ); } diff --git a/packages/cli/test/support/github/store.ts b/packages/cli/test/support/github/store.ts index ce56b61..d552a8e 100644 --- a/packages/cli/test/support/github/store.ts +++ b/packages/cli/test/support/github/store.ts @@ -17,6 +17,8 @@ export interface GithubHarnessOptions { readonly remote?: string | null; /** The type library the store's snapshot reads; empty unless a test supplies one. */ readonly types?: readonly TypeDefinition[]; + /** Overrides the fixed success credential, e.g. to exercise credential failures. */ + readonly credentials?: GithubCredentials["Service"]; } /** A `ProjectStore` stub: types are on disk in production, a fixed set in tests. */ @@ -24,6 +26,7 @@ function stubProjectStore(types: readonly TypeDefinition[]) { return Layer.succeed( ProjectStore, ProjectStore.of({ + projectExists: () => Effect.die("ProjectStore.projectExists is not used by the github store"), initProject: () => Effect.void, openProject: () => Effect.die("ProjectStore.openProject is not used by the github store"), listTypes: () => Effect.succeed({ records: types, errors: [] }), @@ -52,7 +55,11 @@ export function githubInfra( }); const credentials = Layer.succeed( GithubCredentials, - GithubCredentials.of({ token: () => Effect.succeed(Redacted.make("test-token")) }), + options.credentials ?? + GithubCredentials.of({ + resolve: () => Effect.succeed({ token: Redacted.make("test-token"), source: "GH_TOKEN" }), + token: () => Effect.succeed(Redacted.make("test-token")), + }), ); return Layer.mergeAll( stubGithubHttp((request) => {