@discovery-tree/runner 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +33 -1
  2. package/dist/cli.js +320 -30
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -118,9 +118,17 @@ could not do it. What it may do without asking:
118
118
  `cargo` and `go` run code**, from the repository (package scripts, build files, tests) or
119
119
  written by the agent, so this list amounts to arbitrary code execution as you. It keeps the
120
120
  agent from stalling on every command; it is not a sandbox.
121
+ Also on it, the `gh` commands that only read (`gh pr view/diff/checks/list/status`,
122
+ `gh run view/list`, `gh issue view/list`, `gh repo view`), so the agent can see the pull
123
+ request Discovery Tree opened from its branch, its checks and review comments. They run as
124
+ your `gh` login and can read whatever it can. Install the [GitHub CLI](https://cli.github.com)
125
+ and run `gh auth login` for them to work; `doctor` checks.
121
126
  Left off on purpose: `WebFetch` and `WebSearch` (the easiest way for a manipulated agent to
122
127
  send data out), `find` (`-exec`), `sed`, `cp`, `mv` (they can write anywhere; the Edit and
123
- Write tools cover changes in the worktree) and `git push` (the runner pushes).
128
+ Write tools cover changes in the worktree), `git push` (the runner pushes) and `gh` commands
129
+ that change GitHub, `gh api` included (Discovery Tree opens the pull request). Add, say,
130
+ `"Bash(gh pr comment *)"` to `extraAllowedTools` if you want the agent to reply on its pull
131
+ request as you.
124
132
  - **The deny list** (`--disallowedTools`, which wins over the allow-list): the agent's file
125
133
  tools may not read or edit `~/.ssh`, `~/.aws`, `~/.config/gcloud`, `~/.azure`, `~/.gnupg`,
126
134
  `~/.netrc`, `~/.git-credentials`, `~/.config/gh`, `~/.docker/config.json`, `~/.kube`,
@@ -188,6 +196,30 @@ url."git@my-alias:".insteadOf "git@github.com:"`), which git applies after the r
188
196
  5. When Discovery Tree closes the session, the worktree is removed (`git worktree remove --force`).
189
197
  The branch stays, locally and on the remote.
190
198
 
199
+ ### Screenshots
200
+
201
+ Discovery Tree asks for a screenshot of every user-visible change, in the pull request
202
+ description. A hosted agent's platform keeps the images it captures; on your computer they are
203
+ files nobody else can open, and GitHub has no API for pull request attachments. So the runner
204
+ publishes them:
205
+
206
+ 1. The agent saves images (PNG, JPEG, GIF, WebP; up to 12 a turn, 8 MB each) in `.dt-evidence/`
207
+ at the root of its worktree. The folder is listed in the clone's `.git/info/exclude`, so
208
+ neither the agent's commits nor the runner's commit of leftovers include it.
209
+ 2. At the end of the turn, after the work branch is pushed, the runner commits them to a branch of
210
+ their own, `dt-evidence/<workBranch>` with `/` written `%2F` (built with `git hash-object`/`commit-tree`, without
211
+ touching the worktree), and pushes it. The images never merge with the change.
212
+ 3. It adds a `## Screenshots` section to the turn's final message, linking each image as
213
+ `https://github.com/<owner>/<repo>/raw/<commit>/<file>`. That message becomes the pull request
214
+ description, where the images render for anyone who can read the repository, and Discovery
215
+ Tree's review inbox reads them through its GitHub App. Published images move to
216
+ `.dt-evidence/published/`. On a later turn, when the pull request is already open,
217
+ Discovery Tree adds that turn's screenshots to the end of its description.
218
+
219
+ The `dt-evidence/…` branches stay on the remote; delete one (`git push origin --delete
220
+ dt-evidence/<branch>`) once its pull request is closed. Its images stop showing after GitHub
221
+ cleans up the commits.
222
+
191
223
  A session without a repository runs in an empty scratch directory.
192
224
 
193
225
  State lives under `$XDG_STATE_HOME/discovery-tree/runner` (usually `~/.local/state/…`): one folder
package/dist/cli.js CHANGED
@@ -33,7 +33,7 @@ var RUNNER_EVENT_TEXT_MAX_LENGTH = 64e3;
33
33
  var RUNNER_EVENTS_MAX_BODY_BYTES = 8 * 1024 * 1024;
