Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
64edafa
docs: repo locate + registry merge spec and plan
m4ttheweric Aug 25, 2026
4ba1f1f
feat(worktree): mergeRegistries — union two registries of one repo by…
m4ttheweric Aug 25, 2026
023b654
feat(repos): prune merges a split worktree registry instead of refusing
m4ttheweric Aug 25, 2026
ba72242
fix(repos): keep a missing index row that still owns a worktree registry
m4ttheweric Aug 25, 2026
24b96f7
feat(repos): keep lost index rows visible and refuse to cd into them
m4ttheweric Aug 25, 2026
52d58b1
fix(repos): make missing rows opt-in via getKnownRepos({ includeMissi…
m4ttheweric Aug 25, 2026
be1eb62
feat(repos): locate core — plan and apply a moved repo's path rewrite…
m4ttheweric Aug 25, 2026
75a31f9
fix(repos): locate repairs git and verifies before it writes any rt s…
m4ttheweric Aug 25, 2026
e9c7988
feat(daemon): withReconcilerHeld — exclusive access to the worktree r…
m4ttheweric Aug 25, 2026
a1a1205
feat(daemon): repos:locate verb, applied under the reconciler hold
m4ttheweric Aug 25, 2026
a8199ba
feat(repos): rt repos locate — daemon-first, local when nothing answers
m4ttheweric Aug 25, 2026
47979eb
fix(repos): decide daemon presence from liveness evidence, not a ping
m4ttheweric Aug 25, 2026
e2d7e7b
feat(repos): implicit index heal moves a repo instead of re-pointing …
m4ttheweric Aug 25, 2026
6d6c74d
fix(repos): a refused move is reported by its caller, never swallowed
m4ttheweric Aug 25, 2026
5da9fb9
test(repos): end-to-end locate against real git state and a live reco…
m4ttheweric Aug 25, 2026
7b49108
locate: unshadow the moved directory, keep claims and legacy rows sound
m4ttheweric Aug 25, 2026
6ff226a
locate: usage guards, stderr refusals, and the doc's legacy-world sec…
m4ttheweric Aug 25, 2026
2b87fc1
docs: scrub employer terms from the repo-locate spec
m4ttheweric Aug 25, 2026
5ea690c
docs: regenerate the command reference for repos locate
m4ttheweric Aug 26, 2026
8971886
locate: unique picker values, live-only fast path, strict repo selector
m4ttheweric Aug 26, 2026
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
134 changes: 134 additions & 0 deletions commands/__tests__/cd.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/**
* The `--repo --worktree <branch>` combo picks a repo via its own inline
* picker (not lib/pickers.ts's pickFromAllRepos), so a `missing: true` row
* needs its own guard: refuse via missingRepoRefusal before ever falling
* into branch resolution against a dead path.
*/

import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { mkdtempSync, realpathSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import { closeStateDb, setKvValue } from "../../lib/state/index.ts";
import { worktreePicker } from "../cd.ts";

// Satisfies ensureShellFunction()'s early-return check so worktreePicker
// never reaches the interactive "install rt cd?" prompt.
const UP_TO_DATE_RC = 'rt() {\n whence -p rt\n "$rt_bin" nav\n}\n';

describe("rt cd --repo --worktree with a missing repo", () => {
const origHome = process.env.HOME;
const origShell = process.env.SHELL;
const origCwd = process.cwd();
let home: string;
let scratch: string;

beforeEach(() => {
home = realpathSync(mkdtempSync(join(tmpdir(), "rt-cd-missing-home-")));
scratch = realpathSync(mkdtempSync(join(tmpdir(), "rt-cd-missing-repos-")));
process.env.HOME = home;
process.env.SHELL = "/bin/zsh";
writeFileSync(join(home, ".zshrc"), UP_TO_DATE_RC);
closeStateDb();
// cwd must NOT be a git repo: getRepoIdentity()'s real getRepoRoot() runs
// "git rev-parse --show-toplevel" against process.cwd() with no override,
// and if it found one it would auto-register it into this isolated
// index (updateRepoIndex's side effect), giving repoChoices a second,
// live entry and forcing the interactive picker instead of the
// single-entry auto-select this test exercises.
process.chdir(scratch);
});

afterEach(() => {
process.chdir(origCwd);
process.env.HOME = origHome;
process.env.SHELL = origShell;
closeStateDb();
rmSync(home, { recursive: true, force: true });
rmSync(scratch, { recursive: true, force: true });
});

test("refuses with missingRepoRefusal instead of falling into branch resolution", async () => {
setKvValue("repo-index", "moved", join(scratch, "gone-away"));

const originalStdoutWrite = process.stdout.write;
const chdirSpy = spyOn(process, "chdir").mockImplementation(() => {});
const errSpy = spyOn(console, "error").mockImplementation(() => {});
const exitSpy = spyOn(process, "exit").mockImplementation(() => {
throw new Error("process.exit sentinel");
});

try {
await expect(worktreePicker(["--repo", "--worktree", "anybranch"])).rejects.toThrow(
"process.exit sentinel",
);
expect(chdirSpy).not.toHaveBeenCalled();
expect(exitSpy.mock.calls.at(-1)?.[0]).toBe(1);
expect(errSpy.mock.calls.flat().join(" ")).toContain("rt repos locate");
} finally {
process.stdout.write = originalStdoutWrite;
chdirSpy.mockRestore();
errSpy.mockRestore();
exitSpy.mockRestore();
}
});
});

/**
* The plain `rt cd` picker (no --repo/--worktree flags) reaches
* pickFromAllRepos through commands/cd.ts's own `getKnownRepos()` call — a
* bare call there excludes missing rows, so a lost repo would silently vanish
* from the picker instead of hitting the missingRepoRefusal guard
* pickFromAllRepos already carries.
*/
describe("rt cd default picker with a missing repo", () => {
const origHome = process.env.HOME;
const origShell = process.env.SHELL;
const origCwd = process.cwd();
let home: string;
let scratch: string;

beforeEach(() => {
home = realpathSync(mkdtempSync(join(tmpdir(), "rt-cd-default-missing-home-")));
scratch = realpathSync(mkdtempSync(join(tmpdir(), "rt-cd-default-missing-repos-")));
process.env.HOME = home;
process.env.SHELL = "/bin/zsh";
writeFileSync(join(home, ".zshrc"), UP_TO_DATE_RC);
closeStateDb();
// Not a git repo — see the comment in the describe block above for why
// this matters (getRepoIdentity() must not auto-register process.cwd()).
process.chdir(scratch);
});

afterEach(() => {
process.chdir(origCwd);
process.env.HOME = origHome;
process.env.SHELL = origShell;
closeStateDb();
rmSync(home, { recursive: true, force: true });
Comment thread
coderabbitai[bot] marked this conversation as resolved.
rmSync(scratch, { recursive: true, force: true });
});

test("the only known repo being missing refuses instead of silently dropping it from the picker", async () => {
setKvValue("repo-index", "moved", join(scratch, "gone-away"));

const originalStdoutWrite = process.stdout.write;
const chdirSpy = spyOn(process, "chdir").mockImplementation(() => {});
const errSpy = spyOn(console, "error").mockImplementation(() => {});
const exitSpy = spyOn(process, "exit").mockImplementation(() => {
throw new Error("process.exit sentinel");
});

try {
await expect(worktreePicker([])).rejects.toThrow("process.exit sentinel");
expect(chdirSpy).not.toHaveBeenCalled();
expect(exitSpy.mock.calls.at(-1)?.[0]).toBe(1);
expect(errSpy.mock.calls.flat().join(" ")).toContain("rt repos locate");
} finally {
process.stdout.write = originalStdoutWrite;
chdirSpy.mockRestore();
errSpy.mockRestore();
exitSpy.mockRestore();
}
});
});
165 changes: 165 additions & 0 deletions commands/__tests__/repos-locate.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
/**
* The CLI takes its local branch here. `daemonPresent()` reads
* `DAEMON_PID_PATH`/`DAEMON_SOCK_PATH`, which are module-load constants bound
* to the throwaway HOME the bunfig preload (test-setup.ts) sets before any
* module loads — not to the per-test HOME below. That tree holds neither a pid
* file nor a socket, so the apply happens in-process, which is exactly the
* "no daemon, nothing to race" branch.
*/

import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { execSync } from "node:child_process";
import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { closeStateDb, setKvValue } from "../../lib/state/index.ts";
import { loadRepoIndex } from "../../lib/repo-index.ts";
import { saveRegistry, loadRegistry } from "../../lib/worktree/registry.ts";
import { deriveRepoIdentity, serializeIdentity } from "../../lib/settings/identity.ts";
import { reposLocate, type RegisterDeps } from "../repos.ts";

function testDeps(): RegisterDeps & { lines: string[] } {
const lines: string[] = [];
return { print: (s) => lines.push(s), lines };
}

async function runExpectingProcessExit(fn: () => Promise<void>): Promise<number | undefined> {
const exitSpy = spyOn(process, "exit").mockImplementation(() => {
throw new Error("process.exit sentinel");
});
try {
await fn();
return undefined;
} catch {
return exitSpy.mock.calls.at(-1)?.[0] as number | undefined;
} finally {
exitSpy.mockRestore();
}
}

describe("reposLocate", () => {
const origHome = process.env.HOME;
let home: string;
let scratch: string;

beforeEach(() => {
home = realpathSync(mkdtempSync(join(tmpdir(), "rt-locate-cli-home-")));
scratch = realpathSync(mkdtempSync(join(tmpdir(), "rt-locate-cli-repos-")));
process.env.HOME = home;
closeStateDb();
});

afterEach(() => {
process.env.HOME = origHome;
closeStateDb();
rmSync(home, { recursive: true, force: true });
rmSync(scratch, { recursive: true, force: true });
});

async function movedRepo(name: string): Promise<{ identity: string; from: string; to: string }> {
const dir = join(scratch, name);
mkdirSync(dir, { recursive: true });
execSync("git init -q -b main", { cwd: dir, stdio: "pipe" });
execSync(`git remote add origin https://gitlab.com/g/${name}.git`, { cwd: dir, stdio: "pipe" });
execSync("git -c user.email=t@t -c user.name=t commit --allow-empty -q -m init", { cwd: dir, stdio: "pipe" });
const from = realpathSync(dir);
const identity = serializeIdentity(await deriveRepoIdentity(from));
setKvValue("repo-index", identity, from);
saveRegistry(identity, [{ name: "main", path: from, kind: "main", branch: "main", createdAt: "2026-01-01T00:00:00.000Z" }]);
const to = join(scratch, `${name}-moved`);
renameSync(from, to);
return { identity, from, to };
}

test("locates a moved repo and says where it went", async () => {
const { identity, from, to } = await movedRepo("alpha");
const deps = testDeps();

await reposLocate([to], {}, deps);

expect(loadRepoIndex()[identity]).toBe(to);
expect(loadRegistry(identity)[0]?.path).toBe(to);
expect(deps.lines.join("\n")).toContain(from);
expect(deps.lines.join("\n")).toContain(to);
});

test("--dry-run reports the plan and writes nothing", async () => {
const { identity, from, to } = await movedRepo("beta");
const deps = testDeps();

await reposLocate([to, "--dry-run"], {}, deps);

expect(loadRepoIndex()[identity]).toBe(from);
expect(deps.lines.join("\n")).toContain("would move");
});

test("--json emits a contract envelope", async () => {
const { identity, to } = await movedRepo("gamma");
const deps = testDeps();

await reposLocate([to, "--json"], {}, deps);

const parsed = JSON.parse(deps.lines[0]!);
expect(parsed.contract).toBe(1);
expect(parsed.located.identity).toBe(identity);
expect(parsed.located.to).toBe(to);
});

test("--repo resolves to an identity and is honoured", async () => {
const { identity, to } = await movedRepo("delta");
const deps = testDeps();

await reposLocate([to, "--repo", identity], {}, deps);

expect(loadRepoIndex()[identity]).toBe(to);
});

test("a refusal exits 2 with the typed message", async () => {
const plain = join(scratch, "plain");
mkdirSync(plain);
const deps = testDeps();

const code = await runExpectingProcessExit(() => reposLocate([plain], {}, deps));

expect(code).toBe(2);
expect(deps.lines.join("\n")).toContain("not a git repository");
});

test("an unknown flag is a usage error", async () => {
const deps = testDeps();
const code = await runExpectingProcessExit(() => reposLocate(["--nope"], {}, deps));
expect(code).toBe(2);
expect(deps.lines.join("\n")).toContain("usage: rt repos locate");
});

test("--repo without a value is a usage error", async () => {
const deps = testDeps();
const code = await runExpectingProcessExit(() => reposLocate(["--repo"], {}, deps));
expect(code).toBe(2);
expect(deps.lines.join("\n")).toContain("--repo needs a value");
});

test("a second positional is a usage error, not a silently ignored path", async () => {
const deps = testDeps();
const code = await runExpectingProcessExit(() => reposLocate([scratch, join(scratch, "other")], {}, deps));
expect(code).toBe(2);
expect(deps.lines.join("\n")).toContain("locate takes one path");
});

test("no path and no lost rows exits 1 saying so", async () => {
const deps = testDeps();
const code = await runExpectingProcessExit(() => reposLocate([], {}, deps));
expect(code).toBe(1);
expect(deps.lines.join("\n")).toContain("no indexed repo is missing");
});

test("no path, a lost row and no candidate lists the lost row and exits 1", async () => {
setKvValue("repo-index", "remote:gitlab.com%2Fg%2Fghost", join(scratch, "ghost"));
const deps = testDeps();

const code = await runExpectingProcessExit(() => reposLocate([], {}, deps));

expect(code).toBe(1);
expect(deps.lines.join("\n")).toContain("remote:gitlab.com%2Fg%2Fghost");
});
});
61 changes: 60 additions & 1 deletion commands/__tests__/repos.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import { homedir, tmpdir } from "node:os";
import { basename, join } from "node:path";
import { getKnownRepos, loadRepoIndex, loadRepoIndexEntries, updateRepoIndex } from "../../lib/repo-index.ts";
import { loadRepoTracking } from "../../lib/repo-tracking.ts";
import { saveRegistry } from "../../lib/worktree/registry.ts";
import { deriveRepoIdentity, serializeIdentity } from "../../lib/settings/identity.ts";
import { closeStateDb } from "../../lib/state/index.ts";
import { closeStateDb, setKvValue } from "../../lib/state/index.ts";
import { reposPrune, reposRegister, type RegisterDeps } from "../repos.ts";

function testDeps(): RegisterDeps & { lines: string[] } {
Expand Down Expand Up @@ -119,6 +120,49 @@ describe("reposRegister", () => {
expect(body).toEqual({ contract: 1, registered: [{ name, path: repoPath, tracking: null }] });
});

test("a repo whose move cannot be applied exits 2 instead of reporting it registered", async () => {
const repoPath = makeTempRepo();
execSync("git remote add origin git@gitlab.com:group/moved.git", { cwd: repoPath, stdio: "pipe" });
const identity = serializeIdentity(await deriveRepoIdentity(repoPath));
const gone = join(home, "gone-away");
setKvValue("repo-index", identity, gone);
// A registry record whose re-rooted spelling is occupied by something git
// does not list as a worktree — the apply refuses at verification, so
// nothing is written and the row keeps naming the gone path.
saveRegistry(identity, [
{ name: "main", path: gone, kind: "main", branch: "main", createdAt: "2026-01-01T00:00:00.000Z" },
{ name: "t1", path: join(gone, ".worktrees", "t1"), kind: "ephemeral", state: "on-deck", branch: "feat", createdAt: "2026-01-01T00:00:00.000Z" },
]);
mkdirSync(join(repoPath, ".worktrees", "t1"), { recursive: true });
const deps = testDeps();

const code = await runExpectingProcessExit(() => reposRegister([repoPath], {}, deps));

expect(code).toBe(2);
expect(deps.lines.some((l) => l.includes("registered"))).toBe(false);
expect(loadRepoIndex()[identity]).toBe(gone);
});

test("--json reports a failed move as an error envelope, never a registered one", async () => {
const repoPath = makeTempRepo();
execSync("git remote add origin git@gitlab.com:group/moved-json.git", { cwd: repoPath, stdio: "pipe" });
const identity = serializeIdentity(await deriveRepoIdentity(repoPath));
const gone = join(home, "gone-away-json");
setKvValue("repo-index", identity, gone);
saveRegistry(identity, [
{ name: "t1", path: join(gone, ".worktrees", "t1"), kind: "ephemeral", state: "on-deck", branch: "feat", createdAt: "2026-01-01T00:00:00.000Z" },
]);
mkdirSync(join(repoPath, ".worktrees", "t1"), { recursive: true });
const deps = testDeps();

await runExpectingProcessExit(() => reposRegister([repoPath, "--json"], {}, deps));

expect(deps.lines).toHaveLength(1);
const body = JSON.parse(deps.lines[0]!);
expect(body.error?.code).toBe("locate-failed");
expect(body.registered).toBeUndefined();
});

test("no paths exits 2 with a usage error", async () => {
const deps = testDeps();
const code = await runExpectingProcessExit(() => reposRegister([], {}, deps));
Expand Down Expand Up @@ -250,4 +294,19 @@ describe("reposPrune", () => {
expect(code).toBe(2);
expect(loadRepoIndexEntries().map((e) => e.repoName)).toEqual(["gone"]);
});

test("a retained missing row tells the operator to locate it", async () => {
const { setKvValue } = await import("../../lib/state/index.ts");
updateRepoIndex("moved-repo", join(home, "gone-away"));
setKvValue("worktree-registry", "moved-repo", [
{ name: "t1", path: join(home, "gone-away", ".worktrees", "t1"), kind: "ephemeral", state: "on-deck", branch: "on-deck/t1", createdAt: "2026-01-01T00:00:00.000Z" },
]);
const deps = testDeps();

await reposPrune([], {}, deps);

expect(deps.lines.join("\n")).toContain("kept moved-repo");
expect(deps.lines.join("\n")).toContain("rt repos locate");
expect(loadRepoIndex()["moved-repo"]).toBeDefined();
});
});
Loading
Loading