my-durable 0.0.76 → 0.0.77

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.
@@ -24,7 +24,20 @@
24
24
  *
25
25
  * No express, no Store import: the leader wires routes and store calls.
26
26
  */
27
- import { chmodSync, lstatSync, readFileSync, readdirSync, statSync, writeFileSync, type Dirent } from "node:fs";
27
+ import {
28
+ chmodSync,
29
+ closeSync,
30
+ constants as fsConstants,
31
+ fstatSync,
32
+ lstatSync,
33
+ openSync,
34
+ readFileSync,
35
+ readSync,
36
+ readdirSync,
37
+ statSync,
38
+ writeFileSync,
39
+ type Dirent,
40
+ } from "node:fs";
28
41
  import { mkdir, rename, stat } from "node:fs/promises";
29
42
  import { basename, join } from "node:path";
30
43
  import { DatabaseSync } from "node:sqlite";
@@ -107,12 +120,29 @@ export function readArchiveManifest(bundleDir: string): ArchiveManifest | undefi
107
120
  // bytes; a planted one had NO ceiling — restore and the archive LISTING
108
121
  // read the whole file into RAM per cheap request (leader probe: a 150 MB
109
122
  // plant cost ~770 ms and ~600 MB RSS per refused restore, repeatable).
110
- // Refuse oversized manifests without reading them.
111
- if (statSync(manifestPath).size > 1024 * 1024) return undefined;
112
- const text = readFileSync(manifestPath, "utf8");
113
- // R20 cold-1 M5: a same-user planter can swap the file between stat and
114
- // read — the cap is enforced on the BYTES WE ACTUALLY READ, not the stat.
115
- if (text.length > 1024 * 1024) return undefined;
123
+ // run-7 D6 (leader-probed): the path-based stat+read was defeated by
124
+ // non-regular files — a FIFO (stat size 0) BLOCKED the synchronous read
125
+ // forever (whole-device freeze), a /dev/zero symlink read unbounded, and
126
+ // a swap race re-opened a different file. The cap is now DESCRIPTOR-
127
+ // pinned: O_NOFOLLOW refuses symlinks, O_NONBLOCK makes a FIFO open
128
+ // return instead of block, fstat-on-fd rejects non-regular files, and we
129
+ // read at most size+1 bytes FROM THE FD (the pinned inode cannot be
130
+ // swapped out from under us).
131
+ const fd = openSync(manifestPath, fsConstants.O_RDONLY | fsConstants.O_NONBLOCK | fsConstants.O_NOFOLLOW);
132
+ try {
133
+ const st = fstatSync(fd);
134
+ if (!st.isFile() || st.size > 1024 * 1024) return undefined;
135
+ const buf = Buffer.alloc(st.size + 1); // +1: detect growth between fstat and read
136
+ let read = 0;
137
+ while (read < buf.length) {
138
+ const n = readSync(fd, buf, read, buf.length - read, read);
139
+ if (n === 0) break;
140
+ read += n;
141
+ }
142
+ if (read > 1024 * 1024) return undefined;
143
+ const text = buf.subarray(0, read).toString("utf8");
144
+ // R20 cold-1 M5 kept: the cap is enforced on the BYTES WE ACTUALLY READ.
145
+ if (text.length > 1024 * 1024) return undefined;
116
146
  const parsed: unknown = JSON.parse(text);
117
147
  if (typeof parsed !== "object" || parsed === null) return undefined;
118
148
  const m = parsed as Record<string, unknown>;
@@ -138,6 +168,9 @@ export function readArchiveManifest(bundleDir: string): ArchiveManifest | undefi
138
168
  archivedAt: m.archivedAt,
139
169
  packageVersion: m.packageVersion,
140
170
  };
171
+ } finally {
172
+ closeSync(fd);
173
+ }
141
174
  } catch {
142
175
  return undefined;
143
176
  }