34
34
 
35
35
  // src/version.ts
36
- var RUNNER_VERSION = true ? "0.1.3" : "0.0.0-dev";
36
+ var RUNNER_VERSION = true ? "0.1.5" : "0.0.0-dev";
37
37
  var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
38
38
 
39
39
  // src/api.ts
@@ -331,7 +331,19 @@ function runnerSystemPrompt(input) {
331
331
  "Commit your work to this branch as you go, with clear, descriptive commit messages.",
332
332
  "Do not push, do not switch, create or delete branches, and do not rewrite commits that may",
333
333
  "already be pushed: the runner commits anything left over and pushes this branch for you",
334
- "at the end of every turn."
334
+ "at the end of every turn.",
335
+ "Do not open a pull request either: Discovery Tree opens it from this branch when a turn",
336
+ "ends, with that turn\u2019s final message as its description, and later turns add to it.",
337
+ "Before then (your first turn) there is none; say so rather than trying to open one.",
338
+ `To read it, use \`gh pr view ${input.workBranch}\` (\`--comments\` for the conversation),`,
339
+ "`gh pr diff`, `gh pr checks`, and `gh run view` for a check run\u2019s logs. Only `gh` commands",
340
+ "that read are allowed; ones that change GitHub (comment, edit, merge, `gh api`) are denied.",
341
+ "For screenshots of a user-visible change, save the images (PNG, JPEG, GIF or WebP) in",
342
+ "`.dt-evidence/` at the root of this worktree, named for what they show",
343
+ "(`settings-dark.png`), for example with `npx playwright screenshot <url> .dt-evidence/<name>.png`.",
344
+ "Do not commit them, upload them or link them yourself: at the end of the turn the runner",
345
+ "publishes them on a branch of their own and adds them, linked, under your final message,",
346
+ "so they appear in the pull request description. The folder is ignored by git."
335
347
  ].join(" ");
336
348
  }
337
349
 
@@ -403,6 +415,16 @@ var DEFAULT_ALLOWED_TOOLS = [
403
415
  "Bash(git stash *)",
404
416
  "Bash(git blame *)",
405
417
  "Bash(git grep *)",
418
+ "Bash(gh pr view *)",
419
+ "Bash(gh pr diff *)",
420
+ "Bash(gh pr checks *)",
421
+ "Bash(gh pr list *)",
422
+ "Bash(gh pr status *)",
423
+ "Bash(gh run view *)",
424
+ "Bash(gh run list *)",
425
+ "Bash(gh issue view *)",
426
+ "Bash(gh issue list *)",
427
+ "Bash(gh repo view *)",
406
428
  "Bash(npm *)",
407
429
  "Bash(npx *)",
408
430
  "Bash(pnpm *)",
@@ -576,7 +598,7 @@ function sleep(ms, signal) {
576
598
  }
577
599
 
578
600
  // src/session-manager.ts
579
- import { mkdir as mkdir5, rm as rm4 } from "node:fs/promises";
601
+ import { mkdir as mkdir6, rm as rm5 } from "node:fs/promises";
580
602
 
581
603
  // src/git.ts
582
604
  import { mkdir as mkdir2, rm as rm2, stat } from "node:fs/promises";
@@ -834,18 +856,28 @@ async function defaultBranch(repoDir) {
834
856
  }
835
857
  async function commitAndPush(input) {
836
858
  const { worktree } = input;
859
+ const exclude = input.exclude ?? [];
860
+ const excluded = (line) => {
861
+ const path = line.slice(3).replace(/^"|"$/g, "");
862
+ return exclude.some((p) => path === p || path.startsWith(`${p}/`));
863
+ };
837
864
  let committed = false;
838
865
  try {
839
- const dirty = (await git(worktree, ["status", "--porcelain"])).length > 0;
866
+ const status2 = await git(worktree, ["status", "--porcelain"]);
867
+ const dirty = status2.split("\n").some((line) => line && !excluded(line));
840
868
  if (dirty) {
841
869
  await git(worktree, ["add", "-A"]);
842
- const identity = await gitOk(worktree, ["config", "user.email"]) ? [] : [
870
+ if (exclude.length) await git(worktree, ["reset", "-q", "--", ...exclude]);
871
+ }
872
+ const staged = dirty && !await gitOk(worktree, ["diff", "--cached", "--quiet"]);
873
+ if (staged) {
874
+ const identity2 = await gitOk(worktree, ["config", "user.email"]) ? [] : [
843
875
  "-c",
844
876
  "user.name=Discovery Tree runner",
845
877
  "-c",
846
878
  "user.email=dt-runner@users.noreply.local"
847
879
  ];
848
- await git(worktree, [...identity, "commit", "--no-verify", "-q", "-m", input.message]);
880
+ await git(worktree, [...identity2, "commit", "--no-verify", "-q", "-m", input.message]);
849
881
  committed = true;
850
882
  }
851
883
  } catch (err) {
@@ -1133,43 +1165,223 @@ function takeBatch(pending) {
1133
1165
 
1134
1166
  // src/session.ts
1135
1167
  import { spawn as spawn2 } from "node:child_process";
1168
+ import { basename, dirname as dirname4 } from "node:path";
1136
1169
  import { createInterface } from "node:readline";
1137
1170
 
1171
+ // src/evidence.ts
1172
+ import { mkdir as mkdir4, mkdtemp, readdir, readFile as readFile3, rename as rename2, rm as rm3, stat as stat2, writeFile as writeFile3 } from "node:fs/promises";
1173
+ import { tmpdir } from "node:os";
1174
+ import { isAbsolute as isAbsolute2, join as join4 } from "node:path";
1175
+ var EVIDENCE_DIR = ".dt-evidence";
1176
+ var PUBLISHED_DIR = "published";
1177
+ var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set(["png", "jpg", "jpeg", "gif", "webp"]);
1178
+ var MAX_EVIDENCE_IMAGES = 12;
1179
+ var MAX_EVIDENCE_BYTES = 8 * 1024 * 1024;
1180
+ function evidenceBranch(workBranch) {
1181
+ return `dt-evidence/${workBranch.replace(/%/g, "%25").replace(/\//g, "%2F")}`;
1182
+ }
1183
+ async function ensureEvidenceDir(worktree) {
1184
+ await mkdir4(join4(worktree, EVIDENCE_DIR), { recursive: true });
1185
+ const rel = await git(worktree, ["rev-parse", "--git-path", "info/exclude"]);
1186
+ const file = isAbsolute2(rel) ? rel : join4(worktree, rel);
1187
+ const line = `/${EVIDENCE_DIR}/`;
1188
+ let current = "";
1189
+ try {
1190
+ current = await readFile3(file, "utf8");
1191
+ } catch {
1192
+ }
1193
+ if (current.split("\n").some((l) => l.trim() === line)) return;
1194
+ await mkdir4(join4(file, ".."), { recursive: true });
1195
+ const sep = current && !current.endsWith("\n") ? "\n" : "";
1196
+ await writeFile3(
1197
+ file,
1198
+ `${current}${sep}# Screenshots dt-runner publishes on their own branch
1199
+ ${line}
1200
+ `
1201
+ );
1202
+ }
1203
+ async function publishEvidence(input) {
1204
+ const dir = join4(input.worktree, EVIDENCE_DIR);
1205
+ let found;
1206
+ try {
1207
+ found = await waitingImages(dir);
1208
+ } catch (err) {
1209
+ const why = err instanceof Error ? err.message : String(err);
1210
+ return { images: [], skipped: [], error: `Reading the screenshots failed: ${why}` };
1211
+ }
1212
+ const skipped = found.filter((f) => f.size > MAX_EVIDENCE_BYTES).map((f) => f.name);
1213
+ const fitting = found.filter((f) => f.size <= MAX_EVIDENCE_BYTES);
1214
+ skipped.push(...fitting.slice(MAX_EVIDENCE_IMAGES).map((f) => f.name));
1215
+ const files = fitting.slice(0, MAX_EVIDENCE_IMAGES);
1216
+ if (!files.length) return { images: [], skipped, error: null };
1217
+ const branch = evidenceBranch(input.workBranch);
1218
+ let scratch = null;
1219
+ try {
1220
+ assertSafeRef(branch, "Evidence branch");
1221
+ scratch = await mkdtemp(join4(tmpdir(), "dt-evidence-"));
1222
+ const index = join4(scratch, "index");
1223
+ const ref = `refs/heads/${branch}`;
1224
+ const build = async () => {
1225
+ await gitOk2(input.repoDir, ["fetch", "--quiet", "origin", `+${ref}:${ref}`]);
1226
+ const parent = await revParse(input.repoDir, ref);
1227
+ const run = (args) => gitWithIndex(input.repoDir, index, args);
1228
+ await run(parent ? ["read-tree", parent] : ["read-tree", "--empty"]);
1229
+ for (const f of files) {
1230
+ const blob = await git(input.repoDir, ["hash-object", "-w", "--", join4(dir, f.name)]);
1231
+ await run(["update-index", "--add", "--cacheinfo", `100644,${blob},${f.path}`]);
1232
+ }
1233
+ const tree = await run(["write-tree"]);
1234
+ const parentTree = parent ? await git(input.repoDir, ["rev-parse", `${parent}^{tree}`]) : null;
1235
+ if (parent && tree === parentTree) return parent;
1236
+ const made = await git(input.repoDir, [
1237
+ ...await identity(input.repoDir),
1238
+ "commit-tree",
1239
+ tree,
1240
+ ...parent ? ["-p", parent] : [],
1241
+ "-m",
1242
+ `Screenshots for ${input.workBranch}
1243
+
1244
+ Published by dt-runner for the pull request's review; not part of the change.`
1245
+ ]);
1246
+ await git(input.repoDir, ["update-ref", ref, made]);
1247
+ return made;
1248
+ };
1249
+ let commit = await build();
1250
+ try {
1251
+ await git(input.repoDir, ["push", "--quiet", "origin", `${commit}:${ref}`]);
1252
+ } catch {
1253
+ commit = await build();
1254
+ await git(input.repoDir, ["push", "--quiet", "origin", `${commit}:${ref}`]);
1255
+ }
1256
+ await mkdir4(join4(dir, PUBLISHED_DIR), { recursive: true });
1257
+ for (const f of files) {
1258
+ await rename2(join4(dir, f.name), join4(dir, PUBLISHED_DIR, f.name)).catch(() => void 0);
1259
+ }
1260
+ return {
1261
+ images: files.map((f) => ({
1262
+ path: f.path,
1263
+ caption: captionFor(f.name),
1264
+ url: rawFileUrl(input.repo, commit, f.path)
1265
+ })),
1266
+ skipped,
1267
+ error: null
1268
+ };
1269
+ } catch (err) {
1270
+ const why = err instanceof GitError || err instanceof Error ? err.message : String(err);
1271
+ return { images: [], skipped, error: `Publishing the screenshots failed: ${why}` };
1272
+ } finally {
1273
+ if (scratch) await rm3(scratch, { recursive: true, force: true }).catch(() => void 0);
1274
+ }
1275
+ }
1276
+ function evidenceMarkdown(result) {
1277
+ if (!result.images.length) return "";
1278
+ return ["## Screenshots", "", ...result.images.map((i) => `![${i.caption}](${i.url})`)].join(
1279
+ "\n"
1280
+ );
1281
+ }
1282
+ function rawFileUrl(repo, commit, path) {
1283
+ const segments = path.split("/").map(encodeURIComponent).join("/");
1284
+ return `https://${repo.host}/${repo.owner}/${repo.repo}/raw/${commit}/${segments}`;
1285
+ }
1286
+ async function waitingImages(dir) {
1287
+ let entries;
1288
+ try {
1289
+ entries = await readdir(dir, { withFileTypes: true });
1290
+ } catch {
1291
+ return [];
1292
+ }
1293
+ const out = [];
1294
+ for (const e of entries) {
1295
+ if (!e.isFile()) continue;
1296
+ const ext = e.name.split(".").pop()?.toLowerCase() ?? "";
1297
+ if (!e.name.includes(".") || !IMAGE_EXTENSIONS.has(ext)) continue;
1298
+ const { size } = await stat2(join4(dir, e.name));
1299
+ out.push({ name: e.name, path: safeName(e.name), size });
1300
+ }
1301
+ out.sort((a, b) => a.name.localeCompare(b.name));
1302
+ const taken = /* @__PURE__ */ new Set();
1303
+ for (const f of out) {
1304
+ let path = f.path;
1305
+ for (let n = 2; taken.has(path.toLowerCase()); n++) {
1306
+ path = f.path.replace(/(\.[^.]+)?$/, (ext) => `-${n}${ext}`);
1307
+ }
1308
+ taken.add(path.toLowerCase());
1309
+ f.path = path;
1310
+ }
1311
+ return out;
1312
+ }
1313
+ function safeName(name) {
1314
+ const cleaned = name.replace(/[^\w.-]+/g, "-").replace(/^[.-]+/, "");
1315
+ return cleaned || "screenshot.png";
1316
+ }
1317
+ function captionFor(name) {
1318
+ return name.replace(/\.[^.]+$/, "").replace(/[-_]+/g, " ").replace(/[[\]]/g, "").trim();
1319
+ }
1320
+ async function gitOk2(cwd, args) {
1321
+ const res = await exec("git", args, { cwd, env: gitEnv(), timeoutMs: 5 * 6e4 });
1322
+ return res.code === 0;
1323
+ }
1324
+ async function revParse(cwd, ref) {
1325
+ const res = await exec("git", ["rev-parse", "--verify", "-q", `${ref}^{commit}`], {
1326
+ cwd,
1327
+ env: gitEnv(),
1328
+ timeoutMs: 6e4
1329
+ });
1330
+ return res.code === 0 ? res.stdout.trim() : null;
1331
+ }
1332
+ async function gitWithIndex(cwd, index, args) {
1333
+ const res = await exec("git", args, {
1334
+ cwd,
1335
+ env: { ...gitEnv(), GIT_INDEX_FILE: index },
1336
+ timeoutMs: 6e4
1337
+ });
1338
+ if (res.code !== 0) throw new GitError(args, res);
1339
+ return res.stdout.trim();
1340
+ }
1341
+ async function identity(cwd) {
1342
+ const res = await exec("git", ["config", "user.email"], {
1343
+ cwd,
1344
+ env: gitEnv(),
1345
+ timeoutMs: 6e4
1346
+ });
1347
+ return res.code === 0 && res.stdout.trim() ? [] : ["-c", "user.name=Discovery Tree runner", "-c", "user.email=dt-runner@users.noreply.local"];
1348
+ }
1349
+
1138
1350
  // src/session-store.ts
1139
- import { mkdir as mkdir4, readdir, rm as rm3 } from "node:fs/promises";
1140
- import { join as join4 } from "node:path";
1351
+ import { mkdir as mkdir5, readdir as readdir2, rm as rm4 } from "node:fs/promises";
1352
+ import { join as join5 } from "node:path";
1141
1353
  var HANDLED_COMMAND_IDS_KEPT = 100;
1142
1354
  var SessionStore = class {
1143
1355
  constructor(stateDir) {
1144
1356
  this.stateDir = stateDir;
1145
1357
  }
1146
1358
  dir(sessionId) {
1147
- return join4(this.stateDir, "sessions", sessionId);
1359
+ return join5(this.stateDir, "sessions", sessionId);
1148
1360
  }
1149
1361
  outboxFile(sessionId) {
1150
- return join4(this.dir(sessionId), "outbox.json");
1362
+ return join5(this.dir(sessionId), "outbox.json");
1151
1363
  }
1152
1364
  async save(record) {
1153
1365
  record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1154
- await writeJsonAtomic(join4(this.dir(record.sessionId), "session.json"), record);
1366
+ await writeJsonAtomic(join5(this.dir(record.sessionId), "session.json"), record);
1155
1367
  }
1156
1368
  async list() {
1157
- const root = join4(this.stateDir, "sessions");
1158
- await mkdir4(root, { recursive: true });
1369
+ const root = join5(this.stateDir, "sessions");
1370
+ await mkdir5(root, { recursive: true });
1159
1371
  const out = [];
1160
- for (const entry of await readdir(root, { withFileTypes: true })) {
1372
+ for (const entry of await readdir2(root, { withFileTypes: true })) {
1161
1373
  if (!entry.isDirectory()) continue;
1162
- const rec = await readJson(join4(root, entry.name, "session.json"));
1374
+ const rec = await readJson(join5(root, entry.name, "session.json"));
1163
1375
  if (rec?.sessionId === entry.name) out.push(rec);
1164
1376
  }
1165
1377
  return out;
1166
1378
  }
1167
1379
  async remove(sessionId) {
1168
- await rm3(this.dir(sessionId), { recursive: true, force: true });
1380
+ await rm4(this.dir(sessionId), { recursive: true, force: true });
1169
1381
  }
1170
1382
  /** Scratch working directory for a session without a repository. */
1171
1383
  scratchDir(sessionId) {
1172
- return join4(this.stateDir, "scratch", sessionId);
1384
+ return join5(this.stateDir, "scratch", sessionId);
1173
1385
  }
1174
1386
  };
1175
1387
  function assertSafeSessionId(id) {
@@ -1560,6 +1772,7 @@ ${text}`;
1560
1772
  async ensureProcess() {
1561
1773
  while (this.child && this.stopping) await this.waitForExit();
1562
1774
  if (this.child) return;
1775
+ await this.prepareEvidenceDir();
1563
1776
  const { bin, features } = await this.deps.claude();
1564
1777
  const args = claudeArgs({
1565
1778
  permissionMode: this.deps.permissionMode,
@@ -1694,13 +1907,20 @@ ${text}`;
1694
1907
  });
1695
1908
  }
1696
1909
  const push = await this.pushWork();
1910
+ const screenshots = push.failed ? "" : await this.publishScreenshots().catch((err) => {
1911
+ this.deps.logger.warn(`session ${this.sessionId}: publishing screenshots failed`, {
1912
+ error: scrubSecrets(err instanceof Error ? err.message : String(err))
1913
+ });
1914
+ return "";
1915
+ });
1697
1916
  this.record.turnActive = false;
1698
1917
  await this.deps.store.save(this.record);
1699
1918
  const failed = turnFailed || push.failed;
1919
+ const text = interrupted ? turn.isError ? null : turn.text : turn.text;
1700
1920
  this.emit({
1701
1921
  type: "result",
1702
1922
  status: failed ? "failed" : "idle",
1703
- text: interrupted ? turn.isError ? null : turn.text : turn.text,
1923
+ text: withScreenshots(text, screenshots),
1704
1924
  branch: push.branch,
1705
1925
  // The turn's work is only on this computer (committing or pushing it failed): a
1706
1926
  // continuation of the run must come back to this runner to find it.
@@ -1715,6 +1935,48 @@ ${text}`;
1715
1935
  { pushed: push.branch ?? void 0 }
1716
1936
  );
1717
1937
  }
1938
+ /** The screenshot folder exists and is kept out of git before the agent can use it. */
1939
+ async prepareEvidenceDir() {
1940
+ if (!this.record.workBranch || !this.record.repoDir) return;
1941
+ try {
1942
+ await ensureEvidenceDir(this.record.cwd);
1943
+ } catch (err) {
1944
+ this.deps.logger.warn(`session ${this.sessionId}: could not prepare the screenshot folder`, {
1945
+ error: scrubSecrets(err instanceof Error ? err.message : String(err))
1946
+ });
1947
+ }
1948
+ }
1949
+ /** Publishes the turn's screenshots; their markdown, or '' when there were none. */
1950
+ async publishScreenshots() {
1951
+ const { workBranch, repoDir, cwd, repository } = this.record;
1952
+ const repo = parseRepoUrl(
1953
+ repository ?? (repoDir ? `https://github.com/${basename(dirname4(repoDir))}/${basename(repoDir)}` : "")
1954
+ );
1955
+ if (!workBranch || !repoDir || !repo) return "";
1956
+ const res = await publishEvidence({ repoDir, worktree: cwd, workBranch, repo });
1957
+ if (res.skipped.length) {
1958
+ this.emit({
1959
+ type: "error",
1960
+ message: `Screenshots not published (over 8 MB each, or past the first ${MAX_EVIDENCE_IMAGES}): ${res.skipped.join(", ").slice(0, 300)}`,
1961
+ retryable: false
1962
+ });
1963
+ }
1964
+ if (res.error) {
1965
+ this.deps.logger.warn(`session ${this.sessionId}: ${res.error}`);
1966
+ this.emit({
1967
+ type: "error",
1968
+ message: `${res.error} They are still in ${EVIDENCE_DIR}/ for the next turn.`,
1969
+ retryable: false
1970
+ });
1971
+ return "";
1972
+ }
1973
+ if (res.images.length) {
1974
+ this.deps.logger.info(
1975
+ `session ${this.sessionId}: published ${res.images.length} screenshot(s) to ${evidenceBranch(workBranch)}`
1976
+ );
1977
+ }
1978
+ return evidenceMarkdown(res);
1979
+ }
1718
1980
  /**
1719
1981
  * Commits leftovers, then pushes. `branch` is the work branch when it was pushed; `failed`
1720
1982
  * when committing or pushing failed (reported as an error saying where the work is kept).
@@ -1722,11 +1984,14 @@ ${text}`;
1722
1984
  async pushWork() {
1723
1985
  const { workBranch, baseSha, cwd, repoDir } = this.record;
1724
1986
  if (!workBranch || !baseSha) return { branch: null, failed: false };
1987
+ await this.prepareEvidenceDir();
1725
1988
  const res = await commitAndPush({
1726
1989
  worktree: cwd,
1727
1990
  workBranch,
1728
1991
  baseSha,
1729
- message: "Uncommitted changes from the agent\u2019s turn\n\nCommitted by dt-runner at the end of a Discovery Tree agent turn."
1992
+ message: "Uncommitted changes from the agent\u2019s turn\n\nCommitted by dt-runner at the end of a Discovery Tree agent turn.",
1993
+ // Also when the folder could not be listed in `info/exclude`.
1994
+ exclude: [EVIDENCE_DIR]
1730
1995
  });
1731
1996
  const uncommitted = res.failedAt === "commit";
1732
1997
  if (!!this.record.keepWorktree !== uncommitted) {
@@ -1843,6 +2108,16 @@ function startupHint(stderr) {
1843
2108
  function delay(ms) {
1844
2109
  return new Promise((r) => setTimeout(r, ms));
1845
2110
  }
2111
+ function withScreenshots(text, screenshots) {
2112
+ if (!screenshots) return text;
2113
+ if (!text) return screenshots;
2114
+ const room = SCREENSHOTS_TEXT_BUDGET - screenshots.length - 4;
2115
+ const body = text.length > room ? `${text.slice(0, Math.max(0, room - 1))}\u2026` : text;
2116
+ return `${body}
2117
+
2118
+ ${screenshots}`;
2119
+ }
2120
+ var SCREENSHOTS_TEXT_BUDGET = 59e3;
1846
2121
 
1847
2122
  // src/session-manager.ts
1848
2123
  var SessionManager = class {
@@ -2010,6 +2285,7 @@ var SessionManager = class {
2010
2285
  Object.assign(record, {
2011
2286
  cwd: wt.worktree,
2012
2287
  repoDir: wt.repoDir,
2288
+ repository: cmd.repository.url,
2013
2289
  workBranch: cmd.repository.workBranch,
2014
2290
  baseRef: wt.baseRef,
2015
2291
  baseSha: wt.baseSha,
@@ -2026,7 +2302,7 @@ var SessionManager = class {
2026
2302
  record.cwd = this.store.scratchDir(
2027
2303
  resume ? safeWorktreeKey(resume.worktreeKey, cmd.sessionId) : cmd.sessionId
2028
2304
  );
2029
- await mkdir5(record.cwd, { recursive: true });
2305
+ await mkdir6(record.cwd, { recursive: true });
2030
2306
  }
2031
2307
  if (resume) {
2032
2308
  record.claudeSessionId = resume.claudeSessionId?.trim() || null;
@@ -2129,7 +2405,7 @@ var SessionManager = class {
2129
2405
  })
2130
2406
  );
2131
2407
  } else if (record.cwd) {
2132
- await rm4(record.cwd, { recursive: true, force: true }).catch(() => void 0);
2408
+ await rm5(record.cwd, { recursive: true, force: true }).catch(() => void 0);
2133
2409
  }
2134
2410
  await session.outbox.settled();
2135
2411
  await this.store.remove(sessionId);
@@ -2485,6 +2761,20 @@ async function runDoctor(env = process.env) {
2485
2761
  } catch {
2486
2762
  checks.push({ name: "git", level: "fail", detail: "git is not installed (or not on PATH)" });
2487
2763
  }
2764
+ try {
2765
+ const res = await exec("gh", ["auth", "status"], { timeoutMs: 1e4 });
2766
+ checks.push({
2767
+ name: "GitHub CLI",
2768
+ level: res.code === 0 ? "ok" : "warn",
2769
+ detail: res.code === 0 ? "signed in: the agent can read its pull request, checks and runs" : "not signed in: run `gh auth login` so the agent can read its pull request"
2770
+ });
2771
+ } catch {
2772
+ checks.push({
2773
+ name: "GitHub CLI",
2774
+ level: "warn",
2775
+ detail: "not installed (no `gh` on PATH): the agent cannot read its pull request; see https://cli.github.com"
2776
+ });
2777
+ }
2488
2778
  const bin = await findClaude(env);
2489
2779
  if (!bin) {
2490
2780
  checks.push({
@@ -2533,10 +2823,10 @@ function formatChecks(checks) {
2533
2823
  }
2534
2824
 
2535
2825
  // src/lock.ts
2536
- import { mkdir as mkdir6, open, readFile as readFile3, rm as rm5 } from "node:fs/promises";
2537
- import { join as join5 } from "node:path";
2826
+ import { mkdir as mkdir7, open, readFile as readFile4, rm as rm6 } from "node:fs/promises";
2827
+ import { join as join6 } from "node:path";
2538
2828
  function lockFile(stateDir) {
2539
- return join5(stateDir, "daemon.pid");
2829
+ return join6(stateDir, "daemon.pid");
2540
2830
  }
2541
2831
  function pidAlive(pid) {
2542
2832
  if (!Number.isInteger(pid) || pid <= 0) return false;
@@ -2550,7 +2840,7 @@ function pidAlive(pid) {
2550
2840
  async function lockHolder(stateDir) {
2551
2841
  let raw;
2552
2842
  try {
2553
- raw = await readFile3(lockFile(stateDir), "utf8");
2843
+ raw = await readFile4(lockFile(stateDir), "utf8");
2554
2844
  } catch {
2555
2845
  return null;
2556
2846
  }
@@ -2558,7 +2848,7 @@ async function lockHolder(stateDir) {
2558
2848
  return pidAlive(pid) && pid !== process.pid ? pid : null;
2559
2849
  }
2560
2850
  async function acquireDaemonLock(stateDir, pid = process.pid) {
2561
- await mkdir6(stateDir, { recursive: true, mode: 448 });
2851
+ await mkdir7(stateDir, { recursive: true, mode: 448 });
2562
2852
  const file = lockFile(stateDir);
2563
2853
  for (let attempt = 0; attempt < 3; attempt++) {
2564
2854
  try {
@@ -2574,19 +2864,19 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
2574
2864
  lock: {
2575
2865
  file,
2576
2866
  async release() {
2577
- const current = await readFile3(file, "utf8").catch(() => "");
2578
- if (Number.parseInt(current.trim(), 10) === pid) await rm5(file, { force: true });
2867
+ const current = await readFile4(file, "utf8").catch(() => "");
2868
+ if (Number.parseInt(current.trim(), 10) === pid) await rm6(file, { force: true });
2579
2869
  }
2580
2870
  }
2581
2871
  };
2582
2872
  } catch (err) {
2583
2873
  if (err.code !== "EEXIST") throw err;
2584
2874
  }
2585
- const raw = await readFile3(file, "utf8").catch(() => null);
2875
+ const raw = await readFile4(file, "utf8").catch(() => null);
2586
2876
  if (raw === null) continue;
2587
2877
  const holder = Number.parseInt(raw.trim(), 10);
2588
2878
  if (pidAlive(holder) && holder !== pid) return { ok: false, pid: holder };
2589
- await rm5(file, { force: true });
2879
+ await rm6(file, { force: true });
2590
2880
  }
2591
2881
  return { ok: false, pid: null };
2592
2882
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@discovery-tree/runner",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "dt-runner: run Discovery Tree agent sessions on your own computer with your own signed-in Claude Code",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {