my-durable 0.0.76 → 0.0.78

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 (31) hide show
  1. package/apps/dpi-backend/src/archived.ts +54 -9
  2. package/apps/dpi-backend/src/git.ts +178 -78
  3. package/apps/dpi-backend/src/pairing.ts +3 -1
  4. package/apps/dpi-backend/src/salvage.ts +70 -4
  5. package/apps/dpi-backend/src/store.ts +273 -15
  6. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-h81haD43.css → index-BF6mtGF4.css} +1 -1
  7. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DAF9D074.js +82 -0
  8. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  9. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/git-rules.ts +38 -0
  10. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/git-store.ts +64 -19
  11. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/hub.ts +26 -2
  12. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/GitPanel.vue +46 -2
  13. package/apps/dpi-playground/apps/dpi-playground-hub/src/audit.ts +11 -3
  14. package/apps/dpi-playground/apps/dpi-playground-hub/src/monitor.ts +25 -2
  15. package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +44 -4
  16. package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +52 -6
  17. package/apps/dpi-sdk/src/api.ts +5 -1
  18. package/apps/dpi-sdk/src/models.ts +180 -19
  19. package/apps/dpi-sdk/src/node/config.ts +13 -2
  20. package/apps/dpi-sdk/src/node/ops.ts +33 -6
  21. package/apps/dpi-sdk/src/node/registry-migration.ts +76 -3
  22. package/apps/dpi-sdk/src/node/registry.ts +5 -2
  23. package/apps/dpi-sdk/src/transcript.ts +1 -0
  24. package/apps/dpi-tui/src/app.ts +7 -6
  25. package/apps/dpi-tui/src/pairing.ts +15 -11
  26. package/apps/dpi-tui/src/pickers.ts +11 -8
  27. package/apps/dpi-tui/src/sanitize.ts +5 -0
  28. package/apps/dpi-tui/src/views.ts +16 -16
  29. package/apps/dpi-tui/src/welcome.ts +9 -4
  30. package/package.json +1 -1
  31. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-BmxTF5DB.js +0 -82
@@ -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
@@ -54,8 +54,15 @@ export function cacheKey(p: string, platform: NodeJS.Platform = process.platform
54
54
  return platform === "win32" ? trimmed.toLowerCase() : trimmed;
55
55
  }
56
56
 
57
- /** Same, for the `-- <paths...>` lists (stage/discard/commit/unstage/resolve). */
58
- const gitPaths = (paths: string[]): string[] => paths.map(gitPath);
57
+ /** Same, for the `-- <paths...>` lists (stage/discard/commit/unstage/resolve).
58
+ * run-8 U2: NUL/empty are refused for EVERY files-bearing op (commit-only
59
+ * before) — with -z parsing the returned spellings are exact bytes, so the
60
+ * parity check is load-bearing. */
61
+ const gitPaths = (paths: string[]): string[] =>
62
+ paths.map((p) => {
63
+ if (typeof p !== "string" || p.includes("\0") || p === "") throw Error("bad file path");
64
+ return gitPath(p);
65
+ });
59
66
 
60
67
  /** Child-process options, exported so a test can assert the Windows console
61
68
  * window stays hidden: a daemon that polls git must never flash a terminal. */
@@ -80,18 +87,26 @@ const childEnv = (): NodeJS.ProcessEnv => {
80
87
  const allow = process.platform === "win32" ? WIN32_CHILD_ENV_ALLOWLIST : CHILD_ENV_ALLOWLIST;
81
88
  return Object.fromEntries(allow.flatMap((k) => (process.env[k] ? [[k, process.env[k]]] : [])));
82
89
  }
83
- export const GIT_EXEC_OPTS = (timeout: number) => ({
90
+ export interface RepoPin {
91
+ gitDir: string;
92
+ workTree: string;
93
+ }
94
+ /** run-7 cold-1 M3: pin the repo per request — GIT_DIR/GIT_WORK_TREE stop
95
+ * every spawn re-running .git discovery, so an in-sandbox racer flipping the
96
+ * .git file (gitdir redirect / core.worktree) between the guard's resolves
97
+ * and the data spawns cannot redirect the operation. */
98
+ export const GIT_EXEC_OPTS = (timeout: number, pin?: RepoPin) => ({
84
99
  timeout,
85
100
  maxBuffer: 8 * 1024 * 1024,
86
101
  windowsHide: true,
87
- env: childEnv(),
102
+ env: { ...childEnv(), ...(pin ? { GIT_DIR: pin.gitDir, GIT_WORK_TREE: pin.workTree } : {}) } as ReturnType<typeof childEnv>,
88
103
  });
89
- export const GH_EXEC_OPTS = (cwd: string, timeout: number) => ({
104
+ export const GH_EXEC_OPTS = (cwd: string, timeout: number, pin?: RepoPin) => ({
90
105
  cwd,
91
106
  timeout,
92
107
  maxBuffer: 4 * 1024 * 1024,
93
108
  windowsHide: true,
94
- env: childEnv(),
109
+ env: { ...childEnv(), ...(pin ? { GIT_DIR: pin.gitDir, GIT_WORK_TREE: pin.workTree } : {}) } as ReturnType<typeof childEnv>,
95
110
  });
96
111
 
97
112
  /** Test seam for counting/driving spawns: `node:child_process`'s ESM namespace
@@ -112,10 +127,10 @@ export function isNotARepoError(e: unknown): boolean {
112
127
  }
113
128
 
114
129
  /** 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> {
130
+ export function git(cwd: string, args: string[], timeout = GIT_TIMEOUT, pin?: RepoPin): Promise<string> {
116
131
  return new Promise((ok, fail) => {
117
132
  // `-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) => {
133
+ execFileImpl("git", ["-C", gitPath(cwd), ...args], GIT_EXEC_OPTS(timeout, pin), (error, stdout, stderr) => {
119
134
  if (error) fail(Error(String(stderr || stdout || error.message).trim().slice(0, 400)));
120
135
  // git chats on stderr for worktree add/switch/fetch — keep both.
121
136
  else ok(`${String(stdout)}${String(stdout) && String(stderr) ? "\n" : ""}${String(stderr)}`);
@@ -126,11 +141,11 @@ export function git(cwd: string, args: string[], timeout = GIT_TIMEOUT): Promise
126
141
  /** One GitHub CLI call — PRs, checks and comments are forge territory and gh
127
142
  * is the least-token-ceremony way to reach them from a device. Same no-shell
128
143
  * rule: argv only, plain text back. */
129
- export function gh(cwd: string, args: string[], timeout = GIT_TIMEOUT): Promise<string> {
144
+ export function gh(cwd: string, args: string[], timeout = GIT_TIMEOUT, pin?: RepoPin): Promise<string> {
130
145
  return new Promise((ok, fail) => {
131
146
  // gh resolves the repo from cwd (a --repo flag wants a slug, not a path).
132
147
  // 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) => {
148
+ execFileImpl("gh", args, GH_EXEC_OPTS(cwd, timeout, pin), (error, stdout, stderr) => {
134
149
  if (error) fail(Error(String(stderr || stdout || error.message).trim().slice(0, 400)));
135
150
  else ok(String(stdout));
136
151
  });
@@ -269,6 +284,41 @@ function ensureWatcher(root: string) {
269
284
  watchers.set(root, entry);
270
285
  }
271
286
 
287
+ /** R23 rule: confinement scopes the DEVICE REST surface only — git
288
+ * discovery must not WALK UP to an enclosing repo whose toplevel sits
289
+ * outside the start dirs (a remote viewer would read a repo the device
290
+ * never served). The absolute git dir is NOT confined: redirects and linked
291
+ * worktrees whose gitdir lives elsewhere are operator territory and are
292
+ * followed via the returned pin (the agent itself is unsandboxed by design). */
293
+ export async function resolveRepoPin(path: string): Promise<RepoPin | undefined> {
294
+ if (!repoRootAllowed) return undefined;
295
+ const [topLevel, gitDir] = await Promise.all([
296
+ git(path, ["rev-parse", "--show-toplevel"]),
297
+ git(path, ["rev-parse", "--absolute-git-dir"]),
298
+ ]);
299
+ const pin: RepoPin = { gitDir: gitDir.trim(), workTree: topLevel.trim() };
300
+ // R23 (operator decision): durable-pi WRAPS pi/pi-durable — the agent is
301
+ // unsandboxed by design (full user shell/fs), so the gitdir-redirect class
302
+ // is not an escalation for it, and refusing gitdirs outside the start dirs
303
+ // broke legitimate linked worktrees. Confinement now scopes only the DEVICE
304
+ // REST surface: the walk-up case (git DISCOVERY adopts a toplevel outside
305
+ // the start dirs) — a viewer must not read a repo the device never served.
306
+ if (!(await repoRootAllowed(pin.workTree))) throw Error("repo root lives outside the start dirs");
307
+ return pin;
308
+ }
309
+
310
+ // R21/run-7 D1: git's repo discovery WALKS UP from the contained request path —
311
+ // a start dir that is a slice of a bigger repo (monorepo, worktree-heavy
312
+ // checkout) made git adopt an OUT-of-sandbox repo root, disclosing repo-wide
313
+ // files/branches/worktrees/remoteUrl and (op "ignore") even WRITING .gitignore
314
+ // outside the start dirs. The store installs this guard; git.ts itself never
315
+ // learns the roots.
316
+ type RepoRootGuard = (root: string) => Promise<boolean>;
317
+ let repoRootAllowed: RepoRootGuard | undefined;
318
+ export function configureGitRootGuard(fn: RepoRootGuard | undefined) {
319
+ repoRootAllowed = fn;
320
+ }
321
+
272
322
  /** Test hook: the TTL cache would serve a pre-mutation answer. */
273
323
  export function clearGitStatusCache() {
274
324
  statusCache.clear();
@@ -301,25 +351,43 @@ async function statusOnce(path: string, key: string): Promise<GitStatus> {
301
351
  // Reach git at all before trusting any "empty" answer: git missing from
302
352
  // the daemon's PATH (seen on a Windows Startup-launched device) must NOT
303
353
  // read as "not a repository" under a real repo.
304
- const root = (await git(path, ["rev-parse", "--show-toplevel"])).trim();
354
+ // The discovered root is an ATTACKER-REACHABLE fact (any contained
355
+ // subdirectory of a repo reaches it): clamp before anything repo-wide
356
+ // runs — a REMOTE VIEWER must not read a repo the device never served.
357
+ // R23: toplevel-only (the gitdir condition broke linked worktrees and
358
+ // treated the unsandboxed local agent as a racer — see resolveRepoPin).
359
+ // The pin rides GIT_DIR/GIT_WORK_TREE into every later spawn regardless.
360
+ let pin: RepoPin | undefined;
361
+ try {
362
+ pin = await resolveRepoPin(path);
363
+ } catch (e) {
364
+ if (!String((e as Error).message).includes("start dirs")) throw e;
365
+ out.repo = true; // repo presence only — no root, files, branches,
366
+ // worktrees, remoteUrl, subject, identity; no watcher on foreign ground.
367
+ statusCache.set(key, { at: Date.now(), s: out });
368
+ statusFailCache.delete(key);
369
+ return out;
370
+ }
371
+ const g = (args: string[], t?: number) => git(path, args, t, pin);
372
+ const root = pin?.workTree ?? (await git(path, ["rev-parse", "--show-toplevel"])).trim();
305
373
  out.repo = true;
306
374
  out.root = root;
307
375
  // Everything after toplevel runs in PARALLEL — status is the long pole
308
376
  // (20s+ on big Windows checkouts) and must not wait for four fast calls.
309
377
  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"]),
378
+ g(["branch", "--show-current"]),
379
+ g(["log", "-1", "--pretty=%h%x09%s"]),
380
+ g(["--no-optional-locks", "status", "--porcelain=v1", "-z", "-b"], GIT_SLOW_TIMEOUT),
381
+ g(["rev-parse", "--git-dir"]),
382
+ g(["worktree", "list", "--porcelain"], GIT_SLOW_TIMEOUT),
383
+ g(["for-each-ref", "refs/heads", "--format=%(refname:short)%09%(upstream:short)%09%(if)%(HEAD)%(then)1%(else)0%(end)"]),
384
+ g(["--no-optional-locks", "diff", "--numstat", "-z", "--no-renames"], GIT_SLOW_TIMEOUT),
385
+ g(["--no-optional-locks", "diff", "--numstat", "-z", "--cached", "--no-renames"]),
318
386
  // 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"]),
387
+ g(["rev-parse", "-q", "--verify", "MERGE_HEAD"]),
388
+ g(["config", "user.name"]),
389
+ g(["config", "user.email"]),
390
+ g(["remote", "get-url", "origin"]),
323
391
  ]);
324
392
  const branch = branchP.status === "fulfilled" ? branchP.value : "";
325
393
  out.branch = branch.trim() || undefined;
@@ -332,8 +400,14 @@ async function statusOnce(path: string, key: string): Promise<GitStatus> {
332
400
  }
333
401
  if (statusP.status === "rejected") throw statusP.reason;
334
402
  const status = statusP.value;
335
- const lines = status.split("\n");
336
- const head2 = lines[0] ?? "";
403
+ // run-8 U2: parse the -z stream (NUL-delimited, NEVER C-quoted). The
404
+ // v1 line form C-quotes control/backslash/non-ASCII names; stripping
405
+ // only the outer quotes handed the ESCAPED spelling to the FE, and its
406
+ // verbatim round-trip into stage/discard reported success while missing
407
+ // the real file (leader-probed: "discarded 1 file(s)" with the
408
+ // TAB-named file still modified).
409
+ const records = status.split("\0").filter(Boolean);
410
+ const head2 = records[0]?.startsWith("## ") ? records[0] : "";
337
411
  // "## main...origin/main [ahead 2, behind 1]" — split by hand: a lazy \S+?
338
412
  // ate the branch down to one letter.
339
413
  const info = head2.replace(/^## /, "");
@@ -346,10 +420,21 @@ async function statusOnce(path: string, key: string): Promise<GitStatus> {
346
420
  out.ahead = Number(ab.match(/ahead (\d+)/)?.[1] ?? 0);
347
421
  out.behind = Number(ab.match(/behind (\d+)/)?.[1] ?? 0);
348
422
  }
349
- // Per line — a ^-anchored regex on the joined blob only ever sees line 1.
350
- const body = lines.slice(1).filter(Boolean);
423
+ // Per record — NUL-delimited, so an embedded newline can never forge a
424
+ // record boundary (the old line-form regex was per-line). A rename/copy
425
+ // record is followed by its ORIGIN path as a separate record; that record
426
+ // is status text too, so it must be dropped ONCE here — leaving it in made
427
+ // the counters at the bottom count an old path that starts with M/A/U.
428
+ const raw = records.filter((r) => !r.startsWith("## "));
429
+ const body: string[] = [];
430
+ for (let i = 0; i < raw.length; i++) {
431
+ const rec = raw[i]!;
432
+ body.push(rec);
433
+ const x = rec[0] ?? " ";
434
+ if ((x === "R" || x === "C") && i + 1 < raw.length) i++;
435
+ }
351
436
  out.merge = mergeP.status === "fulfilled";
352
- out.conflicts = count(body.join("\n"), /^(UU|AA|DD|AU|UA|DU|UD)/gm);
437
+ out.conflicts = body.filter((r) => /^(UU|AA|DD|AU|UA|DU|UD)/.test(r)).length;
353
438
  out.identity = {
354
439
  name: nameP.status === "fulfilled" ? nameP.value.trim() || undefined : undefined,
355
440
  email: emailP.status === "fulfilled" ? emailP.value.trim() || undefined : undefined,
@@ -358,8 +443,10 @@ async function statusOnce(path: string, key: string): Promise<GitStatus> {
358
443
  // ±n per file: worktree-vs-index numstat for unstaged paths, cached for staged.
359
444
  const numstat = (raw: string) => {
360
445
  const m = new Map<string, { a: number; d: number }>();
361
- for (const l of raw.split("\n")) {
362
- const mt = l.match(/^(\d+|-)\t(\d+|-)\t(.+)$/);
446
+ // run-8 U2: -z is NUL-delimited and unquoted (renames disabled, so no
447
+ // trailing original-path record). Paths may contain any byte but NUL.
448
+ for (const rec of raw.split("\0")) {
449
+ const mt = rec.match(/^(\d+|-)\t(\d+|-)\t([\s\S]+)$/);
363
450
  if (!mt) continue;
364
451
  m.set(mt[3]!, { a: mt[1] === "-" ? -1 : Number(mt[1]), d: mt[2] === "-" ? -1 : Number(mt[2]) });
365
452
  }
@@ -367,12 +454,15 @@ async function statusOnce(path: string, key: string): Promise<GitStatus> {
367
454
  };
368
455
  const workNum = numstat(numWorkP.status === "fulfilled" ? numWorkP.value : "");
369
456
  const idxNum = numstat(numIdxP.status === "fulfilled" ? numIdxP.value : "");
370
- out.files = body.slice(0, 500).map((l) => {
371
- const p = l.slice(3).replace(/^"|"$/g, "");
372
- const staged = l[0] !== " " && l[0] !== "?";
457
+ out.files = [];
458
+ for (const l of body.slice(0, 500)) {
459
+ const x = l[0] ?? " ";
460
+ const y = l[1] ?? " ";
461
+ const p = l.slice(3);
462
+ const staged = x !== " " && x !== "?";
373
463
  const n = staged ? idxNum.get(p) : workNum.get(p);
374
- return { path: p, x: l[0] ?? " ", y: l[1] ?? " ", ...(n ? { a: n.a, d: n.d } : {}) };
375
- });
464
+ out.files.push({ path: p, x, y, ...(n ? { a: n.a, d: n.d } : {}) });
465
+ }
376
466
  if (branchesP.status === "fulfilled")
377
467
  out.branches = branchesP.value
378
468
  .split("\n")
@@ -383,9 +473,11 @@ async function statusOnce(path: string, key: string): Promise<GitStatus> {
383
473
  return { name: name ?? "", current: head === "1", upstream: upstream || undefined };
384
474
  })
385
475
  .filter((b) => b.name);
386
- out.staged = count(body.join("\n"), /^[MADRC]/gm);
387
- out.unstaged = count(body.join("\n"), /^ [MD]/gm);
388
- out.untracked = count(body.join("\n"), /^\?\?/gm);
476
+ // run-8 U2: count PER RECORD — with -z a filename may contain a newline,
477
+ // so the old joined-text ^-anchored regexes could be forged by a name.
478
+ out.staged = body.filter((r) => /^[MADRC]/.test(r)).length;
479
+ out.unstaged = body.filter((r) => /^ [MD]/.test(r)).length;
480
+ out.untracked = body.filter((r) => /^\?\?/.test(r)).length;
389
481
  // In a linked worktree --git-dir is "<main>/.git/worktrees/<name>";
390
482
  // the main checkout is the .git's parent.
391
483
  const gitDir = (gitDirP.status === "fulfilled" ? gitDirP.value : "").trim();
@@ -513,16 +605,24 @@ export async function gitOp(
513
605
  prs?: { n: number; title: string; state: string; draft: boolean; branch: string; url: string }[];
514
606
  }> {
515
607
  const { ref, message, target, branch, files, create, staged, rebase, setUpstream, name, lines, method, body, n, side } = opts;
608
+ // R23: the TOPLEVEL must sit under the start dirs (gitdir redirects are
609
+ // operator territory — see resolveRepoPin); the resolved pin rides
610
+ // GIT_DIR/GIT_WORK_TREE into EVERY spawn below, so per-spawn .git discovery
611
+ // never re-runs and the check cannot be raced.
612
+ const pin = await resolveRepoPin(path);
613
+ const g = (args: string[], t?: number) => git(path, args, t, pin);
614
+ const ghP = (args: string[], t?: number) => gh(path, args, t, pin);
516
615
  switch (op) {
517
616
  case "diff":
518
- return { text: await git(path, ["--no-pager", "diff", ...(ref && safeRef(ref) ? [ref] : [])]) };
617
+ return { text: await g(["--no-pager", "diff", ...(ref && safeRef(ref) ? [ref] : [])]) };
519
618
  case "log":
520
- return { text: (await git(path, ["--no-pager", "log", "--oneline", "-n", "30", ...(ref && safeRef(ref) ? [ref] : [])])).trimEnd() };
619
+ return { text: (await g(["--no-pager", "log", "--oneline", "-n", "30", ...(ref && safeRef(ref) ? [ref] : [])])).trimEnd() };
521
620
  case "log-list": {
522
621
  // IntelliJ's log window: hash, refs, author, date, subject — structured.
523
622
  // %p = parents — the swimlane graph is computed from these on the UI.
524
- const raw = await git(
525
- path,
623
+ // run-7 cold-2 M1: pinned like every other spawn — the bare git() here
624
+ // re-ran .git discovery, reopening the TOCTOU M3 exists to close.
625
+ const raw = await g(
526
626
  ["--no-pager", "log", "-n", "50", "--date=short", "--pretty=format:%h%x1f%D%x1f%an%x1f%ad%x1f%s%x1f%p"],
527
627
  );
528
628
  return {
@@ -544,69 +644,69 @@ export async function gitOp(
544
644
  };
545
645
  }
546
646
  case "fetch":
547
- return { text: (await git(path, ["fetch", "--all", "--prune"])).trim() || "fetched" };
647
+ return { text: (await g(["fetch", "--all", "--prune"])).trim() || "fetched" };
548
648
  case "pull":
549
649
  // --ff-only stays the default; --rebase is an explicit opt-in the UI
550
650
  // offers only after a ff-only failure.
551
- return { text: (await git(path, ["pull", ...(rebase ? ["--rebase"] : ["--ff-only"])])).trim() || "up to date" };
651
+ return { text: (await g(["pull", ...(rebase ? ["--rebase"] : ["--ff-only"])])).trim() || "up to date" };
552
652
  case "branch":
553
- return { text: (await git(path, ["--no-pager", "branch", "-vv"])).trimEnd() };
653
+ return { text: (await g(["--no-pager", "branch", "-vv"])).trimEnd() };
554
654
  case "switch": {
555
655
  if (!ref || !safeRef(ref)) throw Error("switch needs a branch name (letters, digits, ./-_)");
556
656
  // create:true = git switch -c — IntelliJ's "new branch" action.
557
- return { text: (await git(path, ["switch", ...(create ? ["-c"] : []), ref])).trim() };
657
+ return { text: (await g(["switch", ...(create ? ["-c"] : []), ref])).trim() };
558
658
  }
559
659
  case "push": {
560
660
  if (setUpstream) {
561
661
  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}` };
662
+ return { text: (await g(["push", "-u", "origin", ref], GIT_SLOW_TIMEOUT)).trim() || `pushed, upstream set to origin/${ref}` };
563
663
  }
564
- return { text: (await git(path, ["push"], GIT_SLOW_TIMEOUT)).trim() || "pushed (or nothing to push)" };
664
+ return { text: (await g(["push"], GIT_SLOW_TIMEOUT)).trim() || "pushed (or nothing to push)" };
565
665
  }
566
666
  case "stage": {
567
667
  if (!files?.length) throw Error("stage needs files");
568
- return { text: (await git(path, ["add", "--", ...gitPaths(files)])).trim() || `staged ${files.length} file(s)` };
668
+ return { text: (await g(["add", "--", ...gitPaths(files)])).trim() || `staged ${files.length} file(s)` };
569
669
  }
570
670
  case "discard": {
571
671
  // IntelliJ's Rollback: index AND worktree back to HEAD for these paths.
572
672
  if (!files?.length) throw Error("discard needs files");
573
- return { text: (await git(path, ["checkout", "HEAD", "--", ...gitPaths(files)])).trim() || `discarded ${files.length} file(s)` };
673
+ return { text: (await g(["checkout", "HEAD", "--", ...gitPaths(files)])).trim() || `discarded ${files.length} file(s)` };
574
674
  }
575
675
  case "diff-file": {
576
676
  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" };
677
+ return { text: (await g(["--no-pager", "diff", ...(staged ? ["--cached"] : []), "HEAD", "--", gitPath(target)])).trim() || "no diff" };
578
678
  }
579
679
  case "stash-push":
580
- return { text: (await git(path, ["stash", "push", ...(message ? ["-m", message] : [])])).trim() || "stashed" };
680
+ return { text: (await g(["stash", "push", ...(message ? ["-m", message] : [])])).trim() || "stashed" };
581
681
  case "stash-pop":
582
- return { text: (await git(path, ["stash", "pop"])).trim() || "stash popped" };
682
+ return { text: (await g(["stash", "pop"])).trim() || "stash popped" };
583
683
  case "unstage": {
584
684
  // IntelliJ's Unstage: index only, worktree keeps its changes.
585
685
  if (!files?.length) throw Error("unstage needs files");
586
686
  try {
587
- return { text: (await git(path, ["reset", "-q", "HEAD", "--", ...gitPaths(files)])).trim() || `unstaged ${files.length} file(s)` };
687
+ return { text: (await g(["reset", "-q", "HEAD", "--", ...gitPaths(files)])).trim() || `unstaged ${files.length} file(s)` };
588
688
  } catch {
589
689
  // 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)` };
690
+ return { text: (await g(["reset", "-q", "--", ...gitPaths(files)])).trim() || `unstaged ${files.length} file(s)` };
591
691
  }
592
692
  }
593
693
  case "compare": {
594
694
  // ahead/behind vs ANY ref, not just the upstream (orca git-bridge).
595
695
  if (!ref || !safeRef(ref)) throw Error("compare needs a branch name");
596
- const raw = await git(path, ["rev-list", "--left-right", "--count", `${ref}...HEAD`]);
696
+ const raw = await g(["rev-list", "--left-right", "--count", `${ref}...HEAD`]);
597
697
  const [behind = "0", ahead = "0"] = raw.trim().split(/\s+/);
598
698
  return { text: `${Number(ahead)} ahead, ${Number(behind)} behind of ${ref}`, ahead: Number(ahead), behind: Number(behind) };
599
699
  }
600
700
  case "merge-abort":
601
701
  try {
602
- return { text: (await git(path, ["merge", "--abort"])).trim() || "merge aborted" };
702
+ return { text: (await g(["merge", "--abort"])).trim() || "merge aborted" };
603
703
  } catch {
604
- return { text: (await git(path, ["rebase", "--abort"])).trim() || "rebase aborted" };
704
+ return { text: (await g(["rebase", "--abort"])).trim() || "rebase aborted" };
605
705
  }
606
706
  case "show-files": {
607
707
  // What one commit touched — the log row expander.
608
708
  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]);
709
+ const raw = await g(["--no-pager", "show", "--name-status", "--pretty=format:", "--no-renames", "-m", "--first-parent", target]);
610
710
  return {
611
711
  text: "",
612
712
  changed: raw
@@ -625,7 +725,7 @@ export async function gitOp(
625
725
  if (!lines?.length) throw Error("ignore needs pattern lines");
626
726
  if (lines.length > 50) throw Error("ignore takes at most 50 lines");
627
727
  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();
728
+ const root = pin?.workTree ?? (await g(["rev-parse", "--show-toplevel"])).trim();
629
729
  await appendFile(join(root, ".gitignore"), `\n${lines.join("\n")}\n`, "utf8");
630
730
  return { text: `added to .gitignore: ${lines.join(", ")}` };
631
731
  }
@@ -633,11 +733,11 @@ export async function gitOp(
633
733
  // A named ref of HEAD — the rewind target. Never touches the worktree.
634
734
  if (!name || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name)) throw Error("checkpoint needs a name (letters, digits, ._-)");
635
735
  const refname = `refs/dpi/checkpoints/${name}`;
636
- await git(path, ["update-ref", refname, "HEAD"]);
736
+ await g(["update-ref", refname, "HEAD"]);
637
737
  return { text: `checkpoint ${name} saved` };
638
738
  }
639
739
  case "checkpoints": {
640
- const raw = await git(path, [
740
+ const raw = await g([
641
741
  "--no-pager", "for-each-ref", "refs/dpi/checkpoints",
642
742
  "--format=%(refname:strip=3)%09%(objectname:short)%09%(committerdate:short)%09%(contents:subject)",
643
743
  ]);
@@ -657,28 +757,28 @@ export async function gitOp(
657
757
  // reset --hard to one of OUR checkpoint refs only — never an arbitrary ref.
658
758
  if (!name || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name)) throw Error("rewind needs a checkpoint name");
659
759
  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}` };
760
+ const sha = (await g(["rev-parse", "--verify", refname])).trim();
761
+ return { text: (await g(["reset", "--hard", sha])).trim().split("\n")[0] ?? `rewound to ${name}` };
662
762
  }
663
763
  case "resolve": {
664
764
  // orca's conflicts section, one click: pick a side, stage the result.
665
765
  if (side !== "ours" && side !== "theirs") throw Error("resolve needs side=ours|theirs");
666
766
  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}` };
767
+ await g(["checkout", `--${side}`, "--", ...gitPaths(files)]);
768
+ return { text: (await g(["add", "--", ...gitPaths(files)])).trim() || `resolved ${files.length} file(s) with --${side}` };
669
769
  }
670
770
  case "submodule-update":
671
- return { text: (await git(path, ["submodule", "update", "--init", "--recursive"], GIT_SLOW_TIMEOUT)).trim() || "submodules up to date" };
771
+ return { text: (await g(["submodule", "update", "--init", "--recursive"], GIT_SLOW_TIMEOUT)).trim() || "submodules up to date" };
672
772
  case "pr-create": {
673
773
  // gh pr create — title from message, head = current branch. gh owns auth.
674
774
  const title = (message ?? "").trim();
675
775
  if (!title) throw Error("pr-create needs a title (message)");
676
776
  const args = ["pr", "create", "--title", title.slice(0, 200), "--body", (body ?? title).slice(0, 4000)];
677
777
  if (ref && safeRef(ref)) args.push("--base", ref);
678
- return { text: (await gh(path, args, GIT_SLOW_TIMEOUT)).trim() };
778
+ return { text: (await ghP(args, GIT_SLOW_TIMEOUT)).trim() }; // run-7 cold-2 M2: pinned like its pr-* siblings
679
779
  }
680
780
  case "pr-list": {
681
- const raw = await gh(path, ["pr", "list", "--limit", "20", "--json", "number,title,state,isDraft,headRefName,url"]);
781
+ const raw = await ghP(["pr", "list", "--limit", "20", "--json", "number,title,state,isDraft,headRefName,url"]);
682
782
  const list = JSON.parse(raw || "[]") as { number: number; title: string; state: string; isDraft: boolean; headRefName: string; url: string }[];
683
783
  return {
684
784
  text: "",
@@ -687,17 +787,17 @@ export async function gitOp(
687
787
  }
688
788
  case "pr-merge": {
689
789
  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` };
790
+ return { text: (await ghP(["pr", "merge", String(n), method === "merge" ? "--merge" : "--squash"], GIT_SLOW_TIMEOUT)).trim() || `PR #${n} merged` };
691
791
  }
692
792
  case "pr-checks": {
693
793
  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" };
794
+ return { text: (await ghP(["pr", "checks", String(n)], GIT_SLOW_TIMEOUT)).trim() || "no checks reported" };
695
795
  }
696
796
  case "pr-comment": {
697
797
  if (!n || !Number.isInteger(n)) throw Error("pr-comment needs a PR number");
698
798
  const text = (body ?? "").trim();
699
799
  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() };
800
+ return { text: (await ghP(["pr", "comment", String(n), "--body", text.slice(0, 4000)])).trim() };
701
801
  }
702
802
  case "commit": {
703
803
  const msg = (message ?? "").trim();
@@ -705,26 +805,26 @@ export async function gitOp(
705
805
  // IntelliJ-style: chosen files only, when the caller picked some.
706
806
  if (files?.length) {
707
807
  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" };
808
+ return { text: (await g(["commit", "-m", msg, "--", ...gitPaths(files)])).split("\n")[0]?.trim() ?? "committed" };
709
809
  }
710
- return { text: (await git(path, ["commit", "-am", msg])).split("\n")[0]?.trim() ?? "committed" };
810
+ return { text: (await g(["commit", "-am", msg])).split("\n")[0]?.trim() ?? "committed" };
711
811
  }
712
812
  case "worktree-list":
713
- return { text: (await git(path, ["--no-pager", "worktree", "list"])).trimEnd() };
813
+ return { text: (await g(["--no-pager", "worktree", "list"])).trimEnd() };
714
814
  case "worktree-add": {
715
815
  // branch = create a NEW branch for the worktree; ref = check out an
716
816
  // existing one. Both validated the same strict way — never a shell.
717
817
  if (!target || !isAbsolute(target)) throw Error("worktree-add needs an absolute target path");
718
818
  if (branch) {
719
819
  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() };
820
+ return { text: (await g(["worktree", "add", "-b", branch, gitPath(target)])).trim() };
721
821
  }
722
822
  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() };
823
+ return { text: (await g(["worktree", "add", gitPath(target), ref])).trim() };
724
824
  }
725
825
  case "worktree-remove": {
726
826
  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}` };
827
+ return { text: (await g(["worktree", "remove", gitPath(target)])).trim() || `removed ${target}` };
728
828
  }
729
829
  }
730
830
  }
@@ -697,7 +697,9 @@ export class DevicePairing {
697
697
  )
698
698
  ) {
699
699
  this.pending = undefined;
700
- this.lastFailure = `${code}: ${message}`;
700
+ // run-8 U6: the hub controls this message; the TUI renders (and
701
+ // re-wraps) it every poll — bound it at the seam.
702
+ this.lastFailure = `${code}: ${String(message ?? "").slice(0, 400)}`;
701
703
  return;
702
704
  }
703
705
  await sleep(pollMs * 2, pending.abort.signal);