@@ -161,7 +194,13 @@ function parseRecord(record: unknown): Record<string, unknown> | undefined {
161
194
  function bundleStats(bundleDir: string): { turns: number; lastMessageAt: number | null } {
162
195
  let db: DatabaseSync | undefined;
163
196
  try {
164
- db = new DatabaseSync(join(bundleDir, DB_NAME), { readOnly: true });
197
+ // run-7 D6 (uncovered sibling, same root cause): a planted non-regular
198
+ // agent.sqlite (FIFO / /dev/zero symlink) blocks open(2) synchronously
199
+ // exactly like the manifest read did — only regular files may open.
200
+ const dbPath = join(bundleDir, DB_NAME);
201
+ const dbStat = lstatSync(dbPath);
202
+ if (!dbStat.isFile()) throw new Error("not a regular bundle database");
203
+ db = new DatabaseSync(dbPath, { readOnly: true });
165
204
  // R20 cold-1 M5: this used to materialize EVERY entries row into RAM and
166
205
  // JSON.parse each one per LISTING request — a planted multi-GB bundle was
167
206
  // a repeatable per-request stall (the manifest-cap class). Aggregates run
@@ -297,7 +336,13 @@ export function archivedTranscript(bundleDir: string, format: "markdown" | "json
297
336
  const entries: WireEntry[] = [];
298
337
  let truncated = 0;
299
338
  try {
300
- db = new DatabaseSync(join(bundleDir, DB_NAME), { readOnly: true });
339
+ // run-7 D6 (uncovered sibling, same root cause): a planted non-regular
340
+ // agent.sqlite (FIFO / /dev/zero symlink) blocks open(2) synchronously
341
+ // exactly like the manifest read did — only regular files may open.
342
+ const dbPath = join(bundleDir, DB_NAME);
343
+ const dbStat = lstatSync(dbPath);
344
+ if (!dbStat.isFile()) throw new Error("not a regular bundle database");
345
+ db = new DatabaseSync(dbPath, { readOnly: true });
301
346
  // R20 cold-1 M5: the transcript view read the WHOLE entries table per
302
347
  // request — same planted-bundle amplification. A hard entry cap keeps the
303
348
  // newest turns (the ORDER BY is commit order; truncating from the front
@@ -80,18 +80,26 @@ const childEnv = (): NodeJS.ProcessEnv => {
80
80
  const allow = process.platform === "win32" ? WIN32_CHILD_ENV_ALLOWLIST : CHILD_ENV_ALLOWLIST;
81
81
  return Object.fromEntries(allow.flatMap((k) => (process.env[k] ? [[k, process.env[k]]] : [])));
82
82
  }
83
- export const GIT_EXEC_OPTS = (timeout: number) => ({
83
+ export interface RepoPin {
84
+ gitDir: string;
85
+ workTree: string;
86
+ }
87
+ /** run-7 cold-1 M3: pin the repo per request — GIT_DIR/GIT_WORK_TREE stop
88
+ * every spawn re-running .git discovery, so an in-sandbox racer flipping the
89
+ * .git file (gitdir redirect / core.worktree) between the guard's resolves
90
+ * and the data spawns cannot redirect the operation. */
91
+ export const GIT_EXEC_OPTS = (timeout: number, pin?: RepoPin) => ({
84
92
  timeout,
85
93
  maxBuffer: 8 * 1024 * 1024,
86
94
  windowsHide: true,
87
- env: childEnv(),
95
+ env: { ...childEnv(), ...(pin ? { GIT_DIR: pin.gitDir, GIT_WORK_TREE: pin.workTree } : {}) } as ReturnType<typeof childEnv>,
88
96
  });
89
- export const GH_EXEC_OPTS = (cwd: string, timeout: number) => ({
97
+ export const GH_EXEC_OPTS = (cwd: string, timeout: number, pin?: RepoPin) => ({
90
98
  cwd,
91
99
  timeout,
92
100
  maxBuffer: 4 * 1024 * 1024,
93
101
  windowsHide: true,
94
- env: childEnv(),
102
+ env: { ...childEnv(), ...(pin ? { GIT_DIR: pin.gitDir, GIT_WORK_TREE: pin.workTree } : {}) } as ReturnType<typeof childEnv>,
95
103
  });
96
104
 
97
105
  /** Test seam for counting/driving spawns: `node:child_process`'s ESM namespace
@@ -112,10 +120,10 @@ export function isNotARepoError(e: unknown): boolean {
112
120
  }
113
121
 
114
122
  /** One git call; rejects on non-zero exit with stderr in the message. */
115
- export function git(cwd: string, args: string[], timeout = GIT_TIMEOUT): Promise<string> {
123
+ export function git(cwd: string, args: string[], timeout = GIT_TIMEOUT, pin?: RepoPin): Promise<string> {
116
124
  return new Promise((ok, fail) => {
117
125
  // `-C` is ARGV, so the path goes out forward-slashed (see gitPath).
118
- execFileImpl("git", ["-C", gitPath(cwd), ...args], GIT_EXEC_OPTS(timeout), (error, stdout, stderr) => {
126
+ execFileImpl("git", ["-C", gitPath(cwd), ...args], GIT_EXEC_OPTS(timeout, pin), (error, stdout, stderr) => {
119
127
  if (error) fail(Error(String(stderr || stdout || error.message).trim().slice(0, 400)));
120
128
  // git chats on stderr for worktree add/switch/fetch — keep both.
121
129
  else ok(`${String(stdout)}${String(stdout) && String(stderr) ? "\n" : ""}${String(stderr)}`);
@@ -126,11 +134,11 @@ export function git(cwd: string, args: string[], timeout = GIT_TIMEOUT): Promise
126
134
  /** One GitHub CLI call — PRs, checks and comments are forge territory and gh
127
135
  * is the least-token-ceremony way to reach them from a device. Same no-shell
128
136
  * rule: argv only, plain text back. */
129
- export function gh(cwd: string, args: string[], timeout = GIT_TIMEOUT): Promise<string> {
137
+ export function gh(cwd: string, args: string[], timeout = GIT_TIMEOUT, pin?: RepoPin): Promise<string> {
130
138
  return new Promise((ok, fail) => {
131
139
  // gh resolves the repo from cwd (a --repo flag wants a slug, not a path).
132
140
  // cwd is a Node spawn option, not argv — Node handles Windows paths here.
133
- execFileImpl("gh", args, GH_EXEC_OPTS(cwd, timeout), (error, stdout, stderr) => {
141
+ execFileImpl("gh", args, GH_EXEC_OPTS(cwd, timeout, pin), (error, stdout, stderr) => {
134
142
  if (error) fail(Error(String(stderr || stdout || error.message).trim().slice(0, 400)));
135
143
  else ok(String(stdout));
136
144
  });
@@ -269,6 +277,41 @@ function ensureWatcher(root: string) {
269
277
  watchers.set(root, entry);
270
278
  }
271
279
 
280
+ /** R23 rule: confinement scopes the DEVICE REST surface only — git
281
+ * discovery must not WALK UP to an enclosing repo whose toplevel sits
282
+ * outside the start dirs (a remote viewer would read a repo the device
283
+ * never served). The absolute git dir is NOT confined: redirects and linked
284
+ * worktrees whose gitdir lives elsewhere are operator territory and are
285
+ * followed via the returned pin (the agent itself is unsandboxed by design). */
286
+ export async function resolveRepoPin(path: string): Promise<RepoPin | undefined> {
287
+ if (!repoRootAllowed) return undefined;
288
+ const [topLevel, gitDir] = await Promise.all([
289
+ git(path, ["rev-parse", "--show-toplevel"]),
290
+ git(path, ["rev-parse", "--absolute-git-dir"]),
291
+ ]);
292
+ const pin: RepoPin = { gitDir: gitDir.trim(), workTree: topLevel.trim() };
293
+ // R23 (operator decision): durable-pi WRAPS pi/pi-durable — the agent is
294
+ // unsandboxed by design (full user shell/fs), so the gitdir-redirect class
295
+ // is not an escalation for it, and refusing gitdirs outside the start dirs
296
+ // broke legitimate linked worktrees. Confinement now scopes only the DEVICE
297
+ // REST surface: the walk-up case (git DISCOVERY adopts a toplevel outside
298
+ // the start dirs) — a viewer must not read a repo the device never served.
299
+ if (!(await repoRootAllowed(pin.workTree))) throw Error("repo root lives outside the start dirs");
300
+ return pin;
301
+ }
302
+
303
+ // R21/run-7 D1: git's repo discovery WALKS UP from the contained request path —
304
+ // a start dir that is a slice of a bigger repo (monorepo, worktree-heavy
305
+ // checkout) made git adopt an OUT-of-sandbox repo root, disclosing repo-wide
306
+ // files/branches/worktrees/remoteUrl and (op "ignore") even WRITING .gitignore
307
+ // outside the start dirs. The store installs this guard; git.ts itself never
308
+ // learns the roots.
309
+ type RepoRootGuard = (root: string) => Promise<boolean>;
310
+ let repoRootAllowed: RepoRootGuard | undefined;
311
+ export function configureGitRootGuard(fn: RepoRootGuard | undefined) {
312
+ repoRootAllowed = fn;
313
+ }
314
+
272
315
  /** Test hook: the TTL cache would serve a pre-mutation answer. */
273
316
  export function clearGitStatusCache() {
274
317
  statusCache.clear();
@@ -301,25 +344,43 @@ async function statusOnce(path: string, key: string): Promise<GitStatus> {
301
344
  // Reach git at all before trusting any "empty" answer: git missing from
302
345
  // the daemon's PATH (seen on a Windows Startup-launched device) must NOT
303
346
  // read as "not a repository" under a real repo.
304
- const root = (await git(path, ["rev-parse", "--show-toplevel"])).trim();
347
+ // The discovered root is an ATTACKER-REACHABLE fact (any contained
348
+ // subdirectory of a repo reaches it): clamp before anything repo-wide
349
+ // runs — a REMOTE VIEWER must not read a repo the device never served.
350
+ // R23: toplevel-only (the gitdir condition broke linked worktrees and
351
+ // treated the unsandboxed local agent as a racer — see resolveRepoPin).
352
+ // The pin rides GIT_DIR/GIT_WORK_TREE into every later spawn regardless.
353
+ let pin: RepoPin | undefined;
354
+ try {
355
+ pin = await resolveRepoPin(path);
356
+ } catch (e) {
357
+ if (!String((e as Error).message).includes("start dirs")) throw e;
358
+ out.repo = true; // repo presence only — no root, files, branches,
359
+ // worktrees, remoteUrl, subject, identity; no watcher on foreign ground.
360
+ statusCache.set(key, { at: Date.now(), s: out });
361
+ statusFailCache.delete(key);
362
+ return out;
363
+ }
364
+ const g = (args: string[], t?: number) => git(path, args, t, pin);
365
+ const root = pin?.workTree ?? (await git(path, ["rev-parse", "--show-toplevel"])).trim();
305
366
  out.repo = true;
306
367
  out.root = root;
307
368
  // Everything after toplevel runs in PARALLEL — status is the long pole
308
369
  // (20s+ on big Windows checkouts) and must not wait for four fast calls.
309
370
  const [branchP, headP, statusP, gitDirP, wlP, branchesP, numWorkP, numIdxP, mergeP, nameP, emailP, remoteP] = await Promise.allSettled([
310
- git(path, ["branch", "--show-current"]),
311
- git(path, ["log", "-1", "--pretty=%h%x09%s"]),
312
- git(path, ["--no-optional-locks", "status", "--porcelain=v1", "-b"], GIT_SLOW_TIMEOUT),
313
- git(path, ["rev-parse", "--git-dir"]),
314
- git(path, ["worktree", "list", "--porcelain"], GIT_SLOW_TIMEOUT),
315
- git(path, ["for-each-ref", "refs/heads", "--format=%(refname:short)%09%(upstream:short)%09%(if)%(HEAD)%(then)1%(else)0%(end)"]),
316
- git(path, ["--no-optional-locks", "diff", "--numstat", "--no-renames"], GIT_SLOW_TIMEOUT),
317
- git(path, ["--no-optional-locks", "diff", "--numstat", "--cached", "--no-renames"]),
371
+ g(["branch", "--show-current"]),
372
+ g(["log", "-1", "--pretty=%h%x09%s"]),
373
+ g(["--no-optional-locks", "status", "--porcelain=v1", "-b"], GIT_SLOW_TIMEOUT),
374
+ g(["rev-parse", "--git-dir"]),
375
+ g(["worktree", "list", "--porcelain"], GIT_SLOW_TIMEOUT),
376
+ g(["for-each-ref", "refs/heads", "--format=%(refname:short)%09%(upstream:short)%09%(if)%(HEAD)%(then)1%(else)0%(end)"]),
377
+ g(["--no-optional-locks", "diff", "--numstat", "--no-renames"], GIT_SLOW_TIMEOUT),
378
+ g(["--no-optional-locks", "diff", "--numstat", "--cached", "--no-renames"]),
318
379
  // MERGE_HEAD exists ⇔ a merge is waiting to be resolved.
319
- git(path, ["rev-parse", "-q", "--verify", "MERGE_HEAD"]),
320
- git(path, ["config", "user.name"]),
321
- git(path, ["config", "user.email"]),
322
- git(path, ["remote", "get-url", "origin"]),
380
+ g(["rev-parse", "-q", "--verify", "MERGE_HEAD"]),
381
+ g(["config", "user.name"]),
382
+ g(["config", "user.email"]),
383
+ g(["remote", "get-url", "origin"]),
323
384
  ]);
324
385
  const branch = branchP.status === "fulfilled" ? branchP.value : "";
325
386
  out.branch = branch.trim() || undefined;
@@ -513,16 +574,24 @@ export async function gitOp(
513
574
  prs?: { n: number; title: string; state: string; draft: boolean; branch: string; url: string }[];
514
575
  }> {
515
576
  const { ref, message, target, branch, files, create, staged, rebase, setUpstream, name, lines, method, body, n, side } = opts;
577
+ // R23: the TOPLEVEL must sit under the start dirs (gitdir redirects are
578
+ // operator territory — see resolveRepoPin); the resolved pin rides
579
+ // GIT_DIR/GIT_WORK_TREE into EVERY spawn below, so per-spawn .git discovery
580
+ // never re-runs and the check cannot be raced.
581
+ const pin = await resolveRepoPin(path);
582
+ const g = (args: string[], t?: number) => git(path, args, t, pin);
583
+ const ghP = (args: string[], t?: number) => gh(path, args, t, pin);
516
584
  switch (op) {
517
585
  case "diff":
518
- return { text: await git(path, ["--no-pager", "diff", ...(ref && safeRef(ref) ? [ref] : [])]) };
586
+ return { text: await g(["--no-pager", "diff", ...(ref && safeRef(ref) ? [ref] : [])]) };
519
587
  case "log":
520
- return { text: (await git(path, ["--no-pager", "log", "--oneline", "-n", "30", ...(ref && safeRef(ref) ? [ref] : [])])).trimEnd() };
588
+ return { text: (await g(["--no-pager", "log", "--oneline", "-n", "30", ...(ref && safeRef(ref) ? [ref] : [])])).trimEnd() };
521
589
  case "log-list": {
522
590
  // IntelliJ's log window: hash, refs, author, date, subject — structured.
523
591
  // %p = parents — the swimlane graph is computed from these on the UI.
524
- const raw = await git(
525
- path,
592
+ // run-7 cold-2 M1: pinned like every other spawn — the bare git() here
593
+ // re-ran .git discovery, reopening the TOCTOU M3 exists to close.
594
+ const raw = await g(
526
595
  ["--no-pager", "log", "-n", "50", "--date=short", "--pretty=format:%h%x1f%D%x1f%an%x1f%ad%x1f%s%x1f%p"],
527
596
  );
528
597
  return {
@@ -544,69 +613,69 @@ export async function gitOp(
544
613
  };
545
614
  }
546
615
  case "fetch":
547
- return { text: (await git(path, ["fetch", "--all", "--prune"])).trim() || "fetched" };
616
+ return { text: (await g(["fetch", "--all", "--prune"])).trim() || "fetched" };
548
617
  case "pull":
549
618
  // --ff-only stays the default; --rebase is an explicit opt-in the UI
550
619
  // offers only after a ff-only failure.
551
- return { text: (await git(path, ["pull", ...(rebase ? ["--rebase"] : ["--ff-only"])])).trim() || "up to date" };
620
+ return { text: (await g(["pull", ...(rebase ? ["--rebase"] : ["--ff-only"])])).trim() || "up to date" };
552
621
  case "branch":
553
- return { text: (await git(path, ["--no-pager", "branch", "-vv"])).trimEnd() };
622
+ return { text: (await g(["--no-pager", "branch", "-vv"])).trimEnd() };
554
623
  case "switch": {
555
624
  if (!ref || !safeRef(ref)) throw Error("switch needs a branch name (letters, digits, ./-_)");
556
625
  // create:true = git switch -c — IntelliJ's "new branch" action.
557
- return { text: (await git(path, ["switch", ...(create ? ["-c"] : []), ref])).trim() };
626
+ return { text: (await g(["switch", ...(create ? ["-c"] : []), ref])).trim() };
558
627
  }
559
628
  case "push": {
560
629
  if (setUpstream) {
561
630
  if (!ref || !safeRef(ref)) throw Error("push -u needs a branch name");
562
- return { text: (await git(path, ["push", "-u", "origin", ref], GIT_SLOW_TIMEOUT)).trim() || `pushed, upstream set to origin/${ref}` };
631
+ return { text: (await g(["push", "-u", "origin", ref], GIT_SLOW_TIMEOUT)).trim() || `pushed, upstream set to origin/${ref}` };
563
632
  }
564
- return { text: (await git(path, ["push"], GIT_SLOW_TIMEOUT)).trim() || "pushed (or nothing to push)" };
633
+ return { text: (await g(["push"], GIT_SLOW_TIMEOUT)).trim() || "pushed (or nothing to push)" };
565
634
  }
566
635
  case "stage": {
567
636
  if (!files?.length) throw Error("stage needs files");
568
- return { text: (await git(path, ["add", "--", ...gitPaths(files)])).trim() || `staged ${files.length} file(s)` };
637
+ return { text: (await g(["add", "--", ...gitPaths(files)])).trim() || `staged ${files.length} file(s)` };
569
638
  }
570
639
  case "discard": {
571
640
  // IntelliJ's Rollback: index AND worktree back to HEAD for these paths.
572
641
  if (!files?.length) throw Error("discard needs files");
573
- return { text: (await git(path, ["checkout", "HEAD", "--", ...gitPaths(files)])).trim() || `discarded ${files.length} file(s)` };
642
+ return { text: (await g(["checkout", "HEAD", "--", ...gitPaths(files)])).trim() || `discarded ${files.length} file(s)` };
574
643
  }
575
644
  case "diff-file": {
576
645
  if (!target) throw Error("diff-file needs a file path");
577
- return { text: (await git(path, ["--no-pager", "diff", ...(staged ? ["--cached"] : []), "HEAD", "--", gitPath(target)])).trim() || "no diff" };
646
+ return { text: (await g(["--no-pager", "diff", ...(staged ? ["--cached"] : []), "HEAD", "--", gitPath(target)])).trim() || "no diff" };
578
647
  }
579
648
  case "stash-push":
580
- return { text: (await git(path, ["stash", "push", ...(message ? ["-m", message] : [])])).trim() || "stashed" };
649
+ return { text: (await g(["stash", "push", ...(message ? ["-m", message] : [])])).trim() || "stashed" };
581
650
  case "stash-pop":
582
- return { text: (await git(path, ["stash", "pop"])).trim() || "stash popped" };
651
+ return { text: (await g(["stash", "pop"])).trim() || "stash popped" };
583
652
  case "unstage": {
584
653
  // IntelliJ's Unstage: index only, worktree keeps its changes.
585
654
  if (!files?.length) throw Error("unstage needs files");
586
655
  try {
587
- return { text: (await git(path, ["reset", "-q", "HEAD", "--", ...gitPaths(files)])).trim() || `unstaged ${files.length} file(s)` };
656
+ return { text: (await g(["reset", "-q", "HEAD", "--", ...gitPaths(files)])).trim() || `unstaged ${files.length} file(s)` };
588
657
  } catch {
589
658
  // unborn branch: HEAD does not resolve yet — reset against the empty tree.
590
- return { text: (await git(path, ["reset", "-q", "--", ...gitPaths(files)])).trim() || `unstaged ${files.length} file(s)` };
659
+ return { text: (await g(["reset", "-q", "--", ...gitPaths(files)])).trim() || `unstaged ${files.length} file(s)` };
591
660
  }
592
661
  }
593
662
  case "compare": {
594
663
  // ahead/behind vs ANY ref, not just the upstream (orca git-bridge).
595
664
  if (!ref || !safeRef(ref)) throw Error("compare needs a branch name");
596
- const raw = await git(path, ["rev-list", "--left-right", "--count", `${ref}...HEAD`]);
665
+ const raw = await g(["rev-list", "--left-right", "--count", `${ref}...HEAD`]);
597
666
  const [behind = "0", ahead = "0"] = raw.trim().split(/\s+/);
598
667
  return { text: `${Number(ahead)} ahead, ${Number(behind)} behind of ${ref}`, ahead: Number(ahead), behind: Number(behind) };
599
668
  }
600
669
  case "merge-abort":
601
670
  try {
602
- return { text: (await git(path, ["merge", "--abort"])).trim() || "merge aborted" };
671
+ return { text: (await g(["merge", "--abort"])).trim() || "merge aborted" };
603
672
  } catch {
604
- return { text: (await git(path, ["rebase", "--abort"])).trim() || "rebase aborted" };
673
+ return { text: (await g(["rebase", "--abort"])).trim() || "rebase aborted" };
605
674
  }
606
675
  case "show-files": {
607
676
  // What one commit touched — the log row expander.
608
677
  if (!target || !/^[0-9a-f]{4,40}$/.test(target)) throw Error("show-files needs a commit hash");
609
- const raw = await git(path, ["--no-pager", "show", "--name-status", "--pretty=format:", "--no-renames", "-m", "--first-parent", target]);
678
+ const raw = await g(["--no-pager", "show", "--name-status", "--pretty=format:", "--no-renames", "-m", "--first-parent", target]);
610
679
  return {
611
680
  text: "",
612
681
  changed: raw
@@ -625,7 +694,7 @@ export async function gitOp(
625
694
  if (!lines?.length) throw Error("ignore needs pattern lines");
626
695
  if (lines.length > 50) throw Error("ignore takes at most 50 lines");
627
696
  for (const l of lines) if (!l.trim() || l.length > 200 || /[\n\r\0]/.test(l)) throw Error("bad ignore pattern");
628
- const root = (await git(path, ["rev-parse", "--show-toplevel"])).trim();
697
+ const root = pin?.workTree ?? (await g(["rev-parse", "--show-toplevel"])).trim();
629
698
  await appendFile(join(root, ".gitignore"), `\n${lines.join("\n")}\n`, "utf8");
630
699
  return { text: `added to .gitignore: ${lines.join(", ")}` };
631
700
  }
@@ -633,11 +702,11 @@ export async function gitOp(
633
702
  // A named ref of HEAD — the rewind target. Never touches the worktree.
634
703
  if (!name || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name)) throw Error("checkpoint needs a name (letters, digits, ._-)");
635
704
  const refname = `refs/dpi/checkpoints/${name}`;
636
- await git(path, ["update-ref", refname, "HEAD"]);
705
+ await g(["update-ref", refname, "HEAD"]);
637
706
  return { text: `checkpoint ${name} saved` };
638
707
  }
639
708
  case "checkpoints": {
640
- const raw = await git(path, [
709
+ const raw = await g([
641
710
  "--no-pager", "for-each-ref", "refs/dpi/checkpoints",
642
711
  "--format=%(refname:strip=3)%09%(objectname:short)%09%(committerdate:short)%09%(contents:subject)",
643
712
  ]);
@@ -657,28 +726,28 @@ export async function gitOp(
657
726
  // reset --hard to one of OUR checkpoint refs only — never an arbitrary ref.
658
727
  if (!name || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name)) throw Error("rewind needs a checkpoint name");
659
728
  const refname = `refs/dpi/checkpoints/${name}`;
660
- const sha = (await git(path, ["rev-parse", "--verify", refname])).trim();
661
- return { text: (await git(path, ["reset", "--hard", sha])).trim().split("\n")[0] ?? `rewound to ${name}` };
729
+ const sha = (await g(["rev-parse", "--verify", refname])).trim();
730
+ return { text: (await g(["reset", "--hard", sha])).trim().split("\n")[0] ?? `rewound to ${name}` };
662
731
  }
663
732
  case "resolve": {
664
733
  // orca's conflicts section, one click: pick a side, stage the result.
665
734
  if (side !== "ours" && side !== "theirs") throw Error("resolve needs side=ours|theirs");
666
735
  if (!files?.length) throw Error("resolve needs files");
667
- await git(path, ["checkout", `--${side}`, "--", ...gitPaths(files)]);
668
- return { text: (await git(path, ["add", "--", ...gitPaths(files)])).trim() || `resolved ${files.length} file(s) with --${side}` };
736
+ await g(["checkout", `--${side}`, "--", ...gitPaths(files)]);
737
+ return { text: (await g(["add", "--", ...gitPaths(files)])).trim() || `resolved ${files.length} file(s) with --${side}` };
669
738
  }
670
739
  case "submodule-update":
671
- return { text: (await git(path, ["submodule", "update", "--init", "--recursive"], GIT_SLOW_TIMEOUT)).trim() || "submodules up to date" };
740
+ return { text: (await g(["submodule", "update", "--init", "--recursive"], GIT_SLOW_TIMEOUT)).trim() || "submodules up to date" };
672
741
  case "pr-create": {
673
742
  // gh pr create — title from message, head = current branch. gh owns auth.
674
743
  const title = (message ?? "").trim();
675
744
  if (!title) throw Error("pr-create needs a title (message)");
676
745
  const args = ["pr", "create", "--title", title.slice(0, 200), "--body", (body ?? title).slice(0, 4000)];
677
746
  if (ref && safeRef(ref)) args.push("--base", ref);
678
- return { text: (await gh(path, args, GIT_SLOW_TIMEOUT)).trim() };
747
+ return { text: (await ghP(args, GIT_SLOW_TIMEOUT)).trim() }; // run-7 cold-2 M2: pinned like its pr-* siblings
679
748
  }
680
749
  case "pr-list": {
681
- const raw = await gh(path, ["pr", "list", "--limit", "20", "--json", "number,title,state,isDraft,headRefName,url"]);
750
+ const raw = await ghP(["pr", "list", "--limit", "20", "--json", "number,title,state,isDraft,headRefName,url"]);
682
751
  const list = JSON.parse(raw || "[]") as { number: number; title: string; state: string; isDraft: boolean; headRefName: string; url: string }[];
683
752
  return {
684
753
  text: "",
@@ -687,17 +756,17 @@ export async function gitOp(
687
756
  }
688
757
  case "pr-merge": {
689
758
  if (!n || !Number.isInteger(n)) throw Error("pr-merge needs a PR number");
690
- return { text: (await gh(path, ["pr", "merge", String(n), method === "merge" ? "--merge" : "--squash"], GIT_SLOW_TIMEOUT)).trim() || `PR #${n} merged` };
759
+ return { text: (await ghP(["pr", "merge", String(n), method === "merge" ? "--merge" : "--squash"], GIT_SLOW_TIMEOUT)).trim() || `PR #${n} merged` };
691
760
  }
692
761
  case "pr-checks": {
693
762
  if (!n || !Number.isInteger(n)) throw Error("pr-checks needs a PR number");
694
- return { text: (await gh(path, ["pr", "checks", String(n)], GIT_SLOW_TIMEOUT)).trim() || "no checks reported" };
763
+ return { text: (await ghP(["pr", "checks", String(n)], GIT_SLOW_TIMEOUT)).trim() || "no checks reported" };
695
764
  }
696
765
  case "pr-comment": {
697
766
  if (!n || !Number.isInteger(n)) throw Error("pr-comment needs a PR number");
698
767
  const text = (body ?? "").trim();
699
768
  if (!text) throw Error("pr-comment needs a body");
700
- return { text: (await gh(path, ["pr", "comment", String(n), "--body", text.slice(0, 4000)])).trim() };
769
+ return { text: (await ghP(["pr", "comment", String(n), "--body", text.slice(0, 4000)])).trim() };
701
770
  }
702
771
  case "commit": {
703
772
  const msg = (message ?? "").trim();
@@ -705,26 +774,26 @@ export async function gitOp(
705
774
  // IntelliJ-style: chosen files only, when the caller picked some.
706
775
  if (files?.length) {
707
776
  for (const f of files) if (f.includes("\0") || f === "") throw Error("bad file path");
708
- return { text: (await git(path, ["commit", "-m", msg, "--", ...gitPaths(files)])).split("\n")[0]?.trim() ?? "committed" };
777
+ return { text: (await g(["commit", "-m", msg, "--", ...gitPaths(files)])).split("\n")[0]?.trim() ?? "committed" };
709
778
  }
710
- return { text: (await git(path, ["commit", "-am", msg])).split("\n")[0]?.trim() ?? "committed" };
779
+ return { text: (await g(["commit", "-am", msg])).split("\n")[0]?.trim() ?? "committed" };
711
780
  }
712
781
  case "worktree-list":
713
- return { text: (await git(path, ["--no-pager", "worktree", "list"])).trimEnd() };
782
+ return { text: (await g(["--no-pager", "worktree", "list"])).trimEnd() };
714
783
  case "worktree-add": {
715
784
  // branch = create a NEW branch for the worktree; ref = check out an
716
785
  // existing one. Both validated the same strict way — never a shell.
717
786
  if (!target || !isAbsolute(target)) throw Error("worktree-add needs an absolute target path");
718
787
  if (branch) {
719
788
  if (!safeRef(branch)) throw Error("worktree-add branch name is invalid (letters, digits, ./-_)");
720
- return { text: (await git(path, ["worktree", "add", "-b", branch, gitPath(target)])).trim() };
789
+ return { text: (await g(["worktree", "add", "-b", branch, gitPath(target)])).trim() };
721
790
  }
722
791
  if (!ref || !safeRef(ref)) throw Error("worktree-add needs a branch (new) or ref (existing)");
723
- return { text: (await git(path, ["worktree", "add", gitPath(target), ref])).trim() };
792
+ return { text: (await g(["worktree", "add", gitPath(target), ref])).trim() };
724
793
  }
725
794
  case "worktree-remove": {
726
795
  if (!target || !isAbsolute(target)) throw Error("worktree-remove needs an absolute path");
727
- return { text: (await git(path, ["worktree", "remove", gitPath(target)])).trim() || `removed ${target}` };
796
+ return { text: (await g(["worktree", "remove", gitPath(target)])).trim() || `removed ${target}` };
728
797
  }
729
798
  }
730
799
  }