From dfa265d2c2545f0b8bb9b3513acd49faff40b024 Mon Sep 17 00:00:00 2001 From: Matthew Whittemore Date: Tue, 10 Nov 2026 21:34:29 -0500 Subject: [PATCH 1/3] loopway finds its project by walking up to the nearest .loopway/ Drops the INIT_CWD fallback and the root `cli` script, adds --project , names the resolved .loopway in the first log line and the TUI header, and documents `npm link -w @loopway/cli` as the dev entry point. Co-Authored-By: Claude Opus 5.5 --- README.md | 9 +++-- docs/developing.md | 15 +++++--- package.json | 1 - packages/cli/src/index.ts | 24 +++++++----- packages/cli/src/project.ts | 23 +++++++++++ packages/cli/src/tui-main.tsx | 4 +- packages/cli/src/tui.tsx | 14 ++++++- packages/cli/test/project.test.ts | 63 +++++++++++++++++++++++++++++++ packages/cli/test/tui.test.tsx | 10 ++++- 9 files changed, 140 insertions(+), 23 deletions(-) create mode 100644 packages/cli/src/project.ts create mode 100644 packages/cli/test/project.test.ts diff --git a/README.md b/README.md index 139ce93a..c11e4eb3 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ This is 2.0, an alpha. It started as a poller; threads are the second slice, and ```bash npm install && npm run build # Node 22+ +npm link -w @loopway/cli # puts your checkout's build on your PATH as `loopway` gh auth login # loopway acts as whoever gh is logged in as ``` @@ -36,10 +37,10 @@ on: pull_request You are the review bot. You read a pull request and review it. EOF -node ../packages/cli/dist/index.js # runs `loopway` here (`npm run build` first) +loopway # re-run `npm run build` in the checkout after changing the code ``` -To run it from a directory outside the checkout, `npm link -w @loopway/cli` puts `loopway` on your PATH. The plain log (see [The TUI](#the-tui)) is one line per event: +`loopway` finds its project the way git finds a repo: it walks up from where you are to the nearest directory with a `.loopway/` folder, and `--project ` names one instead. Its first line (and the TUI header) says which `.loopway` it found; with none above you, it exits and says where it looked. The plain log (see [The TUI](#the-tui)) is one line per event: ``` 2026-11-10 14:02 new owner/repo#12 issue "Fix the login bug" by mcwhittemore @@ -79,7 +80,7 @@ The bare `loopway` adds thread lines to its output, after the line of the event ## Sessions -Each open thread with queued updates and no run in flight gets all of them, oldest first, in one run of Claude Code (`claude -p --permission-mode auto --output-format stream-json`) in the directory `loopway` runs in. A new session gets the bot's prompt plus the updates; later batches run with `--resume `. `--max N` (default 3) caps the runs in flight. +Each open thread with queued updates and no run in flight gets all of them, oldest first, in one run of Claude Code (`claude -p --permission-mode auto --output-format stream-json`) in the project directory (the one holding `.loopway/`). A new session gets the bot's prompt plus the updates; later batches run with `--resume `. `--max N` (default 3) caps the runs in flight. - A delivered batch leaves the queue. A run that fails (an API error, a usage limit, a bad exit, a bad model name) leaves it, marks the session `failed`, and the thread tries again after 5 minutes. A usage limit holds every delivery until it resets. - The session acts as the bot user (see Credentials). It talks only through loopway's own MCP server, which loopway hosts and passes with `--mcp-config`. The one tool so far is `comment(subject, body)`. Every message goes through it, so loopway records it on the thread (`sent`). A comment a thread sent is not queued back to that thread, but is queued to every other thread holding the subject. The comment carries a hidden `` so the poller can tell. @@ -117,7 +118,7 @@ Per thread, the JSON has `session: { id, status: idle | running | blocked | fail ## Bots: `.loopway/` -`loopway` reads the `.loopway/` folder in the directory it runs from. Each bot is one file, `.loopway/.md`: Markdown with YAML front matter. The front matter is the bot's rules; the Markdown is its prompt, which starts each thread's session. The keys: `repos`; `on: issue`, `on: pull_request` or a list of both, which says which new subjects start a thread for the bot; `model` (like `sonnet`, passed to Claude Code); `harness` (only `claude`, the default). Keys loopway does not know are ignored. It polls the union of every bot's repos. +`loopway` reads the nearest `.loopway/` folder at or above where it runs (or the one `--project ` names); sessions run in the directory that holds it. Each bot is one file, `.loopway/.md`: Markdown with YAML front matter. The front matter is the bot's rules; the Markdown is its prompt, which starts each thread's session. The keys: `repos`; `on: issue`, `on: pull_request` or a list of both, which says which new subjects start a thread for the bot; `model` (like `sonnet`, passed to Claude Code); `harness` (only `claude`, the default). Keys loopway does not know are ignored. It polls the union of every bot's repos. `.loopway/dev.md`: diff --git a/docs/developing.md b/docs/developing.md index 7e2792a1..99d001d4 100644 --- a/docs/developing.md +++ b/docs/developing.md @@ -9,14 +9,18 @@ ```bash npm install npm run build -npm run init-scratch # scratch/ (git-ignored): dev and review bots on the sandbox repo +npm link -w @loopway/cli # `loopway` on your PATH is now this checkout's build; rebuild after changes +npm run init-scratch # scratch/ (git-ignored): dev and review bots on the sandbox repo cd scratch -node ../packages/cli/dist/index.js # bare `loopway`, reading ./.loopway -node ../packages/cli/dist/index.js --no-tui # the plain log -node ../packages/cli/dist/index.js --json # NDJSON -node ../packages/cli/dist/index.js threads # the open threads, from another terminal +loopway # bare `loopway`: the nearest .loopway/ above here, named on its first line +loopway --no-tui # the plain log +loopway --json # NDJSON +loopway threads # the open threads, from another terminal +loopway --project scratch # from anywhere, naming the project ``` +There is no `npm run` entry for loopway itself: npm runs scripts from the checkout root, which would read the checkout's own `.loopway`. + It needs `gh auth login`. `npm run init-scratch` points both bots at `craftmilldev/loopway-sandbox`; run it again any time (it keeps bot files you edited and says so; `--force` puts the defaults back). `-- --reset` also clears the project's state in `~/.loopway/state/`, so you start with no threads, and `-- --dir ` makes the project somewhere else. Read the README for what loopway prints. ## Checks @@ -38,6 +42,7 @@ CI runs `npm run build` and these four. | `source.ts` | `SubjectSource`, the interface to a collaboration tool, and the types around it | | `github.ts` | `GitHubSource`: REST with ETags, rate-limit detection | | `poller.ts` | Discovery (2 min), updates (30 s), dedupe, backoff | +| `project.ts` | `findProject`: walks up to the nearest `.loopway/`, or takes `--project` | | `bots.ts` | Reads `.loopway/.md` | | `rules.ts` | `decide(event, threads, bots) -> actions`: the thread rules, a pure function | | `thread.ts`, `threads.ts` | The `Thread` type; the store that applies the rules' actions and keeps `threads/.json` | diff --git a/package.json b/package.json index eab5fcf6..496fb367 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,6 @@ ], "scripts": { "init-scratch": "node tools/init-scratch.mjs", - "cli": "npm run start -w @loopway/cli --", "build": "npm run build --workspaces --if-present", "test": "npm test --workspaces", "typecheck": "npm run typecheck --workspaces", diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 70ab7923..f2772c6e 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -1,5 +1,6 @@ #!/usr/bin/env node import { readFileSync } from "node:fs"; +import { join } from "node:path"; import { parseArgs } from "node:util"; import { loadBots, reposOf, type Bot } from "./bots.js"; import { claudeRunner } from "./claude.js"; @@ -8,6 +9,7 @@ import { formatJson, formatLine, formatThread, formatThreadJson, type LoopwayEve import { ghToken, GitHubSource } from "./github.js"; import { startMcp } from "./mcp.js"; import { Poller } from "./poller.js"; +import { findProject } from "./project.js"; import { Sessions } from "./sessions.js"; import { loadState, saveState, stateDir } from "./state.js"; import { loadThreads, readThreadLog, Threads, visibleThreads } from "./threads.js"; @@ -17,8 +19,8 @@ import { formatPollStatus } from "./tui-text.js"; const HELP = `loopway: watches GitHub and prints every new issue and pull request by you or your bot, and every update to the ones it knows. -Usage: loopway [--no-tui] [--json] [--max N] - loopway threads [--json] +Usage: loopway [--project DIR] [--no-tui] [--json] [--max N] + loopway threads [--project DIR] [--json] 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. @@ -28,12 +30,14 @@ and every update to it goes on the queue of the open threads that hold it. Each session that acts as the bot user and talks back through loopway's own MCP tool. \`loopway threads\` lists the open threads, and those closed in the last 3 days. -Run it from a directory with a .loopway/ folder: one .md per bot, with front matter like +Run it in a project: it walks up from where you are to the nearest directory with a .loopway/ folder, like git +finds a repo, and prints which one it found. Each project has one .md per bot, with front matter like repos: [owner/name] model: sonnet Credentials come from gh (gh auth login), and the bot's from ~/.loopway/config.json (or $LOOPWAY_HOME). State is per project, in ~/.loopway/state/. + --project D use the .loopway/ in directory D, and skip the search --no-tui print the plain log even in a terminal --json print one JSON object per line (implies --no-tui) --max N runs in flight at once (default 3) @@ -43,6 +47,7 @@ State is per project, in ~/.loopway/state/. async function main(): Promise { const { values, positionals } = parseArgs({ options: { + project: { type: "string" }, json: { type: "boolean" }, "no-tui": { type: "boolean" }, max: { type: "string", default: "3" }, @@ -64,7 +69,7 @@ async function main(): Promise { return 0; } - const project = projectDir(); + const project = findProject(process.cwd(), values.project); 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.`); @@ -72,7 +77,7 @@ async function main(): Promise { const repos = reposOf(bots); if (repos.length === 0) { console.error( - "Nothing to read. Add .loopway/.md here, with front matter like:\n\n---\nrepos: [owner/name]\n---", + `Nothing to read in ${join(project, ".loopway")}. Add .md files there, with front matter like:\n\n---\nrepos: [owner/name]\n---`, ); return 1; } @@ -90,7 +95,10 @@ async function main(): Promise { let latest = ""; const say = (line: string) => (tui ? (latest = line) : console.log(line)); const log = (message: string) => (tui ? (latest = message) : console.error(message)); - if (!tui) console.error(`loopway ${pkg.version}: watching ${repos.join(", ")} for ${authors.join(" and ")}`); + if (!tui) + console.error( + `loopway ${pkg.version}: ${join(project, ".loopway")}: watching ${repos.join(", ")} for ${authors.join(" and ")}`, + ); const print = (event: LoopwayEvent) => say(values.json ? formatJson(event) : formatLine(event)); const stop = new AbortController(); const sessions = await startSessions({ @@ -129,6 +137,7 @@ async function main(): Promise { latest: () => latest, status: (now: number) => formatPollStatus(repos, poller.status(), now), onRefresh: () => void poller.refresh(), + project, }; await showTui(props).finally(() => stop.abort()); } @@ -137,9 +146,6 @@ async function main(): Promise { return 0; } -/** Where `loopway` was typed. Under `npm run`, INIT_CWD is the checkout root, not where you were: run the built file directly (`node ../packages/cli/dist/index.js`). */ -const projectDir = () => process.env.INIT_CWD || process.cwd(); - interface SessionsSetup { dir: string; config: GitHubConfig; diff --git a/packages/cli/src/project.ts b/packages/cli/src/project.ts new file mode 100644 index 00000000..c6cce129 --- /dev/null +++ b/packages/cli/src/project.ts @@ -0,0 +1,23 @@ +import { statSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; + +const hasLoopway = (dir: string) => statSync(join(dir, ".loopway"), { throwIfNoEntry: false })?.isDirectory() ?? false; + +/** + * The project directory, the one holding `.loopway/`. `--project ` names it; without that it is the nearest + * directory at or above `from` that has a `.loopway/` folder, the way git finds a repo. + */ +export function findProject(from: string, explicit?: string): string { + if (explicit !== undefined) { + const dir = resolve(from, explicit); + if (hasLoopway(dir)) return dir; + throw new Error(`No .loopway/ folder in ${dir} (from --project).`); + } + for (let dir = resolve(from); ; dir = dirname(dir)) { + if (hasLoopway(dir)) return dir; + if (dirname(dir) === dir) break; + } + throw new Error( + `No .loopway/ folder in ${resolve(from)} or any directory above it. Run loopway inside a project, or name one with --project .`, + ); +} diff --git a/packages/cli/src/tui-main.tsx b/packages/cli/src/tui-main.tsx index 390ef615..ce67b1a1 100644 --- a/packages/cli/src/tui-main.tsx +++ b/packages/cli/src/tui-main.tsx @@ -13,6 +13,8 @@ export interface MainViewProps { latest: string; /** What the poller is doing: last checked, next check. */ status: string; + /** The project directory, so a wrong one is obvious. */ + project: string; now: number; onSelect: (id: string) => void; onOpen: (id: string) => void; @@ -37,7 +39,7 @@ export function MainView(props: MainViewProps) { return ( - loopway · {threads.length} threads + loopway · {props.project} · {threads.length} threads {filter && · filter {filter} (esc clears)} {threads.length === 0 && No threads yet.} diff --git a/packages/cli/src/tui.tsx b/packages/cli/src/tui.tsx index 0cba8832..ce200882 100644 --- a/packages/cli/src/tui.tsx +++ b/packages/cli/src/tui.tsx @@ -16,6 +16,8 @@ export interface TuiProps { status: (now: number) => string; /** Polls GitHub now, instead of waiting for the poller's timers. */ onRefresh: () => void; + /** The project directory the threads belong to, shown in the header. */ + project: string; now?: () => number; refreshMs?: number; } @@ -27,7 +29,16 @@ export async function showTui(props: TuiProps): Promise { } /** The main view of threads, and the view of one thread. q quits; Ctrl-C does too. */ -export function Tui({ threads, readLog, latest, status, onRefresh, now = Date.now, refreshMs = 1000 }: TuiProps) { +export function Tui({ + threads, + readLog, + latest, + status, + onRefresh, + project, + now = Date.now, + refreshMs = 1000, +}: TuiProps) { const { exit } = useApp(); const [filter, setFilter] = useState(); const [selectedId, setSelectedId] = useState(); @@ -61,6 +72,7 @@ export function Tui({ threads, readLog, latest, status, onRefresh, now = Date.no filter={filter} latest={latest()} status={status(now())} + project={project} now={now()} onSelect={setSelectedId} onOpen={setOpenId} diff --git a/packages/cli/test/project.test.ts b/packages/cli/test/project.test.ts new file mode 100644 index 00000000..1079e530 --- /dev/null +++ b/packages/cli/test/project.test.ts @@ -0,0 +1,63 @@ +import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { findProject } from "../src/project.js"; + +let root: string; +beforeEach(async () => { + root = await realpath(await mkdtemp(join(tmpdir(), "loopway-project-"))); +}); +afterEach(() => rm(root, { recursive: true, force: true })); + +const folder = (path: string) => mkdir(join(root, path), { recursive: true }); + +describe("findProject", () => { + it("finds the .loopway in the directory itself", async () => { + await folder("app/.loopway"); + expect(findProject(join(root, "app"))).toBe(join(root, "app")); + }); + + it("walks up from a subdirectory", async () => { + await folder("app/.loopway"); + await folder("app/src/deep"); + expect(findProject(join(root, "app/src/deep"))).toBe(join(root, "app")); + }); + + it("takes the nearest one when projects nest", async () => { + await folder("app/.loopway"); + await folder("app/inner/.loopway"); + expect(findProject(join(root, "app/inner"))).toBe(join(root, "app/inner")); + }); + + it("does not take a file named .loopway", async () => { + await folder("app/.loopway"); + await folder("app/sub"); + await writeFile(join(root, "app/sub/.loopway"), ""); + expect(findProject(join(root, "app/sub"))).toBe(join(root, "app")); + }); + + it("says where it looked when there is none", async () => { + await folder("empty/deeper"); + const from = join(root, "empty/deeper"); + expect(() => findProject(from)).toThrow(`No .loopway/ folder in ${from} or any directory above it`); + }); + + it("--project names the project, from anywhere, and skips the search", async () => { + await folder("app/.loopway"); + await folder("elsewhere/.loopway"); + expect(findProject(join(root, "elsewhere"), join(root, "app"))).toBe(join(root, "app")); + }); + + it("--project resolves a relative directory against where you are", async () => { + await folder("app/.loopway"); + expect(findProject(root, "app")).toBe(join(root, "app")); + }); + + it("--project does not walk up, and names the directory it checked", async () => { + await folder("app/.loopway"); + await folder("app/src"); + const dir = join(root, "app/src"); + expect(() => findProject(root, dir)).toThrow(`No .loopway/ folder in ${dir} (from --project)`); + }); +}); diff --git a/packages/cli/test/tui.test.tsx b/packages/cli/test/tui.test.tsx index 1af5abc9..4cbe6cc7 100644 --- a/packages/cli/test/tui.test.tsx +++ b/packages/cli/test/tui.test.tsx @@ -32,6 +32,7 @@ function show(threads: Thread[] | (() => Thread[]), more: Partial = {} latest={() => "14:03 update o/r#12 comment by me"} status={() => "polling o/r · last checked 14:02 · next in 0:24"} onRefresh={() => {}} + project="/work/app" now={() => NOW} refreshMs={10} {...more} @@ -52,6 +53,11 @@ describe("main view", () => { expect(screen()).toContain(" review open running 0 pending 2026-11-10 14:30 o/r#13"); }); + it("names the project in the header", () => { + show([dev12()]); + expect(screen()).toContain("loopway · /work/app · 1 threads"); + }); + it("shows the latest poller line at the bottom", () => { show([dev12()]); expect(screen().trim().split("\n").at(-3)).toBe("14:03 update o/r#12 comment by me"); @@ -182,10 +188,10 @@ describe("thread view", () => { await press(KEYS.right); expect(screen()).toContain("Subjects"); await press(KEYS.left); - expect(screen()).toContain("loopway · 1 threads"); + expect(screen()).toContain("loopway · /work/app · 1 threads"); await press(KEYS.enter); await press(KEYS.esc); - expect(screen()).toContain("loopway · 1 threads"); + expect(screen()).toContain("loopway · /work/app · 1 threads"); }); it("says there is no session yet when the thread has none, and no log", async () => { From cd7ef8155e72ac2aa1b4b2d48173c91667a32a47 Mon Sep 17 00:00:00 2001 From: Matthew Whittemore Date: Tue, 10 Nov 2026 21:34:59 -0500 Subject: [PATCH 2/3] verifications/509.md Co-Authored-By: Claude Opus 5.5 --- verifications/509.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 verifications/509.md diff --git a/verifications/509.md b/verifications/509.md new file mode 100644 index 00000000..cb00012e --- /dev/null +++ b/verifications/509.md @@ -0,0 +1,25 @@ +# Verification for PR 509: loopway finds its project by walking up + +`loopway` finds its project like git finds a repo: it walks up from the current directory to the nearest directory with a `.loopway/` folder. `--project ` skips the search. The first log line and the TUI header name the `.loopway` it found. Ran on 2026-11-10, on a Mac, with the build from this branch. + +## Automated + +| Check | Result | +| ---------------------- | -------------------------------------- | +| `npm test` | 130 tests (8 new in `project.test.ts`) | +| `npm run typecheck` | clean | +| `npm run lint` | clean | +| `npm run format:check` | clean | + +`project.test.ts` covers: `.loopway` in the directory itself, walking up from a subdirectory, the nearest of two nested projects, a file named `.loopway` being skipped, the not-found message naming where it looked, `--project` from anywhere (absolute and relative), and `--project` not walking up. `tui.test.tsx` checks the header shows the project. + +## Live + +Scratch project in the session scratchpad: `scratch/.loopway/dev.md` (`repos: [craftmilldev/loopway-sandbox]`, `on: issue`), a `LOOPWAY_HOME` of its own, the built CLI as `node /packages/cli/dist/index.js`. Read-only: no issue, PR or comment was created in the sandbox, and nothing was pushed to it. + +1. `npm run build` ran. **`npm link -w @loopway/cli` was not run**: it changes the global npm prefix, outside this task, so steps 2 to 4 used the built file directly. The root `cli` script is gone, so `npm run cli` no longer exists to read the wrong project. +2. From `scratch/sub/deep`, `--no-tui`: the first line is `loopway 2.0.0-alpha: /.loopway: watching craftmilldev/loopway-sandbox for mcwhittemore`. State went to `/state/`. +3. From `/tmp` (no `.loopway` above it; shown as `/private/tmp`): `No .loopway/ folder in /private/tmp or any directory above it. Run loopway inside a project, or name one with --project .` +4. From `/tmp`, `--project --no-tui`: the same first line as step 2, naming the scratch `.loopway`. `--project /tmp/nope` exits with `No .loopway/ folder in /tmp/nope (from --project).` + +Not run live: the TUI header (covered by `tui.test.tsx`) and a session run (this PR changes only the working directory they use, now the resolved project). From a14b7f0b831b445107dede670c3757faa5650421 Mon Sep 17 00:00:00 2001 From: Matthew Whittemore Date: Tue, 10 Nov 2026 22:16:44 -0500 Subject: [PATCH 3/3] findProject skips the loopway home (~/.loopway) Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- packages/cli/src/index.ts | 2 +- packages/cli/src/project.ts | 14 +++++++++----- packages/cli/test/project.test.ts | 24 ++++++++++++++++-------- verifications/509.md | 8 ++++++-- 5 files changed, 33 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index c11e4eb3..690c28d2 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ EOF loopway # re-run `npm run build` in the checkout after changing the code ``` -`loopway` finds its project the way git finds a repo: it walks up from where you are to the nearest directory with a `.loopway/` folder, and `--project ` names one instead. Its first line (and the TUI header) says which `.loopway` it found; with none above you, it exits and says where it looked. The plain log (see [The TUI](#the-tui)) is one line per event: +`loopway` finds its project the way git finds a repo: it walks up from where you are to the nearest directory with a `.loopway/` folder (no `.git` needed; `~/.loopway` itself is config and state, so it is skipped), and `--project ` names one instead. Its first line (and the TUI header) says which `.loopway` it found; with none above you, it exits and says where it looked. The plain log (see [The TUI](#the-tui)) is one line per event: ``` 2026-11-10 14:02 new owner/repo#12 issue "Fix the login bug" by mcwhittemore diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index f2772c6e..be0ffc08 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -69,7 +69,7 @@ async function main(): Promise { return 0; } - const project = findProject(process.cwd(), values.project); + const project = findProject(process.cwd(), loopwayHome(), values.project); 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/project.ts b/packages/cli/src/project.ts index c6cce129..6963d82f 100644 --- a/packages/cli/src/project.ts +++ b/packages/cli/src/project.ts @@ -1,20 +1,24 @@ import { statSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; -const hasLoopway = (dir: string) => statSync(join(dir, ".loopway"), { throwIfNoEntry: false })?.isDirectory() ?? false; +/** A directory is a project when it has a `.loopway/` folder, unless that folder is loopway's own home (`~/.loopway`). */ +const isProject = (dir: string, home: string) => + join(dir, ".loopway") !== resolve(home) && + (statSync(join(dir, ".loopway"), { throwIfNoEntry: false })?.isDirectory() ?? false); /** * The project directory, the one holding `.loopway/`. `--project ` names it; without that it is the nearest - * directory at or above `from` that has a `.loopway/` folder, the way git finds a repo. + * directory at or above `from` that has a `.loopway/` folder, the way git finds a repo. It needs no `.git`. The + * `~/.loopway` folder (`home`) holds config and state, so it never makes `~` a project. */ -export function findProject(from: string, explicit?: string): string { +export function findProject(from: string, home: string, explicit?: string): string { if (explicit !== undefined) { const dir = resolve(from, explicit); - if (hasLoopway(dir)) return dir; + if (isProject(dir, home)) return dir; throw new Error(`No .loopway/ folder in ${dir} (from --project).`); } for (let dir = resolve(from); ; dir = dirname(dir)) { - if (hasLoopway(dir)) return dir; + if (isProject(dir, home)) return dir; if (dirname(dir) === dir) break; } throw new Error( diff --git a/packages/cli/test/project.test.ts b/packages/cli/test/project.test.ts index 1079e530..2fc7f1ce 100644 --- a/packages/cli/test/project.test.ts +++ b/packages/cli/test/project.test.ts @@ -10,54 +10,62 @@ beforeEach(async () => { }); afterEach(() => rm(root, { recursive: true, force: true })); +const home = () => join(root, ".loopway"); const folder = (path: string) => mkdir(join(root, path), { recursive: true }); describe("findProject", () => { it("finds the .loopway in the directory itself", async () => { await folder("app/.loopway"); - expect(findProject(join(root, "app"))).toBe(join(root, "app")); + expect(findProject(join(root, "app"), home())).toBe(join(root, "app")); }); it("walks up from a subdirectory", async () => { await folder("app/.loopway"); await folder("app/src/deep"); - expect(findProject(join(root, "app/src/deep"))).toBe(join(root, "app")); + expect(findProject(join(root, "app/src/deep"), home())).toBe(join(root, "app")); }); it("takes the nearest one when projects nest", async () => { await folder("app/.loopway"); await folder("app/inner/.loopway"); - expect(findProject(join(root, "app/inner"))).toBe(join(root, "app/inner")); + expect(findProject(join(root, "app/inner"), home())).toBe(join(root, "app/inner")); + }); + + it("walks past the loopway home: ~/.loopway is config and state, not a project", async () => { + await folder(".loopway/state"); + await folder("work/app"); + const from = join(root, "work/app"); + expect(() => findProject(from, home())).toThrow("No .loopway/ folder in"); }); it("does not take a file named .loopway", async () => { await folder("app/.loopway"); await folder("app/sub"); await writeFile(join(root, "app/sub/.loopway"), ""); - expect(findProject(join(root, "app/sub"))).toBe(join(root, "app")); + expect(findProject(join(root, "app/sub"), home())).toBe(join(root, "app")); }); it("says where it looked when there is none", async () => { await folder("empty/deeper"); const from = join(root, "empty/deeper"); - expect(() => findProject(from)).toThrow(`No .loopway/ folder in ${from} or any directory above it`); + expect(() => findProject(from, home())).toThrow(`No .loopway/ folder in ${from} or any directory above it`); }); it("--project names the project, from anywhere, and skips the search", async () => { await folder("app/.loopway"); await folder("elsewhere/.loopway"); - expect(findProject(join(root, "elsewhere"), join(root, "app"))).toBe(join(root, "app")); + expect(findProject(join(root, "elsewhere"), home(), join(root, "app"))).toBe(join(root, "app")); }); it("--project resolves a relative directory against where you are", async () => { await folder("app/.loopway"); - expect(findProject(root, "app")).toBe(join(root, "app")); + expect(findProject(root, home(), "app")).toBe(join(root, "app")); }); it("--project does not walk up, and names the directory it checked", async () => { await folder("app/.loopway"); await folder("app/src"); const dir = join(root, "app/src"); - expect(() => findProject(root, dir)).toThrow(`No .loopway/ folder in ${dir} (from --project)`); + expect(() => findProject(root, home(), dir)).toThrow(`No .loopway/ folder in ${dir} (from --project)`); }); }); diff --git a/verifications/509.md b/verifications/509.md index cb00012e..8137b405 100644 --- a/verifications/509.md +++ b/verifications/509.md @@ -6,12 +6,12 @@ | Check | Result | | ---------------------- | -------------------------------------- | -| `npm test` | 130 tests (8 new in `project.test.ts`) | +| `npm test` | 131 tests (9 new in `project.test.ts`) | | `npm run typecheck` | clean | | `npm run lint` | clean | | `npm run format:check` | clean | -`project.test.ts` covers: `.loopway` in the directory itself, walking up from a subdirectory, the nearest of two nested projects, a file named `.loopway` being skipped, the not-found message naming where it looked, `--project` from anywhere (absolute and relative), and `--project` not walking up. `tui.test.tsx` checks the header shows the project. +`project.test.ts` covers: `.loopway` in the directory itself, walking up from a subdirectory, the nearest of two nested projects, a file named `.loopway` being skipped, the loopway home (`~/.loopway`) being skipped, the not-found message naming where it looked, `--project` from anywhere (absolute and relative), and `--project` not walking up. `tui.test.tsx` checks the header shows the project. ## Live @@ -23,3 +23,7 @@ Scratch project in the session scratchpad: `scratch/.loopway/dev.md` (`repos: [c 4. From `/tmp`, `--project --no-tui`: the same first line as step 2, naming the scratch `.loopway`. `--project /tmp/nope` exits with `No .loopway/ folder in /tmp/nope (from --project).` Not run live: the TUI header (covered by `tui.test.tsx`) and a session run (this PR changes only the working directory they use, now the resolved project). + +## Added after review + +Asked whether the walk reaches `~/.loopway` and whether `.loopway` must sit beside `.git`. It reached it: `~/.loopway` has the same name, so any directory under `~` with no project of its own would have resolved to `~` and kept state in `~/.loopway/state/`. `findProject` now skips the loopway home (`$LOOPWAY_HOME`, default `~/.loopway`). No `.git` is needed. Live: with `LOOPWAY_HOME=/.loopway` and no other `.loopway` above `/work/app`, `loopway` from `work/app` exits with the not-found message instead of using ``.