my-durable 0.0.75 → 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
  });
@@ -171,9 +179,21 @@ export interface GitStatus {
171
179
 
172
180
  /** One status for MANY paths — what a session list needs. The per-path cache
173
181
  * keeps repeat polls cheap on big repos. */
174
- export async function gitStatusBatch(paths: string[]): Promise<Record<string, GitStatus>> {
182
+ export async function gitStatusBatch(paths: string[]): Promise<Record<string, GitStatus | { error: string }>> {
175
183
  const unique = [...new Set(paths.filter(Boolean))];
176
- const entries = await Promise.all(unique.map(async (p) => [p, await gitStatus(p)] as const));
184
+ // R21 (index 400s): one failing path (permissions, a git binary error, a
185
+ // timeout on a huge checkout) used to reject the WHOLE batch — every
186
+ // project's chip died with it. Settle each path separately: failures become
187
+ // bounded `{error}` entries the FE caches instead of retry-hammering.
188
+ const entries = await Promise.all(
189
+ unique.map(async (p): Promise<[string, GitStatus | { error: string }]> => {
190
+ try {
191
+ return [p, await gitStatus(p)];
192
+ } catch (e) {
193
+ return [p, { error: String((e as Error)?.message ?? e).slice(0, 120) }];
194
+ }
195
+ }),
196
+ );
177
197
  return Object.fromEntries(entries);
178
198
  }
179
199
 
@@ -257,6 +277,41 @@ function ensureWatcher(root: string) {
257
277
  watchers.set(root, entry);
258
278
  }
259
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
+
260
315
  /** Test hook: the TTL cache would serve a pre-mutation answer. */
261
316
  export function clearGitStatusCache() {
262
317
  statusCache.clear();
@@ -289,25 +344,43 @@ async function statusOnce(path: string, key: string): Promise<GitStatus> {
289
344
  // Reach git at all before trusting any "empty" answer: git missing from
290
345
  // the daemon's PATH (seen on a Windows Startup-launched device) must NOT
291
346
  // read as "not a repository" under a real repo.
292
- 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();
293
366
  out.repo = true;
294
367
  out.root = root;
295
368
  // Everything after toplevel runs in PARALLEL — status is the long pole
296
369
  // (20s+ on big Windows checkouts) and must not wait for four fast calls.
297
370
  const [branchP, headP, statusP, gitDirP, wlP, branchesP, numWorkP, numIdxP, mergeP, nameP, emailP, remoteP] = await Promise.allSettled([
298
- git(path, ["branch", "--show-current"]),
299
- git(path, ["log", "-1", "--pretty=%h%x09%s"]),
300
- git(path, ["--no-optional-locks", "status", "--porcelain=v1", "-b"], GIT_SLOW_TIMEOUT),
301
- git(path, ["rev-parse", "--git-dir"]),
302
- git(path, ["worktree", "list", "--porcelain"], GIT_SLOW_TIMEOUT),
303
- git(path, ["for-each-ref", "refs/heads", "--format=%(refname:short)%09%(upstream:short)%09%(if)%(HEAD)%(then)1%(else)0%(end)"]),
304
- git(path, ["--no-optional-locks", "diff", "--numstat", "--no-renames"], GIT_SLOW_TIMEOUT),
305
- 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"]),
306
379
  // MERGE_HEAD exists ⇔ a merge is waiting to be resolved.
307
- git(path, ["rev-parse", "-q", "--verify", "MERGE_HEAD"]),
308
- git(path, ["config", "user.name"]),
309
- git(path, ["config", "user.email"]),
310
- 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"]),
311
384
  ]);
312
385
  const branch = branchP.status === "fulfilled" ? branchP.value : "";
313
386
  out.branch = branch.trim() || undefined;
@@ -501,16 +574,24 @@ export async function gitOp(
501
574
  prs?: { n: number; title: string; state: string; draft: boolean; branch: string; url: string }[];
502
575
  }> {
503
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);
504
584
  switch (op) {
505
585
  case "diff":
506
- return { text: await git(path, ["--no-pager", "diff", ...(ref && safeRef(ref) ? [ref] : [])]) };
586
+ return { text: await g(["--no-pager", "diff", ...(ref && safeRef(ref) ? [ref] : [])]) };
507
587
  case "log":
508
- 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() };
509
589
  case "log-list": {
510
590
  // IntelliJ's log window: hash, refs, author, date, subject — structured.
511
591
  // %p = parents — the swimlane graph is computed from these on the UI.
512
- const raw = await git(
513
- 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(
514
595
  ["--no-pager", "log", "-n", "50", "--date=short", "--pretty=format:%h%x1f%D%x1f%an%x1f%ad%x1f%s%x1f%p"],
515
596
  );
516
597
  return {
@@ -532,69 +613,69 @@ export async function gitOp(
532
613
  };
533
614
  }
534
615
  case "fetch":
535
- return { text: (await git(path, ["fetch", "--all", "--prune"])).trim() || "fetched" };
616
+ return { text: (await g(["fetch", "--all", "--prune"])).trim() || "fetched" };
536
617
  case "pull":
537
618
  // --ff-only stays the default; --rebase is an explicit opt-in the UI
538
619
  // offers only after a ff-only failure.
539
- 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" };
540
621
  case "branch":
541
- return { text: (await git(path, ["--no-pager", "branch", "-vv"])).trimEnd() };
622
+ return { text: (await g(["--no-pager", "branch", "-vv"])).trimEnd() };
542
623
  case "switch": {
543
624
  if (!ref || !safeRef(ref)) throw Error("switch needs a branch name (letters, digits, ./-_)");
544
625
  // create:true = git switch -c — IntelliJ's "new branch" action.
545
- return { text: (await git(path, ["switch", ...(create ? ["-c"] : []), ref])).trim() };
626
+ return { text: (await g(["switch", ...(create ? ["-c"] : []), ref])).trim() };
546
627
  }
547
628
  case "push": {
548
629
  if (setUpstream) {
549
630
  if (!ref || !safeRef(ref)) throw Error("push -u needs a branch name");
550
- 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}` };
551
632
  }
552
- 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)" };
553
634
  }
554
635
  case "stage": {
555
636
  if (!files?.length) throw Error("stage needs files");
556
- 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)` };
557
638
  }
558
639
  case "discard": {
559
640
  // IntelliJ's Rollback: index AND worktree back to HEAD for these paths.
560
641
  if (!files?.length) throw Error("discard needs files");
561
- 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)` };
562
643
  }
563
644
  case "diff-file": {
564
645
  if (!target) throw Error("diff-file needs a file path");
565
- 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" };
566
647
  }
567
648
  case "stash-push":
568
- return { text: (await git(path, ["stash", "push", ...(message ? ["-m", message] : [])])).trim() || "stashed" };
649
+ return { text: (await g(["stash", "push", ...(message ? ["-m", message] : [])])).trim() || "stashed" };
569
650
  case "stash-pop":
570
- return { text: (await git(path, ["stash", "pop"])).trim() || "stash popped" };
651
+ return { text: (await g(["stash", "pop"])).trim() || "stash popped" };
571
652
  case "unstage": {
572
653
  // IntelliJ's Unstage: index only, worktree keeps its changes.
573
654
  if (!files?.length) throw Error("unstage needs files");
574
655
  try {
575
- 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)` };
576
657
  } catch {
577
658
  // unborn branch: HEAD does not resolve yet — reset against the empty tree.
578
- 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)` };
579
660
  }
580
661
  }
581
662
  case "compare": {
582
663
  // ahead/behind vs ANY ref, not just the upstream (orca git-bridge).
583
664
  if (!ref || !safeRef(ref)) throw Error("compare needs a branch name");
584
- const raw = await git(path, ["rev-list", "--left-right", "--count", `${ref}...HEAD`]);
665
+ const raw = await g(["rev-list", "--left-right", "--count", `${ref}...HEAD`]);
585
666
  const [behind = "0", ahead = "0"] = raw.trim().split(/\s+/);
586
667
  return { text: `${Number(ahead)} ahead, ${Number(behind)} behind of ${ref}`, ahead: Number(ahead), behind: Number(behind) };
587
668
  }
588
669
  case "merge-abort":
589
670
  try {
590
- return { text: (await git(path, ["merge", "--abort"])).trim() || "merge aborted" };
671
+ return { text: (await g(["merge", "--abort"])).trim() || "merge aborted" };
591
672
  } catch {
592
- return { text: (await git(path, ["rebase", "--abort"])).trim() || "rebase aborted" };
673
+ return { text: (await g(["rebase", "--abort"])).trim() || "rebase aborted" };
593
674
  }
594
675
  case "show-files": {
595
676
  // What one commit touched — the log row expander.
596
677
  if (!target || !/^[0-9a-f]{4,40}$/.test(target)) throw Error("show-files needs a commit hash");
597
- 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]);
598
679
  return {
599
680
  text: "",
600
681
  changed: raw
@@ -613,7 +694,7 @@ export async function gitOp(
613
694
  if (!lines?.length) throw Error("ignore needs pattern lines");
614
695
  if (lines.length > 50) throw Error("ignore takes at most 50 lines");
615
696
  for (const l of lines) if (!l.trim() || l.length > 200 || /[\n\r\0]/.test(l)) throw Error("bad ignore pattern");
616
- const root = (await git(path, ["rev-parse", "--show-toplevel"])).trim();
697
+ const root = pin?.workTree ?? (await g(["rev-parse", "--show-toplevel"])).trim();
617
698
  await appendFile(join(root, ".gitignore"), `\n${lines.join("\n")}\n`, "utf8");
618
699
  return { text: `added to .gitignore: ${lines.join(", ")}` };
619
700
  }
@@ -621,11 +702,11 @@ export async function gitOp(
621
702
  // A named ref of HEAD — the rewind target. Never touches the worktree.
622
703
  if (!name || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name)) throw Error("checkpoint needs a name (letters, digits, ._-)");
623
704
  const refname = `refs/dpi/checkpoints/${name}`;
624
- await git(path, ["update-ref", refname, "HEAD"]);
705
+ await g(["update-ref", refname, "HEAD"]);
625
706
  return { text: `checkpoint ${name} saved` };
626
707
  }
627
708
  case "checkpoints": {
628
- const raw = await git(path, [
709
+ const raw = await g([
629
710
  "--no-pager", "for-each-ref", "refs/dpi/checkpoints",
630
711
  "--format=%(refname:strip=3)%09%(objectname:short)%09%(committerdate:short)%09%(contents:subject)",
631
712
  ]);
@@ -645,28 +726,28 @@ export async function gitOp(
645
726
  // reset --hard to one of OUR checkpoint refs only — never an arbitrary ref.
646
727
  if (!name || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name)) throw Error("rewind needs a checkpoint name");
647
728
  const refname = `refs/dpi/checkpoints/${name}`;
648
- const sha = (await git(path, ["rev-parse", "--verify", refname])).trim();
649
- 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}` };
650
731
  }
651
732
  case "resolve": {
652
733
  // orca's conflicts section, one click: pick a side, stage the result.
653
734
  if (side !== "ours" && side !== "theirs") throw Error("resolve needs side=ours|theirs");
654
735
  if (!files?.length) throw Error("resolve needs files");
655
- await git(path, ["checkout", `--${side}`, "--", ...gitPaths(files)]);
656
- 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}` };
657
738
  }
658
739
  case "submodule-update":
659
- 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" };
660
741
  case "pr-create": {
661
742
  // gh pr create — title from message, head = current branch. gh owns auth.
662
743
  const title = (message ?? "").trim();
663
744
  if (!title) throw Error("pr-create needs a title (message)");
664
745
  const args = ["pr", "create", "--title", title.slice(0, 200), "--body", (body ?? title).slice(0, 4000)];
665
746
  if (ref && safeRef(ref)) args.push("--base", ref);
666
- 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
667
748
  }
668
749
  case "pr-list": {
669
- 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"]);
670
751
  const list = JSON.parse(raw || "[]") as { number: number; title: string; state: string; isDraft: boolean; headRefName: string; url: string }[];
671
752
  return {
672
753
  text: "",
@@ -675,17 +756,17 @@ export async function gitOp(
675
756
  }
676
757
  case "pr-merge": {
677
758
  if (!n || !Number.isInteger(n)) throw Error("pr-merge needs a PR number");
678
- 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` };
679
760
  }
680
761
  case "pr-checks": {
681
762
  if (!n || !Number.isInteger(n)) throw Error("pr-checks needs a PR number");
682
- 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" };
683
764
  }
684
765
  case "pr-comment": {
685
766
  if (!n || !Number.isInteger(n)) throw Error("pr-comment needs a PR number");
686
767
  const text = (body ?? "").trim();
687
768
  if (!text) throw Error("pr-comment needs a body");
688
- 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() };
689
770
  }
690
771
  case "commit": {
691
772
  const msg = (message ?? "").trim();
@@ -693,26 +774,26 @@ export async function gitOp(
693
774
  // IntelliJ-style: chosen files only, when the caller picked some.
694
775
  if (files?.length) {
695
776
  for (const f of files) if (f.includes("\0") || f === "") throw Error("bad file path");
696
- 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" };
697
778
  }
698
- 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" };
699
780
  }
700
781
  case "worktree-list":
701
- return { text: (await git(path, ["--no-pager", "worktree", "list"])).trimEnd() };
782
+ return { text: (await g(["--no-pager", "worktree", "list"])).trimEnd() };
702
783
  case "worktree-add": {
703
784
  // branch = create a NEW branch for the worktree; ref = check out an
704
785
  // existing one. Both validated the same strict way — never a shell.
705
786
  if (!target || !isAbsolute(target)) throw Error("worktree-add needs an absolute target path");
706
787
  if (branch) {
707
788
  if (!safeRef(branch)) throw Error("worktree-add branch name is invalid (letters, digits, ./-_)");
708
- return { text: (await git(path, ["worktree", "add", "-b", branch, gitPath(target)])).trim() };
789
+ return { text: (await g(["worktree", "add", "-b", branch, gitPath(target)])).trim() };
709
790
  }
710
791
  if (!ref || !safeRef(ref)) throw Error("worktree-add needs a branch (new) or ref (existing)");
711
- return { text: (await git(path, ["worktree", "add", gitPath(target), ref])).trim() };
792
+ return { text: (await g(["worktree", "add", gitPath(target), ref])).trim() };
712
793
  }
713
794
  case "worktree-remove": {
714
795
  if (!target || !isAbsolute(target)) throw Error("worktree-remove needs an absolute path");
715
- return { text: (await git(path, ["worktree", "remove", gitPath(target)])).trim() || `removed ${target}` };
796
+ return { text: (await g(["worktree", "remove", gitPath(target)])).trim() || `removed ${target}` };
716
797
  }
717
798
  }
718
799
  }
@@ -14,7 +14,7 @@ import type { DevicePairing } from "./pairing.js";
14
14
 
15
15
  type Async = (req: Request, res: Response) => Promise<unknown>;
16
16
  const route = (fn: Async) => (req: Request, res: Response, next: NextFunction) => fn(req, res).catch(next);
17
- import { gitOp, gitStatus, gitStatusBatch, isNotARepoError, type GitOp } from "./git.js";
17
+ import { gitOp, gitStatus, gitStatusBatch, isNotARepoError, type GitOp, type GitStatus } from "./git.js";
18
18
  const GIT_OPS: GitOp[] = ["diff", "log", "log-list", "fetch", "pull", "push", "switch", "branch", "commit", "stage", "unstage", "discard", "diff-file", "stash-push", "stash-pop", "compare", "merge-abort", "show-files", "ignore", "checkpoint", "checkpoints", "rewind", "resolve", "submodule-update", "pr-create", "pr-list", "pr-merge", "pr-checks", "pr-comment", "worktree-list", "worktree-add", "worktree-remove"];
19
19
 
20
20
  interface Locals {
@@ -180,12 +180,28 @@ export function v1(
180
180
  }));
181
181
  r.post("/git/status-batch", route(async (req, res) => {
182
182
  const raw: string[] = Array.isArray(req.body?.paths) ? req.body.paths.map(String).filter(Boolean).slice(0, 50) : [];
183
- const paths = await Promise.all(raw.map((p) => store.containedPath(p)));
184
- try {
185
- res.json(await gitStatusBatch(paths));
186
- } catch (e) {
187
- throw gitFault(e, paths[0] ?? "");
183
+ // R21 (index 400s): a project left over from OTHER start dirs (device
184
+ // restarted with a narrower sandbox) used to reject the WHOLE batch from
185
+ // Promise.all — every project's chip died with it and the FE retried the
186
+ // doomed request every stale window. Settle containment per path: foreign
187
+ // paths answer a bounded `{error}` entry keyed by the path AS SENT (the
188
+ // FE's cache key), the rest keep their real status.
189
+ const settled = await Promise.all(
190
+ raw.map(async (p): Promise<[string, string | undefined]> => {
191
+ try {
192
+ return [p, await store.containedPath(p)];
193
+ } catch {
194
+ return [p, undefined];
195
+ }
196
+ }),
197
+ );
198
+ const contained = settled.filter((e): e is [string, string] => e[1] !== undefined).map(([, c]) => c);
199
+ const statuses = await gitStatusBatch(contained);
200
+ const out: Record<string, GitStatus | { error: string }> = {};
201
+ for (const [p, c] of settled) {
202
+ out[p] = c === undefined ? { error: "path must live under a start dir" } : (statuses[c] ?? { error: "git status unavailable" });
188
203
  }
204
+ res.json(out);
189
205
  }));
190
206
  r.post("/git", route(async (req, res) => {
191
207
  const body = req.body ?? {};