diff --git a/packages/cli/src/backend/filesystem/documents.ts b/packages/cli/src/backend/filesystem/documents.ts index 2a18694..1fd8f65 100644 --- a/packages/cli/src/backend/filesystem/documents.ts +++ b/packages/cli/src/backend/filesystem/documents.ts @@ -11,7 +11,10 @@ export function stringifyYaml(value: unknown): string { export function stringifyToml(value: Record): string { const text = Bun.TOML.stringify(value); - if (text === undefined) throw new WayfulError({ message: "cannot serialize TOML metadata." }); + if (text === undefined) + throw new WayfulError({ + message: "cannot serialize TOML metadata; the record has a value TOML cannot represent.", + }); return text.endsWith("\n") ? text : `${text}\n`; } @@ -19,7 +22,7 @@ export function parseYaml(text: string, where: string): unknown { try { return Bun.YAML.parse(text); } catch { - throw new WayfulError({ message: `malformed YAML in ${where}.` }); + throw new WayfulError({ message: `malformed YAML in ${where}; fix the file and retry.` }); } } @@ -27,7 +30,7 @@ export function parseToml(text: string, where: string): unknown { try { return Bun.TOML.parse(text); } catch { - throw new WayfulError({ message: `malformed TOML in ${where}.` }); + throw new WayfulError({ message: `malformed TOML in ${where}; fix the file and retry.` }); } } @@ -36,12 +39,19 @@ export function parseFrontmatter( where: string, ): { data: Record; body: string } { if (!text.startsWith("---\n")) - throw new WayfulError({ message: `malformed frontmatter in ${where}.` }); + throw new WayfulError({ + message: `malformed frontmatter in ${where}; fix the file and retry.`, + }); const end = text.indexOf("\n---", 4); - if (end < 0) throw new WayfulError({ message: `malformed frontmatter in ${where}.` }); + if (end < 0) + throw new WayfulError({ + message: `malformed frontmatter in ${where}; fix the file and retry.`, + }); const data = parseYaml(text.slice(4, end), where); if (!data || typeof data !== "object" || Array.isArray(data)) - throw new WayfulError({ message: `malformed frontmatter in ${where}.` }); + throw new WayfulError({ + message: `malformed frontmatter in ${where}; fix the file and retry.`, + }); return { data: data as Record, body: text.slice(end + 4).replace(/^\n/, "") }; } @@ -64,7 +74,9 @@ export function writeAtomic( ): Effect.Effect { return Effect.gen(function* () { const tmp = `${path}.tmp-${process.pid}-${yield* Clock.currentTimeMillis}-${(yield* Random.next).toString(36).slice(2)}`; - const onError = new WayfulError({ message: `cannot write ${path}.` }); + const onError = new WayfulError({ + message: `cannot write '${path}'; check that its directory exists and is writable.`, + }); yield* fs.writeFileString(tmp, text).pipe(Effect.mapError(() => onError)); yield* fs.rename(tmp, path).pipe(Effect.mapError(() => onError)); }); diff --git a/packages/cli/src/backend/filesystem/layer/ops/goal.ts b/packages/cli/src/backend/filesystem/layer/ops/goal.ts index 860ae90..35d9afa 100644 --- a/packages/cli/src/backend/filesystem/layer/ops/goal.ts +++ b/packages/cli/src/backend/filesystem/layer/ops/goal.ts @@ -1,6 +1,5 @@ import { Effect, FileSystem, Path } from "effect"; -import { WayfulError } from "@domain/errors"; import type { GoalRecord, NewGoalRecord } from "@domain/model"; import type { MapHandle } from "@backend/MapStore"; import { decodeGoal } from "@backend/filesystem/decode"; @@ -13,7 +12,13 @@ import { writeAtomic, } from "@backend/filesystem/documents"; import { goalFile, goalsDir, mapDir } from "@backend/filesystem/paths"; -import { accessError, collect, fail, goalToDocument } from "@backend/filesystem/layer/records"; +import { + accessError, + collect, + fail, + goalToDocument, + readDirError, +} from "@backend/filesystem/layer/records"; export function makeGoalOps(fs: FileSystem.FileSystem, path: Path.Path) { return { @@ -22,7 +27,7 @@ export function makeGoalOps(fs: FileSystem.FileSystem, path: Path.Path) { const dir = goalsDir(path, mapDir(path, map.project.root, map.name)); const files = yield* fs .readDirectory(dir) - .pipe(Effect.mapError(() => new WayfulError({ message: "cannot read goals." }))); + .pipe(Effect.mapError(() => readDirError(dir, "goals"))); const filenames = files.filter((file) => file.endsWith(".md")).toSorted(); const result = yield* collect( filenames, diff --git a/packages/cli/src/backend/filesystem/layer/ops/map.ts b/packages/cli/src/backend/filesystem/layer/ops/map.ts index 20d8197..fedbfc6 100644 --- a/packages/cli/src/backend/filesystem/layer/ops/map.ts +++ b/packages/cli/src/backend/filesystem/layer/ops/map.ts @@ -16,7 +16,7 @@ import { writeAtomic, } from "@backend/filesystem/documents"; import { goalFile, goalsDir, mapDir, mapFile, mapsDir, stepsDir } from "@backend/filesystem/paths"; -import { accessError, collect, fail } from "@backend/filesystem/layer/records"; +import { accessError, collect, fail, readDirError } from "@backend/filesystem/layer/records"; export function makeMapOps(fs: FileSystem.FileSystem, path: Path.Path) { const openMapHandle = ( @@ -79,7 +79,7 @@ export function makeMapOps(fs: FileSystem.FileSystem, path: Path.Path) { if (!exists) return { records: [], errors: [] }; const entries = yield* fs .readDirectory(dir) - .pipe(Effect.mapError(() => new WayfulError({ message: "cannot read project maps." }))); + .pipe(Effect.mapError(() => readDirError(dir, "project maps"))); const names: string[] = []; for (const name of entries.toSorted()) { const stat = yield* fs @@ -126,7 +126,9 @@ export function makeMapOps(fs: FileSystem.FileSystem, path: Path.Path) { const dir = mapDir(path, project.root, name); const exists = yield* fs.exists(dir).pipe(Effect.mapError(accessError)); if (exists) return yield* fail(`map '${name}' already exists.`); - const onCreateError = new WayfulError({ message: `cannot create map '${name}'.` }); + const onCreateError = new WayfulError({ + message: `cannot create map '${name}' under '${dir}'; check that the directory is writable.`, + }); yield* fs .makeDirectory(stepsDir(path, dir), { recursive: true }) .pipe(Effect.mapError(() => onCreateError)); diff --git a/packages/cli/src/backend/filesystem/layer/ops/project.ts b/packages/cli/src/backend/filesystem/layer/ops/project.ts index e0ce069..f9af65f 100644 --- a/packages/cli/src/backend/filesystem/layer/ops/project.ts +++ b/packages/cli/src/backend/filesystem/layer/ops/project.ts @@ -68,7 +68,9 @@ export function makeProjectOps(fs: FileSystem.FileSystem, path: Path.Path) { const wayfulDir = path.join(root, ".wayful"); const exists = yield* fs.exists(wayfulDir).pipe(Effect.mapError(accessError)); if (exists) return yield* fail("Wayful state already exists; refusing to overwrite it."); - const onCreateError = new WayfulError({ message: `cannot create ${root}.` }); + const onCreateError = new WayfulError({ + message: `cannot create '${root}'; check that the parent directory exists and is writable.`, + }); yield* fs .makeDirectory(typesDir(path, root), { recursive: true }) .pipe(Effect.mapError(() => onCreateError)); diff --git a/packages/cli/src/backend/filesystem/layer/ops/step.ts b/packages/cli/src/backend/filesystem/layer/ops/step.ts index 3a52fb2..e5aaa86 100644 --- a/packages/cli/src/backend/filesystem/layer/ops/step.ts +++ b/packages/cli/src/backend/filesystem/layer/ops/step.ts @@ -15,7 +15,13 @@ import { writeAtomic, } from "@backend/filesystem/documents"; import { mapDir, mapFile, stepFile, stepsDir } from "@backend/filesystem/paths"; -import { accessError, collect, fail, stepToDocument } from "@backend/filesystem/layer/records"; +import { + accessError, + collect, + fail, + readDirError, + stepToDocument, +} from "@backend/filesystem/layer/records"; export function makeStepOps(fs: FileSystem.FileSystem, path: Path.Path) { // Guards each map's `step_id_counter` read-modify-write so that two @@ -37,7 +43,7 @@ export function makeStepOps(fs: FileSystem.FileSystem, path: Path.Path) { const raw = (yield* liftSync(() => parseToml(text, file))) as Record; const counter = raw.step_id_counter; if (!Number.isInteger(counter) || (counter as number) < 1) - return yield* fail("malformed map metadata."); + return yield* fail(`map metadata in ${file} is missing a positive step_id_counter.`); yield* writeAtomic( fs, file, @@ -52,7 +58,7 @@ export function makeStepOps(fs: FileSystem.FileSystem, path: Path.Path) { const dir = stepsDir(path, mapDir(path, map.project.root, map.name)); const files = yield* fs .readDirectory(dir) - .pipe(Effect.mapError(() => new WayfulError({ message: "cannot read steps." }))); + .pipe(Effect.mapError(() => readDirError(dir, "steps"))); const filenames = files.filter((file) => file.endsWith(".md")).toSorted(); const result = yield* collect( filenames, diff --git a/packages/cli/src/backend/filesystem/layer/ops/type.ts b/packages/cli/src/backend/filesystem/layer/ops/type.ts index b3656a8..f969016 100644 --- a/packages/cli/src/backend/filesystem/layer/ops/type.ts +++ b/packages/cli/src/backend/filesystem/layer/ops/type.ts @@ -7,7 +7,7 @@ import type { ProjectHandle } from "@backend/ProjectStore"; import { decodeType } from "@backend/filesystem/decode"; import { liftSync, parseFrontmatter, readTextFile } from "@backend/filesystem/documents"; import { typeFile, typesDir } from "@backend/filesystem/paths"; -import { accessError, collect, fail } from "@backend/filesystem/layer/records"; +import { accessError, collect, fail, readDirError } from "@backend/filesystem/layer/records"; export function makeTypeOps(fs: FileSystem.FileSystem, path: Path.Path) { const readType = ( @@ -30,7 +30,7 @@ export function makeTypeOps(fs: FileSystem.FileSystem, path: Path.Path) { const dir = typesDir(path, project.root); const files = yield* fs .readDirectory(dir) - .pipe(Effect.mapError(() => new WayfulError({ message: "cannot read project types." }))); + .pipe(Effect.mapError(() => readDirError(dir, "project types"))); const names = files .filter((file) => file.endsWith(".md")) .map((file) => file.slice(0, -3)) diff --git a/packages/cli/src/backend/filesystem/layer/records.ts b/packages/cli/src/backend/filesystem/layer/records.ts index 114ad88..319a958 100644 --- a/packages/cli/src/backend/filesystem/layer/records.ts +++ b/packages/cli/src/backend/filesystem/layer/records.ts @@ -14,7 +14,17 @@ import { // `yield* fail(...)` rather than call a throwing helper directly. export const fail = (message: string) => Effect.fail(new WayfulError({ message })); -export const accessError = () => new WayfulError({ message: "cannot access filesystem." }); +export const accessError = () => + new WayfulError({ + message: + "cannot access a project file; check that the project exists and you have permission to read it.", + }); + +/** The named error a collection read produces when its directory cannot be listed. */ +export const readDirError = (dir: string, what: string) => + new WayfulError({ + message: `cannot read ${what} from '${dir}'; check that it exists and you have permission to read it.`, + }); /** * Runs `decode` for each item in `items`, collecting successes and turning diff --git a/packages/cli/src/backend/github/api.test.ts b/packages/cli/src/backend/github/api.test.ts index 9d0ce03..7acddf7 100644 --- a/packages/cli/src/backend/github/api.test.ts +++ b/packages/cli/src/backend/github/api.test.ts @@ -8,6 +8,7 @@ import { createIssue, ensureLabel, ensureLabels, + getIssue, listBlockedBy, listIssues, removeBlockedBy, @@ -85,6 +86,80 @@ describe("verifyAccess", () => { }); }); +describe("github failures name the problem and the remedy", () => { + async function failure(status: number, message: string) { + const layer = stubGithubHttp(() => jsonResponse(status, { message })); + return Effect.runPromise( + listIssues(repo, secretToken, { labels: ["wayful:map"] }).pipe( + Effect.flip, + Effect.provide(layer), + ), + ); + } + + test("an invalid credential says so and how to supply a working one", async () => { + const error = await failure(401, "Bad credentials"); + expect(error.message).toContain("acme/widgets"); + expect(error.message).toContain("invalid or expired"); + expect(error.message).toMatch(/gh auth login|GH_TOKEN/); + }); + + test("a credential that cannot reach the repo says so without suggesting a new sign-in", async () => { + const error = await failure(403, "Resource not accessible by integration"); + expect(error.message).toContain("cannot access acme/widgets"); + expect(error.message).not.toContain("gh auth login"); + expect(error.message).not.toMatch(/sign in/i); + }); + + test("a missing repository names it and says it is not found or not visible", async () => { + const error = await failure(404, "Not Found"); + expect(error.message).toContain("acme/widgets"); + expect(error.message).toMatch(/not exist|not be visible/); + }); + + test("an unexpected status keeps GitHub's own explanation", async () => { + const error = await failure(422, "Validation Failed"); + expect(error.message).toContain("422"); + expect(error.message).toContain("Validation Failed"); + }); + + test("a missing resource names the resource and its repository", async () => { + const layer = stubGithubHttp(() => jsonResponse(404, { message: "Not Found" })); + const error = await Effect.runPromise( + getIssue(repo, secretToken, 7).pipe(Effect.flip, Effect.provide(layer)), + ); + expect(error.message).toContain("issue #7"); + expect(error.message).toContain("acme/widgets"); + }); +}); + +describe("verifyAccess failures", () => { + async function failure(status: number, body: unknown) { + const layer = stubGithubHttp(() => jsonResponse(status, body)); + return Effect.runPromise( + verifyAccess(repo, secretToken).pipe(Effect.flip, Effect.provide(layer)), + ); + } + + test("a 401 reports an invalid or expired credential, not a permissions problem", async () => { + const error = await failure(401, { message: "Bad credentials" }); + expect(error.message).toContain("invalid or expired"); + expect(error.message).toMatch(/gh auth login|GH_TOKEN/); + }); + + test("a 403 reports an access problem without suggesting a new sign-in", async () => { + const error = await failure(403, { message: "Forbidden" }); + expect(error.message).toContain("cannot access"); + expect(error.message).not.toMatch(/gh auth login|sign in/i); + }); + + test("a 404 names the repository as not found or not visible", async () => { + const error = await failure(404, { message: "Not Found" }); + expect(error.message).toContain("acme/widgets"); + expect(error.message).toMatch(/not exist|not be visible/); + }); +}); + describe("ensureLabel", () => { test("succeeds when the label is created", async () => { const layer = stubGithubHttp((request) => { diff --git a/packages/cli/src/backend/github/api.ts b/packages/cli/src/backend/github/api.ts index 21ae17e..b1f5938 100644 --- a/packages/cli/src/backend/github/api.ts +++ b/packages/cli/src/backend/github/api.ts @@ -1,8 +1,15 @@ import { DateTime, Effect, Option, Redacted } from "effect"; -import { HttpClientRequest } from "effect/unstable/http"; +import { HttpClientRequest, type HttpClientResponse } from "effect/unstable/http"; -import { WayfulError } from "@domain/errors"; -import { GithubHttp, requestFailed } from "@backend/github/http"; +import { oneLine, WayfulError } from "@domain/errors"; +import { + GithubHttp, + GithubRequestError, + githubMessage, + githubRequestError, + unreadableResponse, + type GithubFailure, +} from "@backend/github/http"; import type { GithubIssue } from "@backend/github/issue"; import type { GitRemoteRef } from "@backend/github/remote"; import { subIssueCapError } from "@backend/github/subIssues"; @@ -20,9 +27,58 @@ export function apiBase(host: string): ApiBase { return { rest: `https://${host}/api/v3`, graphql: `https://${host}/api/graphql` }; } -function insufficientAccess(repo: GitRemoteRef): WayfulError { - return new WayfulError({ - message: `github token cannot access ${repo.owner}/${repo.repo}; run 'gh auth login' with repo scope or check the token's permissions.`, +export function repoLabel(repo: GitRemoteRef): string { + return `${repo.owner}/${repo.repo}`; +} + +/** + * Phrases a classified transport failure in the caller's terms. The transport + * reports *what kind* of failure it was; only the caller knows whether the + * repository itself or a named resource within it was being addressed, and + * each of the four kinds has a different remedy. + */ +export function githubFailure( + repo: GitRemoteRef, + failure: GithubFailure, + resource?: string, +): WayfulError { + const where = resource === undefined ? repoLabel(repo) : `${resource} in ${repoLabel(repo)}`; + switch (failure.kind) { + case "unauthenticated": + return new WayfulError({ + message: `the github credential for ${where} is invalid or expired (status ${failure.status}); run 'gh auth login' or set GH_TOKEN to supply a working token.`, + }); + case "forbidden": + return new WayfulError({ + message: `the github credential is valid but cannot access ${where} (status ${failure.status}); check the token's repository access and scope.`, + }); + case "not-found": + return new WayfulError({ + message: + resource === undefined + ? `github cannot find ${where} (status ${failure.status}); it may not exist or may not be visible to the current credential.` + : `github cannot find ${where} (status ${failure.status}); it may have been deleted, renamed, or not be visible to the current credential.`, + }); + case "unexpected": + return new WayfulError({ + message: `github could not complete the request for ${where} (status ${failure.status})${failure.message ? `: ${oneLine(failure.message)}` : "."}`, + }); + } +} + +/** Fails with the caller-terms message for a non-2xx response. */ +export function responseFailure( + repo: GitRemoteRef, + response: HttpClientResponse.HttpClientResponse, + resource?: string, +): Effect.Effect { + return Effect.gen(function* () { + const text = yield* response.text.pipe(Effect.orElseSucceed(() => "")); + return yield* githubFailure( + repo, + githubRequestError(response.status, githubMessage(text)), + resource, + ); }); } @@ -42,9 +98,21 @@ function execute(request: HttpClientRequest.HttpClientRequest) { return Effect.flatMap(GithubHttp, (http) => http.execute(request)); } -/** A conditional `GET` through the shared transport, cached and revalidated with ETags. */ -function fetchJson(request: HttpClientRequest.HttpClientRequest) { - return Effect.flatMap(GithubHttp, (http) => http.getJson(request)); +/** + * A conditional `GET` through the shared transport, cached and revalidated with + * ETags. The transport's classified failure is rewritten with the repository + * the request addressed, so the message names what was being read. + */ +function fetchJson( + repo: GitRemoteRef, + request: HttpClientRequest.HttpClientRequest, + resource?: string, +) { + return Effect.flatMap(GithubHttp, (http) => http.getJson(request)).pipe( + Effect.mapError((error) => + error instanceof GithubRequestError ? githubFailure(repo, error, resource) : error, + ), + ); } /** @@ -62,14 +130,10 @@ export function verifyAccess( token, ); const response = yield* execute(request); - if (response.status === 401 || response.status === 403 || response.status === 404) { - return yield* insufficientAccess(repo); - } - if (response.status < 200 || response.status >= 300) { - return yield* requestFailed(`unexpected status ${response.status}.`); - } + if (response.status < 200 || response.status >= 300) + return yield* responseFailure(repo, response); const body = yield* response.json.pipe( - Effect.mapError((error) => requestFailed(error.message)), + Effect.mapError((error) => unreadableResponse(error.message)), ); const permissions = Option.fromNullishOr( (body as { permissions?: { push?: boolean } }).permissions, @@ -78,7 +142,10 @@ export function verifyAccess( onNone: () => false, onSome: (p) => p.push === true, }); - if (!canPush) return yield* insufficientAccess(repo); + if (!canPush) + return yield* new WayfulError({ + message: `the github credential is valid but cannot push to ${repoLabel(repo)}; check the token's repository access and scope.`, + }); }); } @@ -102,9 +169,7 @@ export function ensureLabel( ).pipe(HttpClientRequest.bodyJsonUnsafe(label)); const response = yield* execute(request); if (response.status === 201 || response.status === 422) return; - return yield* requestFailed( - `could not create label "${label.name}" (status ${response.status}).`, - ); + return yield* responseFailure(repo, response, `label "${label.name}"`); }); } @@ -185,6 +250,7 @@ export interface ListIssuesOptions { * listing so both follow pagination identically. */ function listPaginated( + repo: GitRemoteRef, token: Redacted.Redacted, initialUrl: string, ): Effect.Effect { @@ -192,8 +258,14 @@ function listPaginated( const issues: GithubIssue[] = []; let next: string | undefined = initialUrl; while (next !== undefined) { - const { value, headers } = yield* fetchJson(authorized(HttpClientRequest.get(next), token)); - if (!Array.isArray(value)) return yield* requestFailed("expected a JSON array of issues."); + const { value, headers } = yield* fetchJson( + repo, + authorized(HttpClientRequest.get(next), token), + ); + if (!Array.isArray(value)) + return yield* new WayfulError({ + message: `github returned an unexpected response for ${repoLabel(repo)}; expected a JSON array of issues.`, + }); for (const raw of value) { const issue = normalizeIssue(raw); if (issue) issues.push(issue); @@ -219,7 +291,7 @@ export function listIssues( url.searchParams.set("per_page", "100"); url.searchParams.set("state", options.state ?? "open"); if (options.labels?.length) url.searchParams.set("labels", options.labels.join(",")); - return listPaginated(token, url.toString()); + return listPaginated(repo, token, url.toString()); } /** Every sub-issue of `parent`, which is how a map's steps and goals are listed. */ @@ -230,7 +302,7 @@ export function listSubIssues( ): Effect.Effect { const base = apiBase(repo.host); const url = `${base.rest}/repos/${repo.owner}/${repo.repo}/issues/${parent}/sub_issues?per_page=100`; - return listPaginated(token, url); + return listPaginated(repo, token, url); } /** @@ -245,7 +317,7 @@ export function listBlockedBy( ): Effect.Effect { const base = apiBase(repo.host); const url = `${base.rest}/repos/${repo.owner}/${repo.repo}/issues/${number}/dependencies/blocked_by?per_page=100`; - return listPaginated(token, url); + return listPaginated(repo, token, url); } /** One issue by number, or a `WayfulError` when it cannot be read. */ @@ -257,13 +329,18 @@ export function getIssue( return Effect.gen(function* () { const base = apiBase(repo.host); const { value } = yield* fetchJson( + repo, authorized( HttpClientRequest.get(`${base.rest}/repos/${repo.owner}/${repo.repo}/issues/${number}`), token, ), + `issue #${number}`, ); const issue = normalizeIssue(value); - if (!issue) return yield* requestFailed(`could not read issue #${number}.`); + if (!issue) + return yield* new WayfulError({ + message: `github returned an unexpected representation of issue #${number} in ${repoLabel(repo)}.`, + }); return issue; }); } @@ -292,7 +369,7 @@ export function updateIssue( ).pipe(HttpClientRequest.bodyJsonUnsafe(patch)); const response = yield* execute(request); if (response.status < 200 || response.status >= 300) - return yield* requestFailed(`could not update issue #${number}.`); + return yield* responseFailure(repo, response, `issue #${number}`); }); } @@ -314,7 +391,7 @@ export function addLabels( ).pipe(HttpClientRequest.bodyJsonUnsafe({ labels })); const response = yield* execute(request); if (response.status < 200 || response.status >= 300) - return yield* requestFailed(`could not label issue #${number}.`); + return yield* responseFailure(repo, response, `issue #${number}`); }); } @@ -335,7 +412,7 @@ export function removeLabel( ); const response = yield* execute(request); if (response.status === 200 || response.status === 404) return; - return yield* requestFailed(`could not remove label from issue #${number}.`); + return yield* responseFailure(repo, response, `issue #${number}`); }); } @@ -358,9 +435,7 @@ export function addSubIssue( if (response.status === 201) return; // GitHub rejects the 101st sub-issue with 422; that is a cap, not a raw failure. if (response.status === 422) return yield* subIssueCapError(); - return yield* requestFailed( - `could not add sub-issue to #${parent} (status ${response.status}).`, - ); + return yield* responseFailure(repo, response, `issue #${parent}`); }); } @@ -385,9 +460,7 @@ export function addBlockedBy( ).pipe(HttpClientRequest.bodyJsonUnsafe({ issue_id: blockingIssueId })); const response = yield* execute(request); if (response.status === 201) return; - return yield* requestFailed( - `could not add a dependency to issue #${number} (status ${response.status}).`, - ); + return yield* responseFailure(repo, response, `issue #${number}`); }); } @@ -408,9 +481,7 @@ export function removeBlockedBy( ); const response = yield* execute(request); if (response.status === 200) return; - return yield* requestFailed( - `could not remove a dependency from issue #${number} (status ${response.status}).`, - ); + return yield* responseFailure(repo, response, `issue #${number}`); }); } @@ -439,13 +510,15 @@ export function createIssue( }), ); const response = yield* execute(request); - if (response.status !== 201) - return yield* requestFailed(`could not create issue (status ${response.status}).`); + if (response.status !== 201) return yield* responseFailure(repo, response, "a new issue"); const body = yield* response.json.pipe( - Effect.mapError((error) => requestFailed(error.message)), + Effect.mapError((error) => unreadableResponse(error.message)), ); const created = normalizeIssue(body); - if (!created) return yield* requestFailed("the created issue could not be read."); + if (!created) + return yield* new WayfulError({ + message: `github returned an unexpected representation of the created issue in ${repoLabel(repo)}.`, + }); return created; }); } diff --git a/packages/cli/src/backend/github/graphql.test.ts b/packages/cli/src/backend/github/graphql.test.ts index 1c8f164..2abd476 100644 --- a/packages/cli/src/backend/github/graphql.test.ts +++ b/packages/cli/src/backend/github/graphql.test.ts @@ -80,14 +80,27 @@ describe("readMapSnapshot", () => { () => jsonResponse(200, { data: { repository: { issue: null } } }), Effect.flip(readMapSnapshot(repo, token, 10)), ); - expect(error.message).toContain("map #10 was not found"); + expect(error.message).toContain("map #10"); + expect(error.message).toContain("acme/widgets"); + expect(error.message).toMatch(/not exist|not be visible/); }); - test("fails clearly on a non-2xx response", async () => { + test("keeps GitHub's own message on an unexpected non-2xx response", async () => { const error = await runGithub( () => jsonResponse(500, { message: "server error" }), Effect.flip(readMapSnapshot(repo, token, 10)), ); - expect(error.message).toContain("graphql snapshot failed with status 500"); + expect(error.message).toContain("acme/widgets"); + expect(error.message).toContain("500"); + expect(error.message).toContain("server error"); + }); + + test("classifies a bad credential on the graphql transport", async () => { + const error = await runGithub( + () => jsonResponse(401, { message: "Bad credentials" }), + Effect.flip(readMapSnapshot(repo, token, 10)), + ); + expect(error.message).toContain("invalid or expired"); + expect(error.message).toMatch(/gh auth login|GH_TOKEN/); }); }); diff --git a/packages/cli/src/backend/github/graphql.ts b/packages/cli/src/backend/github/graphql.ts index 8369205..6be238f 100644 --- a/packages/cli/src/backend/github/graphql.ts +++ b/packages/cli/src/backend/github/graphql.ts @@ -1,9 +1,9 @@ import { DateTime, Effect, Option, Redacted } from "effect"; import { HttpClientRequest } from "effect/unstable/http"; -import { WayfulError } from "@domain/errors"; -import { apiBase, authorized } from "@backend/github/api"; -import { GithubHttp, requestFailed } from "@backend/github/http"; +import { oneLine, WayfulError } from "@domain/errors"; +import { apiBase, authorized, repoLabel, responseFailure } from "@backend/github/api"; +import { GithubHttp } from "@backend/github/http"; import type { GithubIssue } from "@backend/github/issue"; import type { GitRemoteRef } from "@backend/github/remote"; @@ -134,21 +134,34 @@ export function readMapSnapshot( ); const response = yield* http.execute(request); if (response.status < 200 || response.status >= 300) - return yield* requestFailed(`graphql snapshot failed with status ${response.status}.`); + return yield* responseFailure(repo, response, `map #${number}`); const body = (yield* response.json.pipe( - Effect.mapError((error) => requestFailed(error.message)), + Effect.mapError( + (error) => + new WayfulError({ + message: `github returned an unreadable map snapshot for ${repoLabel(repo)}: ${error.message}.`, + }), + ), )) as { readonly data?: { readonly repository?: { readonly issue?: unknown } | null } | null; readonly errors?: unknown; }; const graphqlError = graphqlMessage(body.errors); - if (graphqlError) return yield* requestFailed(graphqlError); + if (graphqlError) + return yield* new WayfulError({ + message: `github rejected the map snapshot request for ${repoLabel(repo)}: ${oneLine(graphqlError)}.`, + }); const raw = body.data?.repository?.issue; if (!raw || typeof raw !== "object") - return yield* requestFailed(`map #${number} was not found.`); + return yield* new WayfulError({ + message: `github cannot find map #${number} in ${repoLabel(repo)}; it may not exist or may not be visible to the current credential.`, + }); const node = raw as Record; const map = normalizeIssue(node); - if (!map) return yield* requestFailed(`map #${number} could not be read.`); + if (!map) + return yield* new WayfulError({ + message: `github returned an unexpected representation of map #${number} in ${repoLabel(repo)}.`, + }); const subIssues = (node.subIssues as { nodes?: unknown } | undefined)?.nodes; const children: SnapshotChild[] = []; diff --git a/packages/cli/src/backend/github/http.test.ts b/packages/cli/src/backend/github/http.test.ts index 3d0bb75..0dce90d 100644 --- a/packages/cli/src/backend/github/http.test.ts +++ b/packages/cli/src/backend/github/http.test.ts @@ -184,6 +184,40 @@ describe("GithubHttp: rate-limit budgeting", () => { }); }); +describe("GithubHttp: response classification", () => { + const cases: ReadonlyArray = [ + [401, "unauthenticated"], + [403, "forbidden"], + [404, "not-found"], + [500, "unexpected"], + ]; + for (const [status, kind] of cases) { + test(`classifies a ${status} response as ${kind}`, async () => { + const error = await run( + () => jsonResponse(status, { message: "nope" }), + Effect.gen(function* () { + const http = yield* GithubHttp; + return yield* Effect.flip(http.getJson(HttpClientRequest.get(url))); + }), + ); + expect((error as { _tag?: string })["_tag"]).toBe("GithubRequestError"); + expect((error as { kind?: string }).kind).toBe(kind); + expect((error as { status?: number }).status).toBe(status); + }); + } + + test("keeps GitHub's own message alongside the classified status", async () => { + const error = await run( + () => jsonResponse(422, { message: "Validation Failed" }), + Effect.gen(function* () { + const http = yield* GithubHttp; + return yield* Effect.flip(http.getJson(HttpClientRequest.get(url))); + }), + ); + expect((error as { message?: string }).message).toContain("Validation Failed"); + }); +}); + describe("makeGithubHttp", () => { test("does not classify a generic 403 as a rate limit", async () => { const result = await run( diff --git a/packages/cli/src/backend/github/http.ts b/packages/cli/src/backend/github/http.ts index 5f47d30..10eaaeb 100644 --- a/packages/cli/src/backend/github/http.ts +++ b/packages/cli/src/backend/github/http.ts @@ -1,4 +1,4 @@ -import { Context, DateTime, Effect, Layer, Option, Ref } from "effect"; +import { Context, Data, DateTime, Effect, Layer, Option, Ref } from "effect"; import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"; import { WayfulError } from "@domain/errors"; @@ -37,7 +37,7 @@ export interface GithubHttpService { */ readonly getJson: ( request: HttpClientRequest.HttpClientRequest, - ) => Effect.Effect; + ) => Effect.Effect; /** The last rate-limit budget observed, for budgeting and for tests. */ readonly rateLimit: Effect.Effect>; } @@ -46,8 +46,58 @@ export class GithubHttp extends Context.Service() "wayful/GithubHttp", ) {} -export function requestFailed(reason: string): WayfulError { - return new WayfulError({ message: `github api request failed: ${reason}` }); +/** The network itself failed before GitHub answered. */ +export function networkFailed(reason: string): WayfulError { + return new WayfulError({ + message: `github request failed: ${reason}; check your network connection and try again.`, + }); +} + +/** GitHub answered, but not with JSON wayful can read. */ +export function unreadableResponse(reason: string): WayfulError { + return new WayfulError({ message: `github sent a response that could not be read: ${reason}.` }); +} + +/** + * The kind of a non-2xx GitHub response, independent of which resource was + * requested. The transport reports this and the caller phrases it: an invalid + * credential, a credential that cannot reach a repository, a repository or + * resource that is missing, and everything else each need a different remedy. + */ +export type GithubFailureKind = "unauthenticated" | "forbidden" | "not-found" | "unexpected"; + +export function classifyStatus(status: number): GithubFailureKind { + if (status === 401) return "unauthenticated"; + if (status === 403) return "forbidden"; + if (status === 404) return "not-found"; + return "unexpected"; +} + +/** + * A non-2xx GitHub response, classified so a caller can report it in its own + * terms. `message` is GitHub's own explanation when it sent one, kept for the + * `unexpected` case where no generic remedy exists. + */ +export interface GithubFailure { + readonly status: number; + readonly kind: GithubFailureKind; + readonly message: string; +} + +export class GithubRequestError extends Data.TaggedError("GithubRequestError") {} + +export function githubRequestError(status: number, message: string): GithubRequestError { + return new GithubRequestError({ status, kind: classifyStatus(status), message }); +} + +/** GitHub's own human message from a JSON error body, or an empty string. */ +export function githubMessage(text: string): string { + try { + const parsed = JSON.parse(text) as { message?: unknown }; + return typeof parsed?.message === "string" ? parsed.message : ""; + } catch { + return ""; + } } function headerInt(headers: Readonly>, name: string): number | undefined { @@ -106,15 +156,6 @@ function primaryRateLimitError(headers: Readonly>): Wayfu }); } -function messageOf(text: string): string { - try { - const parsed = JSON.parse(text) as { message?: unknown }; - return typeof parsed?.message === "string" ? parsed.message : ""; - } catch { - return ""; - } -} - /** * Classifies a `403`/`429` as a primary or secondary rate limit. A primary * limit is exhausted budget; a secondary one is a burst (`retry-after`, an @@ -169,7 +210,7 @@ export function makeGithubHttp(client: HttpClient.HttpClient): Effect.Effect requestFailed(error.message))); + .pipe(Effect.mapError((error) => networkFailed(error.message))); // A 304 is GitHub's own way of saying "nothing changed, this is free": // it neither carries a body nor spends budget, so leave both alone. @@ -180,7 +221,7 @@ export function makeGithubHttp(client: HttpClient.HttpClient): Effect.Effect "")); - const limit = classifyRateLimit(response.status, response.headers, messageOf(text)); + const limit = classifyRateLimit(response.status, response.headers, githubMessage(text)); if (limit !== undefined) return yield* limit; // Not a rate limit: hand the response back intact for the caller. return rebuild(request, response, text); @@ -200,11 +241,13 @@ export function makeGithubHttp(client: HttpClient.HttpClient): Effect.Effect= 300) - return yield* requestFailed(`unexpected status ${response.status}.`); + if (response.status < 200 || response.status >= 300) { + const text = yield* response.text.pipe(Effect.orElseSucceed(() => "")); + return yield* githubRequestError(response.status, githubMessage(text)); + } const value = yield* response.json.pipe( - Effect.mapError((error) => requestFailed(error.message)), + Effect.mapError((error) => unreadableResponse(error.message)), ); const etag = response.headers["etag"]; const read = { value, headers: response.headers }; diff --git a/packages/cli/src/backend/github/mapStore.test.ts b/packages/cli/src/backend/github/mapStore.test.ts index 36bc404..13091d0 100644 --- a/packages/cli/src/backend/github/mapStore.test.ts +++ b/packages/cli/src/backend/github/mapStore.test.ts @@ -267,6 +267,37 @@ describe("GithubMapStore: listMaps", () => { }); }); +describe("GithubMapStore: failures name the problem and the remedy", () => { + async function listFailure(status: number, message: string) { + return run( + () => jsonResponse(status, { message }), + Effect.gen(function* () { + const store = yield* MapStore; + return yield* Effect.flip(store.listMaps(project)); + }), + ); + } + + test("an invalid credential points at how to supply a working one", async () => { + const error = await listFailure(401, "Bad credentials"); + expect(error.message).toContain("acme/widgets"); + expect(error.message).toContain("invalid or expired"); + expect(error.message).toMatch(/gh auth login|GH_TOKEN/); + }); + + test("a credential that cannot reach the repository is not told to sign in again", async () => { + const error = await listFailure(403, "Resource not accessible"); + expect(error.message).toContain("cannot access acme/widgets"); + expect(error.message).not.toMatch(/gh auth login|sign in/i); + }); + + test("a repository that is not visible is named and described", async () => { + const error = await listFailure(404, "Not Found"); + expect(error.message).toContain("acme/widgets"); + expect(error.message).toMatch(/not exist|not be visible/); + }); +}); + describe("GithubMapStore: openMap", () => { test("resolves a kebab-case name to its issue", async () => { const map = await run( diff --git a/packages/cli/src/cli/report.ts b/packages/cli/src/cli/report.ts index a911f32..39c7b50 100644 --- a/packages/cli/src/cli/report.ts +++ b/packages/cli/src/cli/report.ts @@ -1,5 +1,7 @@ import { Console, Effect, Schema } from "effect"; +import { oneLine } from "@domain/errors"; + const errorOutputJson = Schema.fromJsonString(Schema.Struct({ error: Schema.String })); /** @@ -17,11 +19,12 @@ export function report(options: { readonly usageHint?: string; }): Effect.Effect { return Effect.gen(function* () { - yield* Console.error(`wayful: ${options.message}`); + const message = oneLine(options.message); + yield* Console.error(`wayful: ${message}`); if (options.usageHint) yield* Console.error(`wayful: ${options.usageHint}`); if (options.json) yield* Console.log( - yield* Schema.encodeEffect(errorOutputJson)({ error: options.message }).pipe(Effect.orDie), + yield* Schema.encodeEffect(errorOutputJson)({ error: message }).pipe(Effect.orDie), ); process.exitCode = 2; }); diff --git a/packages/cli/src/domain/errors.test.ts b/packages/cli/src/domain/errors.test.ts new file mode 100644 index 0000000..f60c405 --- /dev/null +++ b/packages/cli/src/domain/errors.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, test } from "bun:test"; + +import { oneLine } from "@domain/errors"; + +describe("oneLine", () => { + test("keeps a single-line diagnosis untouched", () => { + expect(oneLine("map 'plan' does not exist.")).toBe("map 'plan' does not exist."); + }); + + test("collapses a multi-line backend message onto one line", () => { + expect(oneLine("github rejected the request:\n Validation Failed\n field is required")).toBe( + "github rejected the request: Validation Failed field is required", + ); + }); + + test("never leaves a leading or trailing blank line", () => { + expect(oneLine("\n broken\n")).toBe("broken"); + }); +}); diff --git a/packages/cli/src/domain/errors.ts b/packages/cli/src/domain/errors.ts index 5fe5543..6e36f5b 100644 --- a/packages/cli/src/domain/errors.ts +++ b/packages/cli/src/domain/errors.ts @@ -7,3 +7,13 @@ export class WayfulError extends Data.TaggedError("WayfulError")<{ export class MapMetadataError extends Data.TaggedError("MapMetadataError")<{ readonly message: string; }> {} + +/** + * Collapses a diagnosis onto one line. A backend can hand back a message with + * embedded newlines (a GitHub error body, a multi-error decode); the contract + * every surface renders is one `wayful:`-prefixed line per message, never a + * paragraph or a stack trace. + */ +export function oneLine(message: string): string { + return message.replace(/\s*\n\s*/g, " ").trim(); +} diff --git a/packages/cli/src/scope.ts b/packages/cli/src/scope.ts index 7f62081..b533296 100644 --- a/packages/cli/src/scope.ts +++ b/packages/cli/src/scope.ts @@ -72,9 +72,10 @@ export function resolveMap( if (map.metadata.allowed_step_types !== undefined) { const types = yield* projectStore.listTypes(project); const known = new Set(types.records.map((type) => type.name)); - if (map.metadata.allowed_step_types.some((type) => !known.has(type))) + const unknown = map.metadata.allowed_step_types.filter((type) => !known.has(type)); + if (unknown.length) return yield* new MapMetadataError({ - message: "map allowed_step_types contains an unknown project type.", + message: `map '${map.name}' allows unknown step type(s): ${unknown.join(", ")}; known types are ${[...known].toSorted().join(", ") || "none"}.`, }); } return map; diff --git a/packages/cli/src/server/http.ts b/packages/cli/src/server/http.ts index f8abe6d..ccb2920 100644 --- a/packages/cli/src/server/http.ts +++ b/packages/cli/src/server/http.ts @@ -165,7 +165,7 @@ export function startServer( }), catch: (cause) => new WayfulError({ - message: `cannot listen on ${config.host}:${config.port} (${String(cause)}).`, + message: `cannot listen on ${config.host}:${config.port} (${String(cause)}); stop the process using that port or choose another with --port.`, }), }).pipe(Effect.tapError(() => Effect.sync(() => stopWatching())));