Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```

Expand All @@ -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 (no `.git` needed; `~/.loopway` itself is config and state, so it is skipped), and `--project <dir>` 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
Expand Down Expand Up @@ -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 <session id>`. `--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 <session id>`. `--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 `<!-- loopway:thread=<id> -->` so the poller can tell.
Expand Down Expand Up @@ -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/<bot>.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 <dir>` names); sessions run in the directory that holds it. Each bot is one file, `.loopway/<bot>.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`:

Expand Down
15 changes: 10 additions & 5 deletions docs/developing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <path>` makes the project somewhere else. Read the README for what loopway prints.

## Checks
Expand All @@ -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/<bot>.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/<id>.json` |
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
24 changes: 15 additions & 9 deletions packages/cli/src/index.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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";
Expand All @@ -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.
Expand All @@ -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 <bot>.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 <bot>.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/<the project's path>.

--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)
Expand All @@ -43,6 +47,7 @@ State is per project, in ~/.loopway/state/<the project's path>.
async function main(): Promise<number> {
const { values, positionals } = parseArgs({
options: {
project: { type: "string" },
json: { type: "boolean" },
"no-tui": { type: "boolean" },
max: { type: "string", default: "3" },
Expand All @@ -64,15 +69,15 @@ async function main(): Promise<number> {
return 0;
}

const project = projectDir();
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.`);

const bots = await loadBots(project);
const repos = reposOf(bots);
if (repos.length === 0) {
console.error(
"Nothing to read. Add .loopway/<bot>.md here, with front matter like:\n\n---\nrepos: [owner/name]\n---",
`Nothing to read in ${join(project, ".loopway")}. Add <bot>.md files there, with front matter like:\n\n---\nrepos: [owner/name]\n---`,
);
return 1;
}
Expand All @@ -90,7 +95,10 @@ async function main(): Promise<number> {
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({
Expand Down Expand Up @@ -129,6 +137,7 @@ async function main(): Promise<number> {
latest: () => latest,
status: (now: number) => formatPollStatus(repos, poller.status(), now),
onRefresh: () => void poller.refresh(),
project,
};
await showTui(props).finally(() => stop.abort());
}
Expand All @@ -137,9 +146,6 @@ async function main(): Promise<number> {
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;
Expand Down
27 changes: 27 additions & 0 deletions packages/cli/src/project.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { statSync } from "node:fs";
import { dirname, join, resolve } from "node:path";

/** 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 <dir>` names it; without that it is the nearest
* 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, home: string, explicit?: string): string {
if (explicit !== undefined) {
const dir = resolve(from, explicit);
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 (isProject(dir, home)) 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 <dir>.`,
);
}
4 changes: 3 additions & 1 deletion packages/cli/src/tui-main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -37,7 +39,7 @@ export function MainView(props: MainViewProps) {
return (
<Box flexDirection="column">
<Text bold>
loopway · {threads.length} threads
loopway · {props.project} · {threads.length} threads
{filter && <Text color="cyan"> · filter {filter} (esc clears)</Text>}
</Text>
{threads.length === 0 && <Text dimColor>No threads yet.</Text>}
Expand Down
14 changes: 13 additions & 1 deletion packages/cli/src/tui.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -27,7 +29,16 @@ export async function showTui(props: TuiProps): Promise<void> {
}

/** 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<string>();
const [selectedId, setSelectedId] = useState<string>();
Expand Down Expand Up @@ -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}
Expand Down
71 changes: 71 additions & 0 deletions packages/cli/test/project.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
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 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"), 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"), 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"), 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"), 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, 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"), 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, 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, home(), dir)).toThrow(`No .loopway/ folder in ${dir} (from --project)`);
});
});
10 changes: 8 additions & 2 deletions packages/cli/test/tui.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ function show(threads: Thread[] | (() => Thread[]), more: Partial<TuiProps> = {}
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}
Expand All @@ -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");
Expand Down Expand Up @@ -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 () => {
Expand Down
Loading
Loading