diff --git a/CHANGELOG.md b/CHANGELOG.md index 54587445..357073a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 2.1.0 + +### Added + +- `loopway setup`: an interactive walk through what loopway needs, safe to run again. It checks `gh` (and offers `gh auth login`), Claude Code, the bot user's token (checked against GitHub, saved to `~/.loopway/config.json` for you alone) and offers `.loopway/dev.md` and `review.md` here, for the repos you name. It only asks about what is missing and never overwrites a file. See [#556](https://github.com/craftmilldev/loopway/issues/556). + ## 2.0.3 ### Added diff --git a/README.md b/README.md index 2e26aef3..62b00061 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ npm install && npm run build # Node 22+ gh auth login # loopway acts as whoever gh is logged in as ``` -Or install the latest release: `npm install -g https://github.com/craftmilldev/loopway/releases/latest/download/loopway-cli.tgz`. +After installing, run `loopway setup` (see [Setup](#setup)). Or install the latest release: `npm install -g https://github.com/craftmilldev/loopway/releases/latest/download/loopway-cli.tgz`. Make a directory to run it from, with a `.loopway/` folder holding one file per bot (`scratch/` inside the checkout is git-ignored): @@ -55,6 +55,17 @@ To run it from a directory outside the checkout, `npm link -w @loopway/cli` puts The first run starts now: it does not replay history. An issue or pull request from before that stays quiet until something happens to it; then, if it is open, it is reported as new, with only what happened since as updates, and its bots start threads. After that it remembers where it got to, so a restart prints nothing twice and picks up what happened while it was stopped. +## Setup + +`loopway setup` is an interactive walk through what loopway needs, in a terminal (it refuses to run without one). Each step checks first and only asks about what is missing, so it is safe to run again on a machine that is already set up: it never overwrites a file you have, and the steps that can be left out say so. + +1. **`gh`**, required. It must be installed and logged in; if it isn't logged in, setup offers to run `gh auth login` for you. It says who you are logged in as. Without a working login it stops. +2. **Claude Code**, which runs the sessions. It checks `claude --version`; if it isn't there, setup says where to get it and carries on. +3. **The bot user**, optional. If `~/.loopway/config.json` has a bot token, setup checks GitHub accepts it and says whose it is. Otherwise it asks for the token of a separate GitHub account (typed as dots, never printed), checks it, refuses your own account's (the bot would comment as you), and saves it as the `github` block with the account's login as `name` and its `users.noreply.github.com` address as `email`. The file is written for you alone (0600) and its other keys are kept. Skipping leaves sessions off. +4. **The bot files**, optional, one each for `.loopway/dev.md` and `.loopway/review.md` in the directory you ran it from. It asks which repos they should watch (guessing from `git remote origin`), warns about one `gh` can't see, and writes the files from the examples under [Bots](#bots-loopway). A file that is already there is left alone. + +It ends by telling you to run `loopway` and assign an issue to yourself. + ## Threads A **thread** is one bot plus the subjects it tracks. The rules are in each bot's front matter (see below), and they are deterministic: diff --git a/docs/developing.md b/docs/developing.md index f342322e..fbb3136d 100644 --- a/docs/developing.md +++ b/docs/developing.md @@ -53,6 +53,7 @@ When CI passes on a push to `main` and `packages/cli` changed since the last `cl | `tui-header.tsx`, `tui-theme.ts` | The header (version, poller status) and the pinned keys; the colors, taken from the billboard | | `tui-log.ts` | The session log as turn blocks, one row per line, and the tool call sentences | | `tui-input.tsx`, `tui-text.ts` | The chat text box (cursor, editing); the thread state and grouping, and the poller's status line | +| `setup.ts`, `setup-io.tsx` | `loopway setup`: the steps (gh, Claude Code, the bot token, the bot files), written against an `Io` interface so tests script the answers and the fake `exec` and `fetch` keep them off the machine and the network; and the real `Io`, one inline [Ink](https://github.com/vadimdemedev/ink) question at a time (`gh auth login` gets the terminal itself) | | `format.ts` | The printed line, and `--json` | `tools/init-scratch.mjs` (`npm run init-scratch`) is a plain Node script, outside the packages; `test/init-scratch.test.ts` runs it in a temp dir. diff --git a/packages/cli/package.json b/packages/cli/package.json index c9be6e2d..d8f441ee 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@loopway/cli", - "version": "2.0.3", + "version": "2.1.0", "private": true, "license": "MIT", "description": "loopway: polls GitHub and prints every new subject and every update to one you know.", diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.ts index b148f97b..55322ad1 100644 --- a/packages/cli/src/config.ts +++ b/packages/cli/src/config.ts @@ -1,4 +1,4 @@ -import { readFile } from "node:fs/promises"; +import { chmod, mkdir, readFile, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import { join } from "node:path"; @@ -42,3 +42,16 @@ export async function loadAutoUpdate(home: string, env: NodeJS.ProcessEnv = proc if (env.LOOPWAY_NO_UPDATE) return false; return (await readConfig(home)).auto_update !== false; } + +/** + * Sets the `github` block of config.json and leaves every other key as it was. The file holds a token, so it is + * written for you alone (0600), in a folder made if need be. + */ +export async function saveGitHubConfig(home: string, github: GitHubConfig): Promise { + const config = await readConfig(home); + const block = { ...(config.github as Record | undefined), ...github }; + await mkdir(home, { recursive: true }); + const path = join(home, "config.json"); + await writeFile(path, JSON.stringify({ ...config, github: block }, null, 2) + "\n", { mode: 0o600 }); + await chmod(path, 0o600); // writeFile's mode only applies to a new file +} diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 9fb78e15..99a5e0d3 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -8,6 +8,8 @@ import { loadAutoUpdate, loadGitHubConfig, loopwayHome, type GitHubConfig } from import { formatJson, formatLine, formatThread, formatThreadJson, type LoopwayEvent } from "./format.js"; import { ghToken, GitHubSource } from "./github.js"; import { startMcp } from "./mcp.js"; +import { inkIo, SetupCancelled } from "./setup-io.js"; +import { runSetup } from "./setup.js"; import { Poller } from "./poller.js"; import { Sessions } from "./sessions.js"; import type { Subject } from "./source.js"; @@ -31,10 +33,15 @@ and every update to the ones it knows. Usage: loopway [--no-tui] [--json] [--max N] loopway threads [--json] + loopway setup In a terminal it opens a TUI: the open threads and those closed in the last 3 days. Enter opens a thread, q quits. With --no-tui, --json, or output that isn't a terminal, it prints a plain log instead. +\`loopway setup\` walks you through what loopway needs: gh logged in, Claude Code, the bot user's token (optional) and +.loopway/dev.md and review.md here (optional). It checks each first, only asks about what is missing, and never +overwrites a file. + Each new issue or pull request starts a thread for every bot whose rules ask for it (on: issue, on: pull_request), and every update to it goes on the queue of the open threads that hold it. Each thread's queue goes to a Claude Code session that acts as the bot user and talks back through loopway's own MCP tool. \`loopway threads\` lists the open @@ -92,6 +99,23 @@ async function main(): Promise { } const project = projectDir(); + if (positionals[0] === "setup") { + if (!process.stdout.isTTY || !process.stdin.isTTY) + throw new Error("loopway setup asks questions: run it in a terminal."); + const io = inkIo(); + try { + return await runSetup({ io, home: loopwayHome(), cwd: project }); + } catch (err) { + if (err instanceof SetupCancelled) { + await io.close(); + console.error("Cancelled: nothing more was changed."); + return 1; + } + throw err; + } finally { + await io.close(); + } + } if (positionals[0] === "threads") return listThreads(stateDir(loopwayHome(), project), values.json); if (positionals.length > 0) throw new Error(`Unknown command "${positionals[0]}". Try loopway --help.`); diff --git a/packages/cli/src/setup-io.tsx b/packages/cli/src/setup-io.tsx new file mode 100644 index 00000000..5f6d943a --- /dev/null +++ b/packages/cli/src/setup-io.tsx @@ -0,0 +1,164 @@ +import { Box, render, Static, Text, useInput } from "ink"; +import { useEffect, useState } from "react"; +import { runInherited, type Io } from "./setup.js"; +import { editInput, emptyInput, InputLine, type InputState } from "./tui-input.js"; +import { theme } from "./tui-theme.js"; + +const MARKS = { ok: "✓", warn: "!", fail: "✗" } as const; + +/** What is being asked: a choice from a list, or a line of text (dots, for a secret). */ +export type Question = + | { kind: "choose"; question: string; options: { value: string; label: string }[] } + | { kind: "text"; question: string; initial?: string; secret?: boolean }; + +/** The choices, as drawn: the one at `at` is marked. */ +export function Choose({ question, options, at }: { question: string; options: { label: string }[]; at: number }) { + return ( + + ? {question} + {options.map((o, i) => ( + + {i === at ? "❯ " : " "} + {o.label} + + ))} + ↑/↓ to move, Enter to choose + + ); +} + +/** The line being typed, as drawn: a secret shows as dots of the same length, so editing behaves as with text. */ +export function Prompt({ question, input, secret }: { question: string; input: InputState; secret?: boolean }) { + const shown = secret ? { ...input, value: "•".repeat(input.value.length) } : input; + return ( + + ? {question} + + ❯ + + + + ); +} + +/** What the screen shows: the lines said so far, and the question being asked, if any. */ +/** Ctrl-C at a question: setup stops, and says so. */ +export class SetupCancelled extends Error { + constructor() { + super("Cancelled."); + } +} + +class Store { + reject?: (err: Error) => void; + lines: { id: number; text: string }[] = []; + question?: Question; + answer?: (value: string) => void; + private listeners = new Set<() => void>(); + subscribe(fn: () => void) { + this.listeners.add(fn); + return () => void this.listeners.delete(fn); + } + change(fn: () => void) { + fn(); + for (const l of this.listeners) l(); + } + /** A new array each time: `Static` only looks again when it gets a different one. */ + say(text: string) { + this.change(() => (this.lines = [...this.lines, { id: this.lines.length, text }])); + } +} + +/** + * One app for the whole walk, with one `useInput` for the whole of it. Questions that came and went each with their + * own `useInput` dropped the terminal out of raw mode between them, and a token typed then was echoed as plain text. + */ +function Screen({ store }: { store: Store }) { + const [, tick] = useState(0); + const [at, setAt] = useState(0); + const [input, setInput] = useState(emptyInput); + useEffect(() => store.subscribe(() => tick((n) => n + 1)), [store]); + const q = store.question; + // A new question starts at its first choice, or its initial text. + useEffect(() => { + setAt(0); + const initial = q?.kind === "text" ? (q.initial ?? "") : ""; + setInput({ value: initial, cursor: initial.length }); + }, [q]); + useInput((typed, key) => { + if (key.ctrl && typed === "c") { + if (store.reject) store.reject(new SetupCancelled()); + else process.exit(1); // between questions, while something is being checked + return; + } + if (!q || !store.answer) return; + if (q.kind === "choose") { + if (key.upArrow) setAt((i) => Math.max(0, i - 1)); + else if (key.downArrow) setAt((i) => Math.min(q.options.length - 1, i + 1)); + else if (key.return) store.answer(q.options[at]!.value); + } else if (key.return) store.answer(input.value); + else setInput((s) => editInput(s, typed, key)); + }); + return ( + <> + {(line) => {line.text}} + {q?.kind === "choose" && } + {q?.kind === "text" && } + + ); +} + +/** + * The real terminal for `loopway setup`: Ink for the questions, with the lines said above them. `close` ends it. + */ +export function inkIo(): Io & { close: () => Promise } { + let store = new Store(); + let app: ReturnType | undefined; + // exitOnCtrlC off: Ink would unmount without settling the question, and setup would end quietly with code 0. + const open = () => (app ??= render(, { exitOnCtrlC: false })); + const ask = (question: Question) => { + open(); + return new Promise((resolve, reject) => { + store.reject = reject; + store.change(() => { + store.question = question; + store.answer = (value) => { + // The answered question stays on screen as a line. + store.say( + `? ${question.question} ${question.kind === "text" && question.secret ? "•".repeat(value.length) : value}`, + ); + store.change(() => { + store.question = undefined; + store.answer = undefined; + store.reject = undefined; + }); + resolve(value); + }; + }); + }); + }; + const close = async () => { + const current = app; + app = undefined; + // Ink draws at most every ~30 ms: let the last lines said (the closing "Done.") reach the screen before it stops. + if (current) await new Promise((resolve) => setTimeout(resolve, 150)); + current?.unmount(); + await current?.waitUntilExit(); + }; + return { + say: (line, tone) => { + open(); + store.say(tone ? `${MARKS[tone]} ${line}` : line); + }, + choose: ((question, options) => ask({ kind: "choose", question, options })) as Io["choose"], + text: (question, initial) => ask({ kind: "text", question, initial }), + secret: (question) => ask({ kind: "text", question, secret: true }), + // gh auth login asks its own questions: give it the terminal, and start again after it, with a clean screen. + run: async (command, args) => { + await close(); + store = new Store(); + return runInherited(command, args); + }, + close, + }; +} diff --git a/packages/cli/src/setup.ts b/packages/cli/src/setup.ts new file mode 100644 index 00000000..19e50cd5 --- /dev/null +++ b/packages/cli/src/setup.ts @@ -0,0 +1,246 @@ +import { execFileSync, spawnSync } from "node:child_process"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { loadGitHubConfig, saveGitHubConfig } from "./config.js"; + +/** What `loopway setup` needs from the terminal. The real one is Ink (setup-io.tsx); tests script it. */ +export interface Io { + say: (line: string, tone?: "ok" | "warn" | "fail") => void; + choose: (question: string, options: { value: T; label: string }[]) => Promise; + text: (question: string, initial?: string) => Promise; + /** Like `text`, but shows dots: for a token. */ + secret: (question: string) => Promise; + /** Runs a command with the terminal handed over (`gh auth login` asks its own questions). Its exit code. */ + run: (command: string, args: string[]) => Promise; +} + +export interface SetupDeps { + io: Io; + /** `~/.loopway`: where the bot's token goes. */ + home: string; + /** Where `.loopway/` is made. */ + cwd: string; + env?: NodeJS.ProcessEnv; + fetch?: typeof globalThis.fetch; + /** A command's output, or undefined when it isn't there or failed. */ + exec?: (command: string, args: string[]) => string | undefined; +} + +const REPO = /^[\w.-]+\/[\w.-]+$/; + +const defaultExec = (command: string, args: string[]) => { + try { + return execFileSync(command, args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); + } catch { + return undefined; + } +}; + +/** Runs a command with the terminal inherited. */ +export const runInherited = async (command: string, args: string[]) => + spawnSync(command, args, { stdio: "inherit" }).status ?? 1; + +const bot = (repos: string[], on: string, prompt: string) => + `---\nrepos: [${repos.join(", ")}]\non: ${on}\n---\n\n${prompt}\n`; + +/** The two starter bot files: the ones in the README. */ +export const BOT_FILES = { + "dev.md": (repos: string[]) => + bot( + repos, + "issue", + "You are the dev bot. When an issue is assigned to you, read it, make the change on a branch, run the tests, and open\na pull request that says `Closes #N`. Ask on the issue when something is unclear.", + ), + "review.md": (repos: string[]) => + bot( + repos, + "pull_request", + "You are the review bot. Read the pull request and its diff, check it against the issue it closes, and leave a\nreview. Be specific, and say what you ran.", + ), +}; + +/** `owner/name` from a GitHub remote URL (https or ssh), or undefined. */ +export function repoFromRemote(url: string | undefined): string | undefined { + const match = /github\.com[:/]([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/.exec(url ?? ""); + return match?.[1]; +} + +/** + * Walks through what loopway needs: `gh` logged in, Claude Code, the bot user's token, and the bot files. Each step + * checks first and only asks about what is missing; nothing is overwritten, and the steps that can be left out say + * so. Returns the exit code: 1 when a step loopway can't run without was not done. + */ +export async function runSetup(deps: SetupDeps): Promise { + const { io, home, cwd } = deps; + const env = deps.env ?? process.env; + const exec = deps.exec ?? defaultExec; + const api = deps.fetch ?? globalThis.fetch; + const get = (token: string, path: string) => + api(`https://api.github.com${path}`, { + headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json", "user-agent": "loopway" }, + }).catch(() => undefined); + /** Who a token is; `offline` when GitHub couldn't be reached at all, which is not the same as refusing the token. */ + type Who = { login: string; id: number } | "rejected" | "offline"; + const who = async (token: string): Promise => { + const res = await get(token, "/user"); + if (!res) return "offline"; + return res.ok ? ((await res.json()) as { login: string; id: number }) : "rejected"; + }; + const known = (w: Who | undefined): w is { login: string; id: number } => typeof w === "object"; + + io.say("loopway setup: each step checks first, and only asks about what is missing."); + + // 1. gh, which loopway acts as you through. Required. + if (exec("gh", ["--version"]) === undefined) { + io.say("gh isn't installed. Install it from https://cli.github.com, then run `loopway setup` again.", "fail"); + return 1; + } + // The same order as ghToken (github.ts), but through `exec` so a test never reaches the real gh. + const login = () => env.GH_TOKEN || env.GITHUB_TOKEN || exec("gh", ["auth", "token"]) || undefined; + let token = login(); + if (!token) { + const answer = await io.choose("gh isn't logged in to GitHub.", [ + { value: "login", label: "Log in now (runs `gh auth login`)" }, + { value: "stop", label: "Stop here" }, + ]); + if (answer === "login") { + await io.run("gh", ["auth", "login"]); + token = login(); + } + } + const me = token ? await who(token) : undefined; + if (!token || !known(me)) { + io.say( + !token + ? "No gh login, and loopway can't run without one." + : me === "offline" + ? "Couldn't reach GitHub: check your connection and run `loopway setup` again." + : "GitHub didn't accept the gh login.", + "fail", + ); + return 1; + } + io.say(`gh is logged in as ${me.login}.`, "ok"); + + // 2. Claude Code, which runs the sessions. Setup carries on without it: it's only needed to run one. + const claude = exec("claude", ["--version"]); + if (claude === undefined) { + io.say( + "Claude Code isn't on your PATH. Sessions need it: install it from https://claude.com/claude-code. Carrying on.", + "warn", + ); + } else io.say(`Claude Code is installed (${claude}).`, "ok"); + + // 3. The bot user. Optional: without its token loopway watches and queues, but runs no sessions. + const config = await loadGitHubConfig(home); + let botDone = false; + let botToken: string | undefined; + if (config.token) { + const existing = await who(config.token); + if (known(existing)) { + io.say(`The bot user is ${existing.login} (from ${join(home, "config.json")}).`, "ok"); + botDone = true; + botToken = config.token; + } else if (existing === "offline") { + io.say("Couldn't reach GitHub to check the bot's saved token: leaving it as it is.", "warn"); + botDone = true; + botToken = config.token; + } else io.say(`The token in ${join(home, "config.json")} isn't accepted by GitHub.`, "warn"); + } + let skipped = false; + while (!botDone && !skipped) { + const answer = await io.choose( + "A bot user acts on your issues so it isn't you commenting. It's a separate GitHub account with its own token.", + [ + { value: "add", label: "Add the bot's token" }, + { value: "skip", label: "Skip it: loopway will watch and queue, but run no sessions" }, + ], + ); + if (answer === "skip") { + skipped = true; + break; + } + const given = (await io.secret("The bot account's GitHub token (a personal access token with repo scope)")).trim(); + const bot = given ? await who(given) : "rejected"; + if (bot === "offline") io.say("Couldn't reach GitHub to check that token: try again.", "fail"); + else if (!known(bot)) io.say("GitHub didn't accept that token.", "fail"); + else if (bot.login.toLowerCase() === me.login.toLowerCase()) + io.say( + `That token is your own account (${me.login}): the bot would comment as you. Use another account's.`, + "warn", + ); + else { + await saveGitHubConfig(home, { + token: given, + name: bot.login, + email: `${bot.id}+${bot.login}@users.noreply.github.com`, + }); + io.say(`Saved ${bot.login} as the bot user in ${join(home, "config.json")}.`, "ok"); + botDone = true; + botToken = given; + } + } + if (skipped) io.say("Skipped the bot user: sessions are off until you add one (run `loopway setup` again).", "warn"); + + // 4. The bot files in .loopway/. Never overwrites one. + const folder = join(cwd, ".loopway"); + const missing: string[] = []; + for (const file of Object.keys(BOT_FILES)) { + const present = await readFile(join(folder, file), "utf8").then( + () => true, + () => false, + ); + if (present) io.say(`.loopway/${file} is already here: left as it is.`, "ok"); + else missing.push(file); + } + const wanted: string[] = []; + for (const file of missing) { + const answer = await io.choose(`Add .loopway/${file} here (${cwd})?`, [ + { value: "yes", label: "Yes" }, + { value: "no", label: "No, skip it" }, + ]); + if (answer === "yes") wanted.push(file); + else io.say(`Skipped .loopway/${file}.`, "warn"); + } + if (wanted.length > 0) { + const repos = await askRepos(io, repoFromRemote(exec("git", ["-C", cwd, "remote", "get-url", "origin"]))); + for (const repo of repos) { + const found = await get(token, `/repos/${repo}`); + if (!found?.ok) + io.say(`Couldn't see ${repo} as ${me.login}: check the name and your access. Using it anyway.`, "warn"); + // A new bot account usually hasn't been added to the repo yet: that is what stops its sessions. + if (botToken && !(await get(botToken, `/repos/${repo}`))?.ok) + io.say( + `The bot user can't see ${repo}: add it as a collaborator, or its sessions can't read or comment.`, + "warn", + ); + } + await mkdir(folder, { recursive: true }); + for (const file of wanted) { + const make = BOT_FILES[file as keyof typeof BOT_FILES]; + try { + await writeFile(join(folder, file), make(repos), { flag: "wx" }); // wx: if it showed up meanwhile, keep it + io.say(`Wrote .loopway/${file} for ${repos.join(", ")}.`, "ok"); + } catch (err) { + if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err; + io.say(`.loopway/${file} appeared meanwhile: left as it is.`, "warn"); + } + } + } + + io.say("Done. Run `loopway` here, then create an issue on GitHub and assign it to yourself.", "ok"); + return 0; +} + +/** Asks for `owner/name`, comma separated, until every one is well formed. */ +async function askRepos(io: Io, guess: string | undefined): Promise { + for (;;) { + const answer = await io.text("Which repos should the bots watch? (owner/name, separated by commas)", guess); + const repos = answer + .split(",") + .map((r) => r.trim()) + .filter(Boolean); + if (repos.length > 0 && repos.every((r) => REPO.test(r))) return repos; + io.say(`"${answer}" isn't a list of owner/name.`, "fail"); + } +} diff --git a/packages/cli/test/setup-io.test.tsx b/packages/cli/test/setup-io.test.tsx new file mode 100644 index 00000000..1acadc17 --- /dev/null +++ b/packages/cli/test/setup-io.test.tsx @@ -0,0 +1,21 @@ +import { render } from "ink-testing-library"; +import { stripVTControlCharacters as plain } from "node:util"; +import { describe, expect, it } from "vitest"; +import { Choose, Prompt } from "../src/setup-io.js"; + +describe("the setup questions as drawn", () => { + it("Choose marks the option at the cursor", () => { + const app = render(); + const screen = plain(app.lastFrame() ?? ""); + expect(screen).toContain(" Alpha"); + expect(screen).toContain("❯ Beta"); + app.unmount(); + }); + + it("Prompt shows a secret as dots", () => { + const app = render(); + expect(plain(app.lastFrame() ?? "")).toContain("•••"); + expect(plain(app.lastFrame() ?? "")).not.toContain("abc"); + app.unmount(); + }); +}); diff --git a/packages/cli/test/setup.test.ts b/packages/cli/test/setup.test.ts new file mode 100644 index 00000000..f7307022 --- /dev/null +++ b/packages/cli/test/setup.test.ts @@ -0,0 +1,217 @@ +import { mkdir, mkdtemp, readFile, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { parseBot } from "../src/bots.js"; +import { repoFromRemote, runSetup, type Io, type SetupDeps } from "../src/setup.js"; + +/** A scripted terminal: answers come off a queue, and everything said and asked is kept. */ +function script(answers: string[]) { + const said: string[] = []; + const asked: string[] = []; + const ran: string[] = []; + const next = (question: string) => { + asked.push(question); + const answer = answers.shift(); + if (answer === undefined) throw new Error(`unexpected question: ${question}`); + return answer; + }; + const io: Io = { + say: (line, tone) => said.push(`${tone ?? "-"} ${line}`), + choose: async (question) => next(question) as never, + text: async (question) => next(question), + secret: async (question) => next(question), + run: async (command, args) => { + ran.push([command, ...args].join(" ")); + return 0; + }, + }; + return { io, said, asked, ran }; +} + +const users: Record = { + mytoken: { login: "me", id: 1 }, + bottoken: { login: "the-bot", id: 77 }, +}; +const repos = new Set(["o/r"]); + +/** GitHub: /user by token, and /repos/ for the repos in `repos`. */ +const fakeFetch = (async (url: string, init: { headers: Record }) => { + const token = init.headers.authorization!.replace("Bearer ", ""); + const path = url.replace("https://api.github.com", ""); + if (path === "/user") { + const user = users[token]; + return user ? Response.json(user) : new Response("{}", { status: 401 }); + } + return new Response("{}", { status: repos.has(path.replace("/repos/", "")) ? 200 : 404 }); +}) as unknown as typeof fetch; + +async function setup(more: Partial = {}, answers: string[] = []) { + const root = await mkdtemp(join(tmpdir(), "loopway-setup-")); + const home = join(root, "home"); + const cwd = join(root, "project"); + await mkdir(cwd, { recursive: true }); + const terminal = script(answers); + const deps: SetupDeps = { + io: terminal.io, + home, + cwd, + env: { GH_TOKEN: "mytoken" }, + fetch: fakeFetch, + exec: (command, args) => + command === "claude" ? "2.1.0 (Claude Code)" : command === "git" ? "git@github.com:o/r.git" : args[0] ? "ok" : "", + ...more, + }; + return { ...terminal, deps, home, cwd, run: () => runSetup(deps) }; +} + +/** gh is installed but has no login; nothing else is there. */ +const onlyGhVersion = (c: string, args: string[]) => (c === "gh" && args[0] === "--version" ? "gh version" : undefined); + +describe("loopway setup", () => { + it("walks a fresh machine: bot token, then both bot files for the guessed repo", async () => { + const t = await setup({}, ["add", "bottoken", "yes", "yes", "o/r"]); + expect(await t.run()).toBe(0); + expect(t.said.join("\n")).toMatch(/gh is logged in as me/); + expect(t.said.join("\n")).toMatch(/Claude Code is installed/); + const config = JSON.parse(await readFile(join(t.home, "config.json"), "utf8")); + expect(config.github).toEqual({ + token: "bottoken", + name: "the-bot", + email: "77+the-bot@users.noreply.github.com", + }); + expect((await stat(join(t.home, "config.json"))).mode & 0o777).toBe(0o600); + for (const [file, on] of [ + ["dev.md", "issue"], + ["review.md", "pull_request"], + ] as const) { + const bot = parseBot(file.slice(0, -3), await readFile(join(t.cwd, ".loopway", file), "utf8")); + expect(bot.repos).toEqual(["o/r"]); + expect(bot.on).toEqual([on]); + } + expect(t.said.join("\n")).not.toContain("bottoken"); // the token is never printed + }); + + it("asks nothing when everything is already set up, and changes nothing", async () => { + const t = await setup(); + await mkdir(join(t.home), { recursive: true }); + await writeFile(join(t.home, "config.json"), JSON.stringify({ auto_update: false, github: { token: "bottoken" } })); + await mkdir(join(t.cwd, ".loopway")); + await writeFile(join(t.cwd, ".loopway", "dev.md"), "mine"); + await writeFile(join(t.cwd, ".loopway", "review.md"), "mine too"); + expect(await t.run()).toBe(0); + expect(t.asked).toEqual([]); + expect(await readFile(join(t.cwd, ".loopway", "dev.md"), "utf8")).toBe("mine"); + expect(JSON.parse(await readFile(join(t.home, "config.json"), "utf8")).auto_update).toBe(false); + }); + + it("lets the bot user and each bot file be skipped", async () => { + // No claude and no git remote, so the repo is asked. + const t2 = await setup( + { env: { GH_TOKEN: "mytoken" }, exec: (c, a) => (c === "gh" && a[0] === "--version" ? "gh version" : undefined) }, + ["skip", "yes", "no", "o/r"], + ); + expect(await t2.run()).toBe(0); + expect(t2.said.join("\n")).toMatch(/warn Claude Code isn't on your PATH/); + expect(t2.said.join("\n")).toMatch(/sessions are off/); + await expect(stat(join(t2.home, "config.json"))).rejects.toThrow(); + await expect(readFile(join(t2.cwd, ".loopway", "dev.md"), "utf8")).resolves.toContain("repos: [o/r]"); + await expect(stat(join(t2.cwd, ".loopway", "review.md"))).rejects.toThrow(); + }); + + it("offers gh auth login when gh has no login, and stops when it is declined or still fails", async () => { + const t = await setup({ env: {}, exec: onlyGhVersion }, ["login"]); + expect(await t.run()).toBe(1); + expect(t.ran).toEqual(["gh auth login"]); + const declined = await setup({ env: {}, exec: onlyGhVersion }, ["stop"]); + expect(await declined.run()).toBe(1); + expect(declined.ran).toEqual([]); + }); + + it("stops when gh isn't installed", async () => { + const t = await setup({ exec: () => undefined }); + expect(await t.run()).toBe(1); + expect(t.said.join("\n")).toMatch(/fail gh isn't installed/); + }); + + it("refuses a bad token and your own account's, and asks again", async () => { + users.mytoken2 = { login: "me", id: 1 }; + const t = await setup({}, ["add", "nonsense", "add", "mytoken2", "skip", "no", "no"]); + expect(await t.run()).toBe(0); + const said = t.said.join("\n"); + expect(said).toMatch(/GitHub didn't accept that token/); + expect(said).toMatch(/your own account \(me\)/); + await expect(stat(join(t.home, "config.json"))).rejects.toThrow(); + }); + + it("replaces a bot token GitHub no longer accepts, and keeps the rest of config.json", async () => { + const t = await setup({}, ["add", "bottoken", "no", "no"]); + await mkdir(t.home, { recursive: true }); + await writeFile(join(t.home, "config.json"), JSON.stringify({ auto_update: false, github: { token: "stale" } })); + expect(await t.run()).toBe(0); + const config = JSON.parse(await readFile(join(t.home, "config.json"), "utf8")); + expect(config.auto_update).toBe(false); + expect(config.github.token).toBe("bottoken"); + }); + + it("asks again for a repo that isn't owner/name, and warns about one it can't see, but still writes", async () => { + const t = await setup({ exec: (c) => (c === "git" ? undefined : "ok") }, ["skip", "yes", "no", "nope", "a/b, c/d"]); + expect(await t.run()).toBe(0); + const said = t.said.join("\n"); + expect(said).toMatch(/"nope" isn't a list of owner\/name/); + expect(said).toMatch(/Couldn't see a\/b/); + expect(await readFile(join(t.cwd, ".loopway", "dev.md"), "utf8")).toContain("repos: [a/b, c/d]"); + }); + + it("tells being offline from a refused token: a saved bot token is kept, and the gh login is not blamed", async () => { + const offline = (async () => { + throw new Error("ENOTFOUND"); + }) as unknown as typeof fetch; + const gh = await setup({ fetch: offline }); + expect(await gh.run()).toBe(1); + expect(gh.said.join("\n")).toMatch(/Couldn't reach GitHub/); + expect(gh.said.join("\n")).not.toMatch(/didn't accept/); + + // gh answers, the bot's saved token's check fails by network only: kept, no question about replacing it. + let calls = 0; + const flaky = (async (url: string, init: { headers: Record }) => { + if (++calls > 1) throw new Error("ENOTFOUND"); + return fakeFetch(url, init); + }) as unknown as typeof fetch; + const t = await setup({ fetch: flaky }, []); + await mkdir(t.home, { recursive: true }); + await writeFile(join(t.home, "config.json"), JSON.stringify({ github: { token: "bottoken" } })); + await mkdir(join(t.cwd, ".loopway")); + for (const f of ["dev.md", "review.md"]) await writeFile(join(t.cwd, ".loopway", f), "x"); + expect(await t.run()).toBe(0); + expect(t.said.join("\n")).toMatch(/leaving it as it is/); + expect(t.asked).toEqual([]); + }); + + it("warns when the bot user can't see a repo you can", async () => { + repos.add("o/mine"); + const t = await setup({ exec: (c) => (c === "git" ? undefined : "ok") }, [ + "add", + "bottoken", + "yes", + "yes", + "o/mine", + ]); + // the bot's token sees only o/r, yours sees o/mine too + const base = t.deps.fetch!; + t.deps.fetch = (async (url: string, init: { headers: Record }) => + init.headers.authorization === "Bearer bottoken" && url.endsWith("/repos/o/mine") + ? new Response("{}", { status: 404 }) + : base(url, init)) as unknown as typeof fetch; + expect(await t.run()).toBe(0); + expect(t.said.join("\n")).toMatch(/warn The bot user can't see o\/mine: add it as a collaborator/); + expect(t.said.join("\n")).not.toMatch(/Couldn't see o\/mine as me/); + }); + + it("reads owner/name from a GitHub remote", () => { + expect(repoFromRemote("git@github.com:craftmilldev/loopway.git")).toBe("craftmilldev/loopway"); + expect(repoFromRemote("https://github.com/craftmilldev/loopway")).toBe("craftmilldev/loopway"); + expect(repoFromRemote("https://example.com/a/b")).toBeUndefined(); + expect(repoFromRemote(undefined)).toBeUndefined(); + }); +}); diff --git a/verifications/560.md b/verifications/560.md new file mode 100644 index 00000000..d82fe7d2 --- /dev/null +++ b/verifications/560.md @@ -0,0 +1,54 @@ +# Verification for PR 560: Add `loopway setup` + +Run 2026-11-16 on macOS, with the CLI built from branch `issue-556-loopway-setup` (`packages/cli/dist/index.js`, version 2.1.0), the real `claude` (2.1.325), and `gh` logged in as `loopway-bot` through `GH_TOKEN`. Issue #556 has no "How to test it" steps, so I ran the command the way a person would: in a real pseudo-terminal, typing the keys, in a fresh temp directory (a git repo whose `origin` is `craftmilldev/loopway-sandbox`) with `LOOPWAY_HOME` pointing at an empty temp folder. `setup` only reads from GitHub (`/user`, `/repos/`), so nothing was opened or written in the sandbox repo or anywhere else on GitHub. + +**Update after review (merged `main`, 2.1.0 kept above 2.0.3):** the review asked for a record with a real token saved, a second run that asks nothing, and the refusals, plus three fixes (offline is not "rejected", the bot's own view of each repo, Ctrl-C). Those are in the section "Rerun after review" at the end; the earlier sections below are the first round. + +**Bottom line:** the fresh-machine walk ran live: gh and Claude Code were checked, the bot-token step refused a token that is the gh login's own account, the bot step could be skipped, both bot files were offered, the repo was guessed from `origin` and accepted, and `.loopway/dev.md` and `review.md` were written. A second run left both files alone. Not run live: logging in with `gh auth login`, saving a valid token from a different account, and a machine with no `gh` or no `claude` (all three are covered by the automated tests only). The live run found a real bug that the tests could not: see below. + +## Automated + +| Check | Result | +| --- | --- | +| `npm run build` | passes | +| `npm test` | cli 265 passed (17 files), web 41 passed (3 files) | +| `npm run typecheck` | passes | +| `npm run lint` | passes | +| `npm run format:check` | passes | + +`test/setup.test.ts` scripts the terminal and fakes `exec` and `fetch`: a fresh machine end to end (token saved 0600 with the name and noreply email, both files parse with `parseBot`, the token never appears in output); an already-set-up machine (asks nothing, changes nothing); skipping the bot user and a bot file; `gh auth login` offered, declined and still failing; `gh` missing; a bad token and your own account's token refused; a stale saved token replaced with the rest of `config.json` kept; a repo that isn't `owner/name` asked again and one `gh` can't see warned about; remote URL parsing. `test/setup-io.test.tsx` covers how the two question views draw. + +## Live, in a pseudo-terminal + +- Header and checks: `✓ gh is logged in as loopway-bot.` and `✓ Claude Code is installed (2.1.325 (Claude Code)).` +- Bot user, add: I typed the real bot token (the one from `~/.loopway/config.json`). It showed as 40 dots and was never echoed, and the screen said: + `! That token is your own account (loopway-bot): the bot would comment as you. Use another account's.` + Because `gh` here is logged in as the bot, this is the closest live case; a different account's token was not available, so saving one was not run live. It then asked again; I chose skip: `! Skipped the bot user: sessions are off until you add one`. Nothing was written to the temp `config.json`. +- Bot files: `Add .loopway/dev.md here (…)?` yes, `Add .loopway/review.md here (…)?` yes, `Which repos should the bots watch?` came up with `craftmilldev/loopway-sandbox` (guessed from `origin`), Enter accepted it, and `✓ Wrote .loopway/dev.md for craftmilldev/loopway-sandbox.` Both files exist, `review.md` has `repos: [craftmilldev/loopway-sandbox]` and `on: pull_request`. +- Second run in the same directory: `✓ .loopway/dev.md is already here: left as it is.`, and no question about the files. +- Not a terminal (`loopway setup < /dev/null`): `loopway setup asks questions: run it in a terminal.`, exit 1. + +### A bug the live run found, and fixed + +The first live runs echoed the token as plain text while it was being typed, and ignored Enter and arrow keys at times (the arrow showed as `^[[B`). Every question had been its own Ink app, and starting the next one raced the last one's cleanup, which left the terminal out of raw mode. The fix is one Ink app for the whole walk with a single input handler (`packages/cli/src/setup-io.tsx`). I reran the flow above on the fixed code: no echo (a grep of the transcript for the token found nothing) and every key was taken. + +## Rerun after review + +Same pseudo-terminal method, fresh `LOOPWAY_HOME` and a git repo whose `origin` is `craftmilldev/loopway-sandbox`. To get a gh login that is not the bot, I removed `GH_TOKEN` from setup's environment, so `gh` used its stored `mcwhittemore` login. + +1. **Fresh home with `{"auto_update": false}` in config.json.** A made-up token (`badtoken123`) gave `✗ GitHub didn't accept that token.` Then the real `loopway-bot` token: `✓ Saved loopway-bot as the bot user in /config.json.` The file's mode is 600, it still has `auto_update: false`, and its `github` block has `name: loopway-bot` and `email: 339690149+loopway-bot@users.noreply.github.com`. The transcript has no trace of the token. Then both bot files were written for `craftmilldev/loopway-sandbox` (`dev.md`: `on: issue`). +2. **Second run, same home and directory.** `✓ The bot user is loopway-bot (from …)`, `.loopway/dev.md` and `review.md` `already here: left as it is`, then `✓ Done.` No question was asked; `config.json` is byte-identical and the bot files' checksums are unchanged. (This run is what showed that the last lines said before exit never reached the screen; it is fixed with a short wait before Ink closes, and the run above is on the fixed code.) +3. **Own account refused:** with the bot's gh login (`GH_TOKEN`), typing the bot's token gave `! That token is your own account (loopway-bot): the bot would comment as you. Use another account's.` and nothing was saved. +4. **Ctrl-C at a question:** exit code 1, `Cancelled: nothing more was changed.`, nothing written. +5. **`loopway` on the generated files:** started in that directory with that home, it printed `loopway 2.1.0: watching craftmilldev/loopway-sandbox for loopway-bot`, so `loadBots` accepted both files and the repo was read from them. I stopped it with `kill -INT`. + +**Not checked: that a new `[#560]` sandbox issue starts a thread from those files.** I tried to open the issue and `create_issue` refused (`dev does not read craftmilldev/loopway-sandbox`: it only opens issues in repos the running loopway reads), and my instructions don't allow `gh` for that. No sandbox issue was opened, so there was nothing to close. The automated `parseBot` test on the written files and the "watching" line above are the evidence instead. + +Changes from the review's other points, with tests: a failed fetch (offline) is told apart from a refused token, so a saved bot token is kept and the gh login is not blamed; each repo is also checked with the bot's token when there is one, and setup warns that the bot user can't see it; Ctrl-C ends setup with exit 1. + +## What I did not check, and what else happened + +- Not run live: `gh auth login` from inside setup, a machine where `gh` or `claude` is missing, and saving a token for a different account (covered by the automated tests only). +- The earlier, buggy runs printed the bot's token (the `loopway-bot` token already in `~/.loopway/config.json`) in my own terminal output before the fix. It should be treated as exposed to this session's logs; rotate it if that matters. +- Other loopways: none touched; setup makes no sandbox issues or PRs, so there was nothing to close. +- Cleanup: the temp directories and driver script were removed after each round, and no transcript was kept.