feat(greptile-early): detect Greptile, ask once on public repos, open the early draft, wait for the review

bin/gstack-greptile-early backs /ship's early Greptile PR:
- detect: a root .greptile/ folder (which takes precedence), greptile.json,
  or a Greptile comment on the repo in the last 90 days; triggerOnDrafts from
  the effective root config; repo visibility; public-repo consent. It prints
  the signal, that /ship will push and open a draft now, the 10-minute wait
  cap and the absolute gstack-config command that turns it off.
- consent yes|no: the public-repo answer, remembered per repo in the
  project's state.
- open: opens the draft through gstack-post with a body saying /ship opened
  it early, and posts one @greptileai comment through gstack-post when the
  config does not set triggerOnDrafts: true. An open PR is left alone.
- wait: polls every 30 s for a completed Greptile check run, a Greptile
  review of the head commit or a summary naming it; each call returns within
  about 90 s and reports timeout 10 minutes after the PR opened.

gstack-config gains ship_greptile_early (default true, invalid values
rejected): on automatically whenever the repo uses Greptile, off per user.
The logic is in lib/greptile-early.ts behind an injectable runner, so its
fixture-repo tests run in the Windows lane; an end-to-end test drives the
real helper and gstack-post against a stub gh.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
garrytanandcapy-ai[bot] committed 2026-10-07 20:27:14 +00:00
1 parent b6abf58a6f
commit 7c836376c3
5 files changed
+598

No files matched your search

+11
View File
@@ -204,6 +204,11 @@ CONFIG_HEADER='# gstack configuration — edit freely, changes take effect on ne
# ship_rerun_backend: local # local | ubicloud — where free-suite flake reruns
# # run; ubicloud also needs UBICLOUD_API_KEY.
# # Invalid values are REJECTED (value kept).
# ship_greptile_early: true # true | false — when the repo uses Greptile, /ship
# # pushes and opens a draft PR after its free tests
# # so Greptile reviews in parallel (a public repo
# # asks once). false keeps the old order.
# # Invalid values are REJECTED (value kept).
#
# ─── Workspace-aware ship ────────────────────────────────────────────
# workspace_root: $HOME/conductor/workspaces # Where /ship looks for sibling
@@ -278,6 +283,7 @@ lookup_default() {
ship_measure_sweep_cases) echo "5" ;;
ship_measure_sweep_budget_usd) echo "150" ;;
ship_rerun_backend) echo "local" ;; # local | ubicloud (Ubicloud spend is opt-in)
ship_greptile_early) echo "true" ;; # true | false — /ship's early Greptile PR
# Unknown key: exit non-zero instead of printing "". The fallback pattern
# the preambles use,
# VAR=$(gstack-config get <key> 2>/dev/null || echo "<default>")
@@ -691,6 +697,11 @@ case "${1:-}" in
echo "Error: $KEY '$VALUE' is not a positive amount in USD (e.g. 25 or 2.50). Existing value left unchanged." >&2
exit 1
fi ;;
ship_greptile_early)
if [ "$VALUE" != "true" ] && [ "$VALUE" != "false" ]; then
echo "Error: ship_greptile_early '$VALUE' not recognized. Valid values: true, false. Existing value left unchanged." >&2
exit 1
fi ;;
ship_rerun_backend)
if [ "$VALUE" != "local" ] && [ "$VALUE" != "ubicloud" ]; then
echo "Error: ship_rerun_backend '$VALUE' not recognized. Valid values: local, ubicloud. Existing value left unchanged." >&2
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env bun
/**
* gstack-greptile-early — /ship's early Greptile review (detect, consent, open, wait).
*
* gstack-greptile-early detect
* gstack-greptile-early consent yes|no
* gstack-greptile-early open --base <branch> --title-file <file> [--ready] [--confirm <token>]
* gstack-greptile-early wait <pr-number> --since <epoch-seconds>
*
* On by default when the repo uses Greptile; `gstack-config set
* ship_greptile_early false` turns it off. Logic: lib/greptile-early.ts.
*/
import * as path from "path";
import { spawnSync } from "child_process";
import { runGreptileEarly } from "../lib/greptile-early";
process.exitCode = runGreptileEarly(process.argv.slice(2), {
run(cmd, args, input) {
const r = spawnSync(cmd, args, { input: input ?? "", encoding: "utf8", timeout: 120_000, maxBuffer: 16 * 1024 * 1024 });
return { status: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? (r.error ? String(r.error) : "") };
},
vars: process.env,
binDir: path.resolve(import.meta.dir),
bun: process.execPath,
now: () => Date.now(),
sleep: (ms) => Bun.sleepSync(ms),
out: (t) => process.stdout.write(t),
err: (t) => process.stderr.write(t),
});
+253
View File
@@ -0,0 +1,253 @@
/**
* greptile-early: /ship's early Greptile review (B2).
*
* When a repo uses Greptile (a root `.greptile/` folder, which takes
* precedence, a root `greptile.json`, or a Greptile comment on the repo in the
* last 90 days), /ship pushes and opens a draft PR right after its free tests
* pass, so Greptile reviews while /ship runs its own passes. It is on by
* default; `gstack-config set ship_greptile_early false` turns it off per user.
* On a public (or unknown-visibility) repo the first early push asks once,
* remembered per repo in the project's state.
*
* detect signal, triggerOnDrafts, visibility, consent, on/off
* consent yes|no remember the public-repo answer for this repo
* open --base B --title-file F [--ready] [--confirm T]
* open the early PR through gstack-post and post one
* `@greptileai` comment when Greptile skips drafts
* wait <pr> --since <epoch> poll (30 s) for a completed Greptile review of the
* PR's head commit; returns within ~90 s per call,
* `timeout` once 10 minutes have passed since <epoch>
*
* bin/gstack-greptile-early is the CLI; tests drive `runGreptileEarly` with a
* fake runner so the logic runs on every platform.
*/
import * as fs from "fs";
import * as path from "path";
import { resolveStateRoot, readConfigKey, type StateRootEnv } from "./state-root";
import { remoteSlug } from "./remote-identity";
export interface EarlyEnv {
run(cmd: string, args: string[], input?: string): { status: number; stdout: string; stderr: string };
vars: StateRootEnv;
/** Directory holding gstack-config and gstack-post (absolute; printed in user-facing lines). */
binDir: string;
/** How to run a Bun script in binDir. */
bun: string;
now(): number;
sleep(ms: number): void;
out(text: string): void;
err(text: string): void;
}
export const WAIT_CAP_SECONDS = 600;
export const POLL_SECONDS = 30;
const CALL_BUDGET_SECONDS = 90;
const COMMENT_WINDOW_DAYS = 90;
const TRIGGER = "@greptileai";
export const EARLY_BODY = "/ship opened this pull request early so Greptile can review it while /ship runs its own checks. /ship will replace this title and description, and marks it ready for review unless a draft was requested.\n";
const isGreptile = (login: unknown) => typeof login === "string" && /greptile/i.test(login);
function json<T>(text: string): T | undefined {
try { return JSON.parse(text) as T; } catch { return undefined; }
}
function gitRoot(env: EarlyEnv): string | undefined {
const r = env.run("git", ["rev-parse", "--show-toplevel"]);
return r.status === 0 ? r.stdout.trim() : undefined;
}
export type Signal = "config-folder" | "greptile.json" | "comment" | "none";
/** Root config files only: the folder takes precedence, and triggerOnDrafts must be literally true. */
export function configSignal(root: string): { signal: Signal; triggerOnDrafts: boolean } {
const folder = path.join(root, ".greptile");
if (fs.existsSync(folder) && fs.statSync(folder).isDirectory()) {
const cfg = json<{ triggerOnDrafts?: unknown }>(readOr(path.join(folder, "config.json")));
return { signal: "config-folder", triggerOnDrafts: cfg?.triggerOnDrafts === true };
}
const file = path.join(root, "greptile.json");
if (fs.existsSync(file)) {
const cfg = json<{ triggerOnDrafts?: unknown }>(readOr(file));
return { signal: "greptile.json", triggerOnDrafts: cfg?.triggerOnDrafts === true };
}
return { signal: "none", triggerOnDrafts: false };
}
function readOr(file: string): string {
try { return fs.readFileSync(file, "utf8"); } catch { return ""; }
}
/** A Greptile comment on any PR of this repo in the last 90 days (conversation or review comments). */
function recentComment(env: EarlyEnv): boolean {
const since = new Date(env.now() - COMMENT_WINDOW_DAYS * 86_400_000).toISOString();
for (const kind of ["issues", "pulls"]) {
const r = env.run("gh", ["api", `repos/{owner}/{repo}/${kind}/comments?sort=created&direction=desc&per_page=100&since=${since}`,
"--jq", "[.[] | {login: .user.login, created: .created_at}]"]);
const rows = r.status === 0 ? json<Array<{ login: string; created: string }>>(r.stdout) : undefined;
if (rows?.some(c => isGreptile(c.login) && c.created >= since)) return true;
}
return false;
}
function visibility(env: EarlyEnv): "public" | "private" | "unknown" {
const r = env.run("gh", ["repo", "view", "--json", "visibility", "--jq", ".visibility"]);
const v = r.status === 0 ? r.stdout.trim().toLowerCase() : "";
return v === "private" || v === "internal" ? "private" : v === "public" ? "public" : "unknown";
}
function consentFile(env: EarlyEnv): string | undefined {
const slug = env.run(path.join(env.binDir, "gstack-slug"), ["--get", "SLUG"]);
let id = slug.status === 0 ? slug.stdout.trim() : "";
if (!id) {
const origin = env.run("git", ["remote", "get-url", "origin"]);
id = origin.status === 0 ? remoteSlug(origin.stdout.trim()) : "";
}
return id ? path.join(resolveStateRoot(env.vars), "projects", id, "ship-greptile-early.json") : undefined;
}
function storedConsent(env: EarlyEnv): "yes" | "no" | undefined {
const file = consentFile(env);
const v = file ? json<{ consent?: string }>(readOr(file))?.consent : undefined;
return v === "yes" || v === "no" ? v : undefined;
}
const config = (env: EarlyEnv) => path.join(env.binDir, "gstack-config");
const SIGNAL_TEXT: Record<Exclude<Signal, "none">, string> = {
"config-folder": "a .greptile/ config folder",
"greptile.json": "greptile.json",
comment: `a Greptile comment on this repo in the last ${COMMENT_WINDOW_DAYS} days`,
};
function detect(env: EarlyEnv): number {
const line = (k: string, v: string) => env.out(`${k}: ${v}\n`);
const off = (reason: string) => { line("GREPTILE_EARLY", "off"); line("GREPTILE_EARLY_REASON", reason); return 0; };
if (readConfigKey("ship_greptile_early", env.vars) === "false") {
off("ship_greptile_early is false");
env.out(`Greptile early review is off for you. Turn it back on: ${config(env)} set ship_greptile_early true\n`);
return 0;
}
const root = gitRoot(env);
if (!root) return off("not in a git repository");
if (env.run("gh", ["auth", "status"]).status !== 0) return off("gh is missing or not logged in");
if (env.run("gh", ["repo", "view", "--json", "nameWithOwner"]).status !== 0) return off("not a GitHub repository");
const cfg = configSignal(root);
const signal: Signal = cfg.signal !== "none" ? cfg.signal : recentComment(env) ? "comment" : "none";
line("GREPTILE_SIGNAL", signal);
if (signal === "none") return off("no Greptile signal (.greptile/, greptile.json, or a Greptile comment in 90 days)");
line("GREPTILE_TRIGGER_ON_DRAFTS", String(cfg.triggerOnDrafts));
const vis = visibility(env);
line("REPO_VISIBILITY", vis);
const stored = vis === "private" ? undefined : storedConsent(env);
const consent = vis === "private" ? "not-needed" : stored === "yes" ? "granted" : stored === "no" ? "declined" : "ask";
line("GREPTILE_CONSENT", consent);
if (consent === "declined") return off("you declined early pushes for this public repo");
line("GREPTILE_EARLY", consent === "ask" ? "ask" : "on");
env.out(`Greptile: found ${SIGNAL_TEXT[signal]}. /ship will push this branch and open a draft PR now so Greptile reviews while /ship runs, then wait up to ${WAIT_CAP_SECONDS / 60} minutes for that review at Step 10. Turn this off: ${config(env)} set ship_greptile_early false\n`);
return 0;
}
function consent(env: EarlyEnv, answer: string | undefined): number {
if (answer !== "yes" && answer !== "no") { env.err("usage: gstack-greptile-early consent yes|no\n"); return 64; }
const file = consentFile(env);
if (!file) { env.err("gstack-greptile-early: cannot resolve this project's state directory.\n"); return 1; }
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, JSON.stringify({ consent: answer, decided_at: new Date(env.now()).toISOString() }) + "\n");
env.out(`GREPTILE_CONSENT: ${answer === "yes" ? "granted" : "declined"}\n`);
return 0;
}
function flag(args: string[], name: string): string | undefined {
const i = args.indexOf(name);
return i >= 0 ? args[i + 1] : undefined;
}
function privateFile(root: string, stem: string, text: string): string {
const dir = path.join(root, ".gstack", "tmp");
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
const file = path.join(dir, `${stem}.${process.pid}.${Math.random().toString(36).slice(2, 10)}`);
fs.writeFileSync(file, text, { mode: 0o600 });
return file;
}
function open(env: EarlyEnv, args: string[]): number {
const base = flag(args, "--base");
const titleFile = flag(args, "--title-file");
const confirm = flag(args, "--confirm");
const ready = args.includes("--ready");
if (!base || !titleFile) { env.err("usage: gstack-greptile-early open --base <branch> --title-file <file> [--ready] [--confirm <token>]\n"); return 64; }
const root = gitRoot(env);
if (!root) { env.err("gstack-greptile-early: not in a git repository.\n"); return 64; }
const branch = env.run("git", ["branch", "--show-current"]).stdout.trim();
const existing = env.run("gh", ["pr", "list", "--head", branch, "--state", "open", "--json", "number,url"]);
const found = existing.status === 0 ? json<Array<{ number: number; url: string }>>(existing.stdout) : undefined;
if (!found) { env.err(`gstack-greptile-early: could not look up open PRs for ${branch}; not opening one.\n${existing.stderr}`); return 3; }
if (found.length) {
env.out(`EARLY_PR: none (PR ${found[0]!.number} is already open; Step 10 triages it as before)\n`);
return 0;
}
const post = path.join(env.binDir, "gstack-post");
const body = privateFile(root, "greptile-early-body", EARLY_BODY);
try {
const created = env.run(env.bun, [post, "pr-create", "--base", base, "--title-file", titleFile, "--body-file", body, ...(ready ? [] : ["--draft"]), ...(confirm ? ["--confirm", confirm] : [])]);
env.out(created.stdout);
if (created.status !== 0) { env.err(created.stderr); return created.status; }
const url = /^https?:\/\/\S+\/pull\/(\d+)\s*$/m.exec(created.stdout);
if (!url) { env.err("gstack-post did not print the new PR URL.\n"); return 3; }
env.out(`EARLY_PR: ${url[1]}\nEARLY_PR_URL: ${url[0].trim()}\nEARLY_PR_OPENED_AT: ${Math.floor(env.now() / 1000)}\n`);
if (ready) { env.out("GREPTILE_TRIGGER: not needed (ready PR; Greptile reviews it when opened)\n"); return 0; }
if (configSignal(root).triggerOnDrafts) { env.out("GREPTILE_TRIGGER: not needed (triggerOnDrafts: true)\n"); return 0; }
const comment = privateFile(root, "greptile-trigger", TRIGGER + "\n");
try {
const posted = env.run(env.bun, [post, "pr-comment", url[1]!, "--body-file", comment]);
env.out(posted.status === 0 ? "GREPTILE_TRIGGER: posted\n" : `GREPTILE_TRIGGER: failed (gstack-post exit ${posted.status}); Greptile may not review the draft\n`);
} finally { fs.rmSync(comment, { force: true }); }
return 0;
} finally { fs.rmSync(body, { force: true }); }
}
type Done = "check run" | "review" | "summary comment";
/** A completed Greptile check run on the head, a Greptile review of the head, or a summary comment naming it. */
export function reviewDone(env: EarlyEnv, pr: string, sha: string): Done | undefined {
const checks = env.run("gh", ["api", `repos/{owner}/{repo}/commits/${sha}/check-runs`, "--jq", "[.check_runs[] | {name, status, app: .app.slug}]"]);
if (json<Array<{ name: string; status: string; app: string }>>(checks.stdout)?.some(c => c.status === "completed" && (isGreptile(c.name) || isGreptile(c.app)))) return "check run";
const reviews = env.run("gh", ["api", `repos/{owner}/{repo}/pulls/${pr}/reviews`, "--jq", "[.[] | {login: .user.login, commit: .commit_id}]"]);
if (json<Array<{ login: string; commit: string }>>(reviews.stdout)?.some(r => isGreptile(r.login) && r.commit === sha)) return "review";
const comments = env.run("gh", ["api", `repos/{owner}/{repo}/issues/${pr}/comments`, "--jq", '[.[] | select(.user.login | test("greptile"; "i")) | .body]']);
if (json<string[]>(comments.stdout)?.some(b => b.includes(sha.slice(0, 7)))) return "summary comment";
return undefined;
}
function wait(env: EarlyEnv, args: string[]): number {
const pr = args[0];
const since = Number(flag(args, "--since"));
if (!pr || !/^[1-9][0-9]*$/.test(pr) || !Number.isInteger(since) || since <= 0) { env.err("usage: gstack-greptile-early wait <pr-number> --since <epoch-seconds>\n"); return 64; }
const head = env.run("gh", ["pr", "view", pr, "--json", "headRefOid", "--jq", ".headRefOid"]);
const sha = head.stdout.trim();
if (head.status !== 0 || !/^[0-9a-f]{40}$/.test(sha)) { env.out("GREPTILE_REVIEW: unavailable (could not read the PR head commit)\n"); return 0; }
const started = env.now();
for (;;) {
const done = reviewDone(env, pr, sha);
if (done) { env.out(`GREPTILE_REVIEW: complete (${done} on ${sha.slice(0, 7)})\n`); return 0; }
const elapsed = Math.floor(env.now() / 1000) - since;
if (elapsed >= WAIT_CAP_SECONDS) { env.out(`GREPTILE_REVIEW: timeout (no completed Greptile review of ${sha.slice(0, 7)} after ${WAIT_CAP_SECONDS / 60} minutes)\n`); return 0; }
const mmss = `${Math.floor(elapsed / 60)}m${String(elapsed % 60).padStart(2, "0")}s`;
env.out(`Greptile: waiting for its review of ${sha.slice(0, 7)} (${mmss} of ${WAIT_CAP_SECONDS / 60}m). Turn early review off: ${config(env)} set ship_greptile_early false\n`);
if ((env.now() - started) / 1000 + POLL_SECONDS > CALL_BUDGET_SECONDS) { env.out("GREPTILE_REVIEW: pending\n"); return 0; }
env.sleep(POLL_SECONDS * 1000);
}
}
export function runGreptileEarly(argv: string[], env: EarlyEnv): number {
const [cmd, ...rest] = argv;
switch (cmd) {
case "detect": return detect(env);
case "consent": return consent(env, rest[0]);
case "open": return open(env, rest);
case "wait": return wait(env, rest);
default:
env.err("usage: gstack-greptile-early {detect | consent yes|no | open --base B --title-file F [--ready] [--confirm T] | wait <pr> --since <epoch>}\n");
return cmd === "help" || cmd === "--help" ? 0 : 64;
}
}
+73
View File
@@ -0,0 +1,73 @@
/**
* gstack-greptile-early open, end to end: the real helper and the real
* gstack-post against a stub gh in fixture repos (B2, CEO-8). Whether the
* `@greptileai` trigger comment reaches gh depends on triggerOnDrafts in the
* root .greptile/ folder or greptile.json. POSIX only (shebang stubs);
* test/greptile-early.test.ts covers the logic on Windows.
*/
import { afterAll, describe, expect, test } from "bun:test";
import { spawnSync } from "child_process";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
const ROOT = path.resolve(import.meta.dir, "..");
const EARLY = path.join(ROOT, "bin", "gstack-greptile-early");
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "greptile-early-cli-"));
afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));
function repo(files: Record<string, string>) {
const dir = fs.mkdtempSync(path.join(tmp, "repo-"));
const stubs = path.join(dir, ".stubs");
const log = path.join(dir, ".log");
fs.mkdirSync(stubs);
fs.mkdirSync(log);
fs.writeFileSync(path.join(tmp, "gitconfig"), "");
const env = { ...process.env, GIT_CONFIG_GLOBAL: path.join(tmp, "gitconfig"), GIT_CONFIG_NOSYSTEM: "1", GSTACK_HOME: path.join(dir, ".state"), PATH: `${stubs}${path.delimiter}${process.env.PATH}` };
for (const args of [["init", "-q", "-b", "feature/x"], ["remote", "add", "origin", "https://github.com/acme/widget.git"]]) {
spawnSync("git", args, { cwd: dir, env, timeout: 10_000 });
}
for (const [name, text] of Object.entries(files)) {
fs.mkdirSync(path.dirname(path.join(dir, name)), { recursive: true });
fs.writeFileSync(path.join(dir, name), text);
}
fs.writeFileSync(path.join(stubs, "gh"), `#!/usr/bin/env bash
case "$1 $2" in
"repo view") echo PRIVATE; exit 0 ;;
"pr list") echo '[]'; exit 0 ;;
esac
n=$(ls "${log}" | grep -c args)
for a in "$@"; do printf '%s\\0' "$a"; done > "${log}/$n.args"
cat > "${log}/$n.stdin"
[ "$1 $2" = "pr create" ] && echo "https://github.com/acme/widget/pull/12"
exit 0
`, { mode: 0o755 });
fs.writeFileSync(path.join(dir, ".title"), "v1.2.3 feat: early review\n");
const r = spawnSync(process.execPath, [EARLY, "open", "--base", "main", "--title-file", path.join(dir, ".title")], { cwd: dir, env, encoding: "utf8", timeout: 60_000 });
const calls = fs.readdirSync(log).filter(f => f.endsWith(".args")).sort((a, b) => parseInt(a) - parseInt(b)).map(f => ({
args: fs.readFileSync(path.join(log, f), "utf8").split("\0").slice(0, -1),
stdin: fs.readFileSync(path.join(log, f.replace(".args", ".stdin")), "utf8"),
}));
return { r, calls };
}
describe("gstack-greptile-early open", () => {
test("greptile.json without triggerOnDrafts: draft PR, then one @greptileai comment", () => {
const { r, calls } = repo({ "greptile.json": "{}" });
expect(r.status, r.stderr).toBe(0);
expect(r.stdout).toContain("EARLY_PR: 12");
expect(calls.map(c => c.args)).toEqual([
["pr", "create", "--base=main", "--title=v1.2.3 feat: early review", "--body-file=-", "--draft"],
["pr", "comment", "12", "--body-file=-"],
]);
expect(calls[0]!.stdin).toContain("/ship opened this pull request early");
expect(calls[1]!.stdin).toBe("@greptileai\n");
});
test(".greptile/config.json with triggerOnDrafts: true: draft PR and no comment", () => {
const { r, calls } = repo({ ".greptile/config.json": '{"triggerOnDrafts": true}', "greptile.json": "{}" });
expect(r.status, r.stderr).toBe(0);
expect(r.stdout).toContain("GREPTILE_TRIGGER: not needed (triggerOnDrafts: true)");
expect(calls.map(c => c.args[1])).toEqual(["create"]);
});
});
+232
View File
@@ -0,0 +1,232 @@
/**
* /ship's early Greptile review (B2: CEO-8 detection and draft trigger, DX-10
* status lines, ENG-20 public-repo consent, the gate decision that it is on by
* default with a per-user off switch). Drives lib/greptile-early.ts in process
* against fixture repos with a fake gh, so it runs in the Windows lane too.
*/
import { afterAll, describe, expect, test } from "bun:test";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { EARLY_BODY, runGreptileEarly, type EarlyEnv } from "../lib/greptile-early";
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "greptile-early-"));
afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));
const SHA = "a".repeat(7) + "b".repeat(33);
const DAY = 86_400_000;
const NOW = Date.parse("2026-10-07T12:00:00Z");
interface Call { cmd: string; args: string[]; file?: string }
function fixture(opts: {
files?: Record<string, string>;
visibility?: string;
comments?: Array<{ login: string; created: string }>;
openPrs?: Array<{ number: number; url: string }>;
checks?: Array<{ name: string; status: string; app: string }>;
reviews?: Array<{ login: string; commit: string }>;
summaries?: string[];
config?: string;
} = {}) {
const root = fs.mkdtempSync(path.join(tmp, "repo-"));
const state = fs.mkdtempSync(path.join(tmp, "state-"));
for (const [name, text] of Object.entries(opts.files ?? {})) {
fs.mkdirSync(path.dirname(path.join(root, name)), { recursive: true });
fs.writeFileSync(path.join(root, name), text);
}
if (opts.config) fs.writeFileSync(path.join(state, "config.yaml"), opts.config);
const calls: Call[] = [];
const out: string[] = [];
let clock = NOW;
const ok = (stdout: string) => ({ status: 0, stdout, stderr: "" });
const env: EarlyEnv = {
vars: { GSTACK_HOME: state },
binDir: "/opt/gstack/bin",
bun: "bun",
now: () => clock,
sleep: ms => { clock += ms; },
out: t => { out.push(t); },
err: t => { out.push(t); },
run(cmd, args) {
const call: Call = { cmd, args };
if (cmd === "bun") {
const bodyFile = args[args.indexOf("--body-file") + 1]!;
call.file = fs.readFileSync(bodyFile, "utf8");
}
calls.push(call);
const joined = args.join(" ");
if (cmd === "git" && args[0] === "rev-parse") return ok(root + "\n");
if (cmd === "git" && args[0] === "branch") return ok("feature/x\n");
if (cmd === "git" && args[0] === "remote") return ok("git@github.com:acme/widget.git\n");
if (cmd.endsWith("gstack-slug")) return ok("acme-widget\n");
if (cmd === "gh" && args[0] === "auth") return ok("");
if (cmd === "gh" && joined.startsWith("repo view --json visibility")) return ok((opts.visibility ?? "PRIVATE") + "\n");
if (cmd === "gh" && args[0] === "repo") return ok("{}");
if (cmd === "gh" && joined.includes("/comments?sort=created")) return ok(JSON.stringify(joined.includes("/issues/") ? opts.comments ?? [] : []));
if (cmd === "gh" && joined.startsWith("pr list")) return ok(JSON.stringify(opts.openPrs ?? []));
if (cmd === "gh" && joined.startsWith("pr view")) return ok(SHA + "\n");
if (cmd === "gh" && joined.includes("/check-runs")) return ok(JSON.stringify(opts.checks ?? []));
if (cmd === "gh" && joined.includes("/reviews")) return ok(JSON.stringify(opts.reviews ?? []));
if (cmd === "gh" && joined.includes("/issues/12/comments")) return ok(JSON.stringify(opts.summaries ?? []));
if (cmd === "bun" && args[1] === "pr-create") return ok("REPO_VISIBILITY: private\nhttps://github.com/acme/widget/pull/12\nPOSTED: pr-create\n");
if (cmd === "bun") return ok("POSTED\n");
return { status: 1, stdout: "", stderr: "unexpected" };
},
};
const run = (...argv: string[]) => {
out.length = 0;
const code = runGreptileEarly(argv, env);
return { code, out: out.join("") };
};
const posts = () => calls.filter(c => c.cmd === "bun").map(c => ({ op: c.args[1], args: c.args.slice(2), file: c.file }));
return { root, state, run, posts, calls, advance: (ms: number) => { clock += ms; } };
}
const value = (out: string, key: string) => new RegExp(`^${key}: (.*)$`, "m").exec(out)?.[1];
describe("detection (CEO-8, DX-10)", () => {
test("a .greptile/ folder wins over greptile.json, and only its triggerOnDrafts counts", () => {
const f = fixture({ files: { ".greptile/config.json": '{"strictness": 2}', "greptile.json": '{"triggerOnDrafts": true}' } });
const r = f.run("detect");
expect(value(r.out, "GREPTILE_SIGNAL")).toBe("config-folder");
expect(value(r.out, "GREPTILE_TRIGGER_ON_DRAFTS")).toBe("false");
expect(value(r.out, "GREPTILE_EARLY")).toBe("on");
const g = fixture({ files: { ".greptile/config.json": '{"triggerOnDrafts": true}' } });
expect(value(g.run("detect").out, "GREPTILE_TRIGGER_ON_DRAFTS")).toBe("true");
});
test("greptile.json alone is a signal; a non-boolean triggerOnDrafts is not true", () => {
const f = fixture({ files: { "greptile.json": '{"triggerOnDrafts": "true"}' } });
const r = f.run("detect");
expect(value(r.out, "GREPTILE_SIGNAL")).toBe("greptile.json");
expect(value(r.out, "GREPTILE_TRIGGER_ON_DRAFTS")).toBe("false");
});
test("a Greptile comment counts only within 90 days", () => {
const recent = fixture({ comments: [{ login: "greptile-apps[bot]", created: new Date(NOW - 10 * DAY).toISOString() }] });
expect(value(recent.run("detect").out, "GREPTILE_SIGNAL")).toBe("comment");
const old = fixture({ comments: [{ login: "greptile-apps[bot]", created: new Date(NOW - 120 * DAY).toISOString() }, { login: "octocat", created: new Date(NOW - DAY).toISOString() }] });
const r = old.run("detect");
expect(value(r.out, "GREPTILE_SIGNAL")).toBe("none");
expect(value(r.out, "GREPTILE_EARLY")).toBe("off");
});
test("without Greptile nothing changes", () => {
const r = fixture().run("detect");
expect(value(r.out, "GREPTILE_EARLY")).toBe("off");
expect(r.out).not.toContain("will push");
});
test("the plan line names the signal, the draft push, the wait cap and the off switch", () => {
const r = fixture({ files: { "greptile.json": "{}" } }).run("detect");
expect(r.out).toContain("Greptile: found greptile.json. /ship will push this branch and open a draft PR now");
expect(r.out).toContain("wait up to 10 minutes");
expect(r.out).toContain("Turn this off: /opt/gstack/bin/gstack-config set ship_greptile_early false");
});
test("ship_greptile_early false turns it off and says how to turn it back on", () => {
const r = fixture({ files: { "greptile.json": "{}" }, config: "ship_greptile_early: false\n" }).run("detect");
expect(value(r.out, "GREPTILE_EARLY")).toBe("off");
expect(r.out).toContain("/opt/gstack/bin/gstack-config set ship_greptile_early true");
});
});
describe("public-repo consent (ENG-20)", () => {
test("a public repo asks once; the answer is remembered per repo", () => {
const f = fixture({ files: { "greptile.json": "{}" }, visibility: "PUBLIC" });
let r = f.run("detect");
expect(value(r.out, "GREPTILE_CONSENT")).toBe("ask");
expect(value(r.out, "GREPTILE_EARLY")).toBe("ask");
expect(f.run("consent", "yes").out).toContain("GREPTILE_CONSENT: granted");
expect(JSON.parse(fs.readFileSync(path.join(f.state, "projects/acme-widget/ship-greptile-early.json"), "utf8")).consent).toBe("yes");
r = f.run("detect");
expect(value(r.out, "GREPTILE_CONSENT")).toBe("granted");
expect(value(r.out, "GREPTILE_EARLY")).toBe("on");
f.run("consent", "no");
r = f.run("detect");
expect(value(r.out, "GREPTILE_EARLY")).toBe("off");
expect(value(r.out, "GREPTILE_EARLY_REASON")).toContain("declined");
});
test("unknown visibility asks like public; a private repo needs no consent", () => {
expect(value(fixture({ files: { "greptile.json": "{}" }, visibility: "" }).run("detect").out, "GREPTILE_CONSENT")).toBe("ask");
expect(value(fixture({ files: { "greptile.json": "{}" } }).run("detect").out, "GREPTILE_CONSENT")).toBe("not-needed");
});
});
describe("opening the early PR (CEO-8)", () => {
test("a draft gets one @greptileai comment through gstack-post when Greptile skips drafts", () => {
const f = fixture({ files: { "greptile.json": "{}" } });
const r = f.run("open", "--base", "main", "--title-file", "/t");
expect(r.code).toBe(0);
expect(value(r.out, "EARLY_PR")).toBe("12");
expect(value(r.out, "EARLY_PR_OPENED_AT")).toBe(String(NOW / 1000));
expect(value(r.out, "GREPTILE_TRIGGER")).toBe("posted");
const [create, comment] = f.posts();
expect(create).toMatchObject({ op: "pr-create", file: EARLY_BODY });
expect(create!.args).toEqual(["--base", "main", "--title-file", "/t", "--body-file", expect.any(String), "--draft"]);
expect(comment).toMatchObject({ op: "pr-comment", file: "@greptileai\n" });
expect(comment!.args[0]).toBe("12");
expect(fs.readdirSync(path.join(f.root, ".gstack/tmp"))).toEqual([]);
});
for (const [name, files] of [["greptile.json", { "greptile.json": '{"triggerOnDrafts": true}' }], [".greptile/ folder", { ".greptile/config.json": '{"triggerOnDrafts": true}' }]] as const) {
test(`triggerOnDrafts: true in ${name} posts no trigger comment`, () => {
const f = fixture({ files });
const r = f.run("open", "--base", "main", "--title-file", "/t");
expect(value(r.out, "GREPTILE_TRIGGER")).toBe("not needed (triggerOnDrafts: true)");
expect(f.posts().map(p => p.op)).toEqual(["pr-create"]);
});
}
test("a ready PR is not a draft and needs no trigger", () => {
const f = fixture({ files: { "greptile.json": "{}" } });
f.run("open", "--base", "main", "--title-file", "/t", "--ready");
expect(f.posts()).toHaveLength(1);
expect(f.posts()[0]!.args).not.toContain("--draft");
});
test("an already open PR is left alone", () => {
const f = fixture({ files: { "greptile.json": "{}" }, openPrs: [{ number: 5, url: "https://github.com/acme/widget/pull/5" }] });
const r = f.run("open", "--base", "main", "--title-file", "/t");
expect(r.code).toBe(0);
expect(r.out).toContain("EARLY_PR: none (PR 5 is already open");
expect(f.posts()).toEqual([]);
});
});
describe("waiting for the review (CEO-8 completion signal)", () => {
const since = String(NOW / 1000);
test("a completed Greptile check run on the head commit completes the wait", () => {
const r = fixture({ checks: [{ name: "Greptile Review", status: "completed", app: "greptile-apps" }] }).run("wait", "12", "--since", since);
expect(r.out).toContain("GREPTILE_REVIEW: complete (check run on aaaaaaa)");
});
test("a Greptile review of the head commit, or a summary naming it, completes the wait", () => {
expect(fixture({ reviews: [{ login: "greptile-apps[bot]", commit: SHA }] }).run("wait", "12", "--since", since).out).toContain("complete (review");
expect(fixture({ summaries: ["Greptile Summary ... Last reviewed commit: aaaaaaab"] }).run("wait", "12", "--since", since).out).toContain("complete (summary comment");
});
test("an in-progress check, an older head's review or another bot's comment does not count", () => {
const f = fixture({
checks: [{ name: "Greptile Review", status: "in_progress", app: "greptile-apps" }, { name: "ci", status: "completed", app: "github-actions" }],
reviews: [{ login: "greptile-apps[bot]", commit: "c".repeat(40) }],
summaries: ["Greptile Summary for an older commit"],
});
const r = f.run("wait", "12", "--since", since);
expect(r.out).toContain("GREPTILE_REVIEW: pending");
expect(r.out).toContain("Greptile: waiting for its review of aaaaaaa (");
expect(r.out).toContain("Turn early review off: /opt/gstack/bin/gstack-config set ship_greptile_early false");
});
test("each call returns within its budget, and the wait times out 10 minutes after the PR opened", () => {
const f = fixture();
const polls = () => f.calls.filter(c => c.args.join(" ").includes("/check-runs")).length;
f.run("wait", "12", "--since", since);
expect(polls()).toBe(4); // at 0, 30, 60 and 90 seconds
f.advance(9 * 60_000);
const r = f.run("wait", "12", "--since", since);
expect(r.out).toContain("GREPTILE_REVIEW: timeout");
expect(r.out).not.toContain("GREPTILE_REVIEW: complete");
});
});