@narumitw/pi-worktree 0.51.7 → 0.51.9

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.
package/dist/index.ts CHANGED
@@ -11,6 +11,9 @@ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "
11
11
  import { basename, dirname, resolve } from "node:path";
12
12
  var GIT_TIMEOUT_MS = 15e3;
13
13
  var GIT_MUTATION_TIMEOUT_MS = 6e4;
14
+ var GIT_METADATA_MAX_BUFFER = 64 * 1024;
15
+ var GIT_RECORDS_MAX_BUFFER = 8 * 1024 * 1024;
16
+ var GIT_MUTATION_MAX_BUFFER = 1024 * 1024;
14
17
  var LOCAL_BRANCH_PREFIX = "refs/heads/";
15
18
  var GitWorktreeError = class extends Error {
16
19
  args;
@@ -43,9 +46,7 @@ function parseWorktreePorcelain(output) {
43
46
  continue;
44
47
  }
45
48
  if (!current) {
46
- throw new GitWorktreeError(
47
- `Worktree porcelain field ${JSON.stringify(key)} appears before worktree.`
48
- );
49
+ throw new GitWorktreeError(`Worktree porcelain field ${JSON.stringify(key)} appears before worktree.`);
49
50
  }
50
51
  switch (key) {
51
52
  case "HEAD":
@@ -113,16 +114,12 @@ function unresolvableSymlinkAncestor(path) {
113
114
  if (isNodeError(error) && (error.code === "ENOENT" || error.code === "ELOOP")) {
114
115
  return current;
115
116
  }
116
- throw new GitWorktreeError(
117
- `Cannot resolve filesystem ancestor ${current}: ${formatError(error)}`
118
- );
117
+ throw new GitWorktreeError(`Cannot resolve filesystem ancestor ${current}: ${formatError(error)}`);
119
118
  }
120
119
  } catch (error) {
121
120
  if (!isNodeError(error) || error.code !== "ENOENT") {
122
121
  if (error instanceof GitWorktreeError) throw error;
123
- throw new GitWorktreeError(
124
- `Cannot inspect filesystem ancestor ${current}: ${formatError(error)}`
125
- );
122
+ throw new GitWorktreeError(`Cannot inspect filesystem ancestor ${current}: ${formatError(error)}`);
126
123
  }
127
124
  const parent = dirname(current);
128
125
  if (parent === current) return void 0;
@@ -137,11 +134,11 @@ function sameWorktreeIdentity(left, right) {
137
134
  return pathsEqual(left.path, right.path) && left.head === right.head && left.branchRef === right.branchRef && left.detached === right.detached && left.isMain === right.isMain && left.bare === right.bare;
138
135
  }
139
136
  async function listWorktrees(pi, cwd, signal) {
140
- const result = await runGit(pi, ["worktree", "list", "--porcelain", "-z"], cwd, signal);
137
+ const result = await runGit(pi, ["worktree", "list", "--porcelain", "-z"], cwd, GIT_RECORDS_MAX_BUFFER, signal);
141
138
  return parseWorktreePorcelain(result.stdout);
142
139
  }
143
140
  async function currentWorktreePath(pi, cwd, signal) {
144
- const result = await runGit(pi, ["rev-parse", "--show-toplevel"], cwd, signal);
141
+ const result = await runGit(pi, ["rev-parse", "--show-toplevel"], cwd, GIT_METADATA_MAX_BUFFER, signal);
145
142
  const path = removeLineEnding(result.stdout);
146
143
  if (!path) throw new GitWorktreeError("Git did not return the current worktree path.");
147
144
  return pathIdentity(path);
@@ -151,6 +148,7 @@ async function symbolicBranch(pi, cwd, signal) {
151
148
  pi,
152
149
  ["symbolic-ref", "--quiet", "--short", "HEAD"],
153
150
  cwd,
151
+ GIT_METADATA_MAX_BUFFER,
154
152
  signal
155
153
  );
156
154
  if (result.killed) throw killedError(["symbolic-ref", "--quiet", "--short", "HEAD"]);
@@ -158,7 +156,7 @@ async function symbolicBranch(pi, cwd, signal) {
158
156
  return result.stdout.trim() || void 0;
159
157
  }
160
158
  async function validateBranch(pi, cwd, branch, signal) {
161
- const result = await runGit(pi, ["check-ref-format", "--branch", branch], cwd, signal);
159
+ const result = await runGit(pi, ["check-ref-format", "--branch", branch], cwd, GIT_METADATA_MAX_BUFFER, signal);
162
160
  const normalized = result.stdout.trim();
163
161
  if (!normalized) throw new GitWorktreeError("Git returned an empty branch name.");
164
162
  return normalized;
@@ -168,6 +166,7 @@ async function localBranchExists(pi, cwd, branch, signal) {
168
166
  pi,
169
167
  ["show-ref", "--verify", "--quiet", `${LOCAL_BRANCH_PREFIX}${branch}`],
170
168
  cwd,
169
+ GIT_METADATA_MAX_BUFFER,
171
170
  signal
172
171
  );
173
172
  if (result.killed) throw killedError(["show-ref", "--verify", "--quiet"]);
@@ -180,6 +179,7 @@ async function resolveCommit(pi, cwd, startPoint, signal) {
180
179
  pi,
181
180
  ["rev-parse", "--verify", "--end-of-options", `${startPoint}^{commit}`],
182
181
  cwd,
182
+ GIT_METADATA_MAX_BUFFER,
183
183
  signal
184
184
  );
185
185
  const oid = result.stdout.trim();
@@ -189,10 +189,10 @@ async function resolveCommit(pi, cwd, startPoint, signal) {
189
189
  return oid;
190
190
  }
191
191
  async function addWorktree(pi, cwd, input, signal) {
192
- await runGit(pi, buildAddArguments(input), cwd, signal, GIT_MUTATION_TIMEOUT_MS);
192
+ await runGit(pi, buildAddArguments(input), cwd, GIT_MUTATION_MAX_BUFFER, signal, GIT_MUTATION_TIMEOUT_MS);
193
193
  }
194
194
  async function removeWorktree(pi, cwd, path, signal) {
195
- await runGit(pi, ["worktree", "remove", path], cwd, signal, GIT_MUTATION_TIMEOUT_MS);
195
+ await runGit(pi, ["worktree", "remove", path], cwd, GIT_MUTATION_MAX_BUFFER, signal, GIT_MUTATION_TIMEOUT_MS);
196
196
  }
197
197
  async function worktreeInventory(pi, path, signal) {
198
198
  const statusArgs = [
@@ -202,10 +202,16 @@ async function worktreeInventory(pi, path, signal) {
202
202
  "--ignored=matching",
203
203
  "--ignore-submodules=none"
204
204
  ];
205
- const status = await runGit(pi, statusArgs, path, signal);
206
- const indexFlags = await runGit(pi, ["ls-files", "-v", "-z"], path, signal);
205
+ const status = await runGit(pi, statusArgs, path, GIT_RECORDS_MAX_BUFFER, signal);
206
+ const indexFlags = await runGit(pi, ["ls-files", "-v", "-z"], path, GIT_RECORDS_MAX_BUFFER, signal);
207
207
  const indexInventory = await indexFlagInventory(pi, indexFlags.stdout, path, signal);
208
- const submoduleStatus = await runGit(pi, ["submodule", "status", "--recursive"], path, signal);
208
+ const submoduleStatus = await runGit(
209
+ pi,
210
+ ["submodule", "status", "--recursive"],
211
+ path,
212
+ GIT_RECORDS_MAX_BUFFER,
213
+ signal
214
+ );
209
215
  const initializedSubmodules = nonEmptyLines(submoduleStatus.stdout).filter((line) => !line.startsWith("-")).map((line) => `initialized submodule: ${line.slice(1).trimStart()}`);
210
216
  const submodules = await runGit(
211
217
  pi,
@@ -217,6 +223,7 @@ async function worktreeInventory(pi, path, signal) {
217
223
  "git status --porcelain=v1 --untracked-files=all --ignored=matching --ignore-submodules=none"
218
224
  ],
219
225
  path,
226
+ GIT_RECORDS_MAX_BUFFER,
220
227
  signal
221
228
  );
222
229
  return [
@@ -231,6 +238,7 @@ async function worktreeAdministrativeDirectory(pi, cwd, signal) {
231
238
  pi,
232
239
  ["rev-parse", "--path-format=absolute", "--git-dir"],
233
240
  cwd,
241
+ GIT_METADATA_MAX_BUFFER,
234
242
  signal
235
243
  );
236
244
  const value = removeLineEnding(result.stdout);
@@ -244,17 +252,11 @@ async function administrativeHistoryOids(pi, cwd, administrativePath, signal) {
244
252
  pi,
245
253
  [gitDirArgument, "for-each-ref", "--format=%(objectname)", "refs/worktree", "refs/bisect"],
246
254
  cwd,
255
+ GIT_RECORDS_MAX_BUFFER,
247
256
  signal
248
257
  );
249
258
  values.push(...splitAdministrativeOids(refs.stdout, "per-worktree refs"));
250
- for (const name of [
251
- "ORIG_HEAD",
252
- "MERGE_HEAD",
253
- "REBASE_HEAD",
254
- "CHERRY_PICK_HEAD",
255
- "REVERT_HEAD",
256
- "BISECT_HEAD"
257
- ]) {
259
+ for (const name of ["ORIG_HEAD", "MERGE_HEAD", "REBASE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "BISECT_HEAD"]) {
258
260
  const contents = readAdministrativeFile(administrativePath, name);
259
261
  if (contents === void 0) continue;
260
262
  values.push(...splitAdministrativeOids(contents, name));
@@ -270,6 +272,7 @@ async function administrativePruneCandidates(pi, cwd, signal) {
270
272
  pi,
271
273
  ["rev-parse", "--path-format=absolute", "--git-common-dir"],
272
274
  cwd,
275
+ GIT_METADATA_MAX_BUFFER,
273
276
  signal
274
277
  );
275
278
  const commonValue = removeLineEnding(commonResult.stdout);
@@ -281,9 +284,7 @@ async function administrativePruneCandidates(pi, cwd, signal) {
281
284
  for (const entry of readdirSync(administrativeRoot, { withFileTypes: true })) {
282
285
  const administrativePath = resolve(administrativeRoot, entry.name);
283
286
  if (!entry.isDirectory() || entry.isSymbolicLink()) {
284
- throw new GitWorktreeError(
285
- `Unexpected Git worktree administrative entry: ${administrativePath}.`
286
- );
287
+ throw new GitWorktreeError(`Unexpected Git worktree administrative entry: ${administrativePath}.`);
287
288
  }
288
289
  if (existsSync(resolve(administrativePath, "locked"))) continue;
289
290
  const gitdirPath = resolve(administrativePath, "gitdir");
@@ -306,17 +307,13 @@ async function administrativePruneCandidates(pi, cwd, signal) {
306
307
  headValue = removeLineEnding(readFileSync(headPath, "utf8"));
307
308
  } catch (error) {
308
309
  if (error instanceof GitWorktreeError) throw error;
309
- throw new GitWorktreeError(
310
- `Cannot inspect Git worktree administrative HEAD ${headPath}: ${formatError(error)}`
311
- );
310
+ throw new GitWorktreeError(`Cannot inspect Git worktree administrative HEAD ${headPath}: ${formatError(error)}`);
312
311
  }
313
312
  const indexDirty = await administrativeIndexIsDirty(pi, cwd, administrativePath, signal);
314
313
  if (headValue.startsWith("ref: ")) {
315
314
  const branchRef = headValue.slice("ref: ".length);
316
315
  if (!branchRef) {
317
- throw new GitWorktreeError(
318
- `Git worktree administrative HEAD has an empty ref: ${headPath}.`
319
- );
316
+ throw new GitWorktreeError(`Git worktree administrative HEAD has an empty ref: ${headPath}.`);
320
317
  }
321
318
  candidates.push({
322
319
  id: entry.name,
@@ -349,7 +346,7 @@ async function administrativeIndexIsDirty(pi, cwd, administrativePath, signal) {
349
346
  "--ignore-submodules=none",
350
347
  "--"
351
348
  ];
352
- const result = await runGitAllowFailure(pi, args, cwd, signal);
349
+ const result = await runGitAllowFailure(pi, args, cwd, GIT_METADATA_MAX_BUFFER, signal);
353
350
  if (result.killed) throw killedError(args);
354
351
  if (result.code === 0) return false;
355
352
  if (result.code === 1) return true;
@@ -363,6 +360,7 @@ async function durableRefExists(pi, cwd, ref, signal) {
363
360
  pi,
364
361
  ["show-ref", "--verify", "--quiet", ref],
365
362
  cwd,
363
+ GIT_METADATA_MAX_BUFFER,
366
364
  signal
367
365
  );
368
366
  if (result.killed) throw killedError(["show-ref", "--verify", "--quiet"]);
@@ -376,21 +374,15 @@ async function durableRefsContaining(pi, cwd, head, signal) {
376
374
  }
377
375
  const result = await runGit(
378
376
  pi,
379
- [
380
- "for-each-ref",
381
- "--format=%(refname)",
382
- `--contains=${head}`,
383
- "refs/heads",
384
- "refs/tags",
385
- "refs/remotes"
386
- ],
377
+ ["for-each-ref", "--format=%(refname)", `--contains=${head}`, "refs/heads", "refs/tags", "refs/remotes"],
387
378
  cwd,
379
+ GIT_RECORDS_MAX_BUFFER,
388
380
  signal
389
381
  );
390
382
  return nonEmptyLines(result.stdout);
391
383
  }
392
384
  async function prunePreview(pi, cwd, signal) {
393
- const result = await runGit(pi, ["worktree", "prune", "--dry-run", "--verbose"], cwd, signal);
385
+ const result = await runGit(pi, ["worktree", "prune", "--dry-run", "--verbose"], cwd, GIT_RECORDS_MAX_BUFFER, signal);
394
386
  return combineOutput(result);
395
387
  }
396
388
  async function pruneWorktrees(pi, cwd, signal) {
@@ -398,6 +390,7 @@ async function pruneWorktrees(pi, cwd, signal) {
398
390
  pi,
399
391
  ["worktree", "prune", "--verbose"],
400
392
  cwd,
393
+ GIT_MUTATION_MAX_BUFFER,
401
394
  signal,
402
395
  GIT_MUTATION_TIMEOUT_MS
403
396
  );
@@ -421,38 +414,39 @@ function stripTerminalControls(value) {
421
414
  return code > 31 && (code < 127 || code > 159);
422
415
  }).join("");
423
416
  }
424
- async function runGit(pi, args, cwd, signal, timeout = GIT_TIMEOUT_MS) {
425
- const result = await runGitAllowFailure(pi, args, cwd, signal, timeout);
417
+ async function runGit(pi, args, cwd, maxBuffer, signal, timeout = GIT_TIMEOUT_MS) {
418
+ const result = await runGitAllowFailure(pi, args, cwd, maxBuffer, signal, timeout);
426
419
  if (result.killed) throw killedError(args);
427
420
  if (result.code !== 0) throw gitFailure(args, result);
428
421
  return result;
429
422
  }
430
- async function runGitAllowFailure(pi, args, cwd, signal, timeout = GIT_TIMEOUT_MS) {
423
+ async function runGitAllowFailure(pi, args, cwd, maxBuffer, signal, timeout = GIT_TIMEOUT_MS) {
424
+ let result;
431
425
  try {
432
- return await pi.exec("git", args, { cwd, signal, timeout });
426
+ result = await pi.exec("git", args, { cwd, signal, timeout, maxBuffer });
433
427
  } catch (error) {
434
428
  const message = formatError(error);
435
429
  if (/\bENOENT\b|not found/i.test(message)) {
436
430
  throw new GitWorktreeError("Git executable was not found. Install Git and retry.", args);
437
431
  }
438
- throw new GitWorktreeError(
439
- `Could not start git ${args.slice(0, 2).join(" ")}: ${message}`,
440
- args
441
- );
432
+ throw new GitWorktreeError(`Could not start git ${args.slice(0, 2).join(" ")}: ${message}`, args);
442
433
  }
434
+ if (result.truncated) throw outputLimitError(args, maxBuffer);
435
+ return result;
443
436
  }
444
- function gitFailure(args, result) {
445
- const detail = stripTerminalControls(
446
- [result.stderr.trim(), result.stdout.trim()].filter(Boolean).join("\n")
437
+ function outputLimitError(args, maxBuffer) {
438
+ return new GitWorktreeError(
439
+ `git ${args.slice(0, 2).join(" ")} output exceeded the ${maxBuffer}-byte limit. Partial output was not used; inspect Git state before retrying.`,
440
+ args
447
441
  );
442
+ }
443
+ function gitFailure(args, result) {
444
+ const detail = stripTerminalControls([result.stderr.trim(), result.stdout.trim()].filter(Boolean).join("\n"));
448
445
  const hint = /not a git repository/i.test(detail) ? "The current Pi workspace is not inside a Git repository." : detail || `Git exited with code ${result.code}.`;
449
446
  return new GitWorktreeError(`git ${args.slice(0, 2).join(" ")} failed: ${hint}`, args);
450
447
  }
451
448
  function killedError(args) {
452
- return new GitWorktreeError(
453
- `git ${args.slice(0, 2).join(" ")} timed out or was cancelled.`,
454
- args
455
- );
449
+ return new GitWorktreeError(`git ${args.slice(0, 2).join(" ")} timed out or was cancelled.`, args);
456
450
  }
457
451
  function nonEmptyLines(value) {
458
452
  return value.split(/\r?\n/u).filter((line) => line.length > 0);
@@ -494,17 +488,13 @@ function parseIndexFlagEntries(value) {
494
488
  async function sparseManagedSkipWorktreePaths(pi, cwd, paths, signal) {
495
489
  if (paths.length === 0) return /* @__PURE__ */ new Set();
496
490
  const configArgs = ["config", "--bool", "--get", "core.sparseCheckout"];
497
- const config = await runGitAllowFailure(pi, configArgs, cwd, signal);
491
+ const config = await runGitAllowFailure(pi, configArgs, cwd, GIT_METADATA_MAX_BUFFER, signal);
498
492
  if (config.killed) throw killedError(configArgs);
499
493
  if (config.code !== 0 || config.stdout.trim() !== "true") return /* @__PURE__ */ new Set();
500
494
  const candidates = new Set(paths);
501
495
  const checkArgs = ["sparse-checkout", "check-rules", "-z"];
502
- const checked = await runGitWithInputAllowFailure(
503
- checkArgs,
504
- cwd,
505
- `${[...candidates].join("\0")}\0`,
506
- signal
507
- );
496
+ const checked = await runGitWithInputAllowFailure(checkArgs, cwd, `${[...candidates].join("\0")}\0`, signal);
497
+ if (checked.truncated) throw outputLimitError(checkArgs, GIT_RECORDS_MAX_BUFFER);
508
498
  if (checked.killed) throw killedError(checkArgs);
509
499
  if (checked.code !== 0) return /* @__PURE__ */ new Set();
510
500
  const included = new Set(nulSeparatedPaths(checked.stdout, "sparse-checkout rules"));
@@ -515,13 +505,15 @@ async function sparseManagedSkipWorktreePaths(pi, cwd, paths, signal) {
515
505
  }
516
506
  function runGitWithInputAllowFailure(args, cwd, input, signal, timeout = GIT_TIMEOUT_MS) {
517
507
  if (signal?.aborted) {
518
- return Promise.resolve({ stdout: "", stderr: "", code: 1, killed: true });
508
+ return Promise.resolve({ stdout: "", stderr: "", code: 1, killed: true, truncated: false });
519
509
  }
520
510
  return new Promise((resolveResult, reject) => {
521
511
  const child = spawn("git", args, { cwd, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
522
512
  let stdout = "";
523
513
  let stderr = "";
524
514
  let killed = false;
515
+ let truncated = false;
516
+ let outputBytes = 0;
525
517
  let settled = false;
526
518
  const finish = (result) => {
527
519
  if (settled) return;
@@ -538,10 +530,7 @@ function runGitWithInputAllowFailure(args, cwd, input, signal, timeout = GIT_TIM
538
530
  child.kill();
539
531
  const message = formatError(error);
540
532
  reject(
541
- /\bENOENT\b|not found/i.test(message) ? new GitWorktreeError("Git executable was not found. Install Git and retry.", args) : new GitWorktreeError(
542
- `Could not start git ${args.slice(0, 2).join(" ")}: ${message}`,
543
- args
544
- )
533
+ /\bENOENT\b|not found/i.test(message) ? new GitWorktreeError("Git executable was not found. Install Git and retry.", args) : new GitWorktreeError(`Could not start git ${args.slice(0, 2).join(" ")}: ${message}`, args)
545
534
  );
546
535
  };
547
536
  const stop = () => {
@@ -549,20 +538,36 @@ function runGitWithInputAllowFailure(args, cwd, input, signal, timeout = GIT_TIM
549
538
  child.kill();
550
539
  };
551
540
  const timeoutHandle = setTimeout(stop, timeout);
541
+ const acceptChunk = (chunk) => {
542
+ if (truncated) return false;
543
+ outputBytes += Buffer.byteLength(chunk);
544
+ if (outputBytes <= GIT_RECORDS_MAX_BUFFER) return true;
545
+ truncated = true;
546
+ child.stdout.destroy();
547
+ child.stderr.destroy();
548
+ stop();
549
+ return false;
550
+ };
552
551
  child.stdout.setEncoding("utf8");
553
552
  child.stderr.setEncoding("utf8");
554
553
  child.stdout.on("data", (chunk) => {
555
- stdout += chunk;
554
+ if (acceptChunk(chunk)) stdout += chunk;
556
555
  });
557
556
  child.stderr.on("data", (chunk) => {
558
- stderr += chunk;
557
+ if (acceptChunk(chunk)) stderr += chunk;
559
558
  });
560
559
  child.stdin.on("error", (error) => {
561
560
  if (!isNodeError(error) || error.code !== "EPIPE") fail(error);
562
561
  });
563
562
  child.once("error", fail);
564
563
  child.once("close", (code, closeSignal) => {
565
- finish({ stdout, stderr, code: code ?? 1, killed: killed || closeSignal !== null });
564
+ finish({
565
+ stdout,
566
+ stderr,
567
+ code: truncated && code === 0 ? 1 : code ?? 1,
568
+ killed: killed || closeSignal !== null,
569
+ truncated
570
+ });
566
571
  });
567
572
  signal?.addEventListener("abort", stop, { once: true });
568
573
  if (signal?.aborted) stop();
@@ -610,21 +615,15 @@ function readAdministrativeFile(administrativePath, name) {
610
615
  stat = lstatSync(path);
611
616
  } catch (error) {
612
617
  if (isNodeError(error) && error.code === "ENOENT") return void 0;
613
- throw new GitWorktreeError(
614
- `Cannot inspect Git worktree administrative ${name}: ${formatError(error)}`
615
- );
618
+ throw new GitWorktreeError(`Cannot inspect Git worktree administrative ${name}: ${formatError(error)}`);
616
619
  }
617
620
  if (stat.isSymbolicLink() || !stat.isFile()) {
618
- throw new GitWorktreeError(
619
- `Git worktree administrative ${name} must be a regular file: ${path}.`
620
- );
621
+ throw new GitWorktreeError(`Git worktree administrative ${name} must be a regular file: ${path}.`);
621
622
  }
622
623
  try {
623
624
  return readFileSync(path, "utf8");
624
625
  } catch (error) {
625
- throw new GitWorktreeError(
626
- `Cannot inspect Git worktree administrative ${name}: ${formatError(error)}`
627
- );
626
+ throw new GitWorktreeError(`Cannot inspect Git worktree administrative ${name}: ${formatError(error)}`);
628
627
  }
629
628
  }
630
629
  function readAdministrativeReflogOids(logPath) {
@@ -685,10 +684,7 @@ async function switchToWorktree(ctx, targetPath) {
685
684
  sessionPath = createTargetSession(ctx, targetPath);
686
685
  const result = await ctx.switchSession(sessionPath, {
687
686
  withSession: async (replacementCtx) => {
688
- replacementCtx.ui.notify(
689
- stripTerminalControls(`Switched Pi workspace to ${targetPath}.`),
690
- "info"
691
- );
687
+ replacementCtx.ui.notify(stripTerminalControls(`Switched Pi workspace to ${targetPath}.`), "info");
692
688
  }
693
689
  });
694
690
  if (result.cancelled) {
@@ -733,12 +729,7 @@ function createTargetSession(ctx, targetPath) {
733
729
  return writeTargetSession(targetPath, ctx.sessionManager.getBranch(), sourceFile, activeLeaf);
734
730
  }
735
731
  if (ctx.sessionManager.getEntries().length > 0) {
736
- return writeTargetSession(
737
- targetPath,
738
- ctx.sessionManager.getBranch(),
739
- void 0,
740
- ctx.sessionManager.getLeafId()
741
- );
732
+ return writeTargetSession(targetPath, ctx.sessionManager.getBranch(), void 0, ctx.sessionManager.getLeafId());
742
733
  }
743
734
  return writeTargetSession(targetPath, [], void 0, null);
744
735
  }
@@ -767,6 +758,8 @@ function formatError2(error) {
767
758
  // src/status.ts
768
759
  import { existsSync as existsSync3 } from "node:fs";
769
760
  var GIT_STATUS_TIMEOUT_MS = 15e3;
761
+ var GIT_STATUS_MAX_BUFFER = 8 * 1024 * 1024;
762
+ var GIT_LAST_COMMIT_MAX_BUFFER = 64 * 1024;
770
763
  var DEFAULT_STATUS_CONCURRENCY = 4;
771
764
  var OID_PATTERN = /^[0-9a-fA-F]{40,64}$/u;
772
765
  var STATUS_XY_PATTERN = /^[.MADRCUT]{2}$/u;
@@ -852,11 +845,7 @@ function formatWorktreeStatusCard(record, currentPath, result) {
852
845
  description: path,
853
846
  statusText: `${statePrefix}unavailable`,
854
847
  searchText: `${label} ${path} ${identity.join(" ")} unavailable ${reason}`,
855
- details: [
856
- ...baseDetails,
857
- `Status: ${reason}`,
858
- "Snapshot: local Git state; no fetch performed."
859
- ]
848
+ details: [...baseDetails, `Status: ${reason}`, "Snapshot: local Git state; no fetch performed."]
860
849
  };
861
850
  }
862
851
  const { snapshot, lastCommit } = result;
@@ -880,10 +869,7 @@ function formatWorktreeStatusCard(record, currentPath, result) {
880
869
  };
881
870
  }
882
871
  async function loadWorktreeStatusCards(pi, records, currentPath, signal, options = {}) {
883
- const concurrency = Math.max(
884
- 1,
885
- Math.min(options.concurrency ?? DEFAULT_STATUS_CONCURRENCY, records.length || 1)
886
- );
872
+ const concurrency = Math.max(1, Math.min(options.concurrency ?? DEFAULT_STATUS_CONCURRENCY, records.length || 1));
887
873
  const cards = new Array(records.length);
888
874
  let nextIndex = 0;
889
875
  const worker = async () => {
@@ -905,15 +891,9 @@ async function loadWorktreeStatusCards(pi, records, currentPath, signal, options
905
891
  try {
906
892
  const status = await runGit2(
907
893
  pi,
908
- [
909
- "status",
910
- "--porcelain=v2",
911
- "--branch",
912
- "-z",
913
- "--untracked-files=all",
914
- "--ignore-submodules=none"
915
- ],
894
+ ["status", "--porcelain=v2", "--branch", "-z", "--untracked-files=all", "--ignore-submodules=none"],
916
895
  record.path,
896
+ GIT_STATUS_MAX_BUFFER,
917
897
  signal
918
898
  );
919
899
  const snapshot = parseWorktreeStatusPorcelain(status.stdout);
@@ -922,6 +902,7 @@ async function loadWorktreeStatusCards(pi, records, currentPath, signal, options
922
902
  pi,
923
903
  ["show", "-s", "--format=%aI%x00%s", "--end-of-options", snapshot.headOid],
924
904
  record.path,
905
+ GIT_LAST_COMMIT_MAX_BUFFER,
925
906
  signal
926
907
  )).stdout
927
908
  ) : void 0;
@@ -1009,9 +990,12 @@ function unavailableReason(record) {
1009
990
  if (!existsSync3(record.path)) return "Worktree path is missing";
1010
991
  return void 0;
1011
992
  }
1012
- async function runGit2(pi, args, cwd, signal) {
993
+ async function runGit2(pi, args, cwd, maxBuffer, signal) {
1013
994
  throwIfAborted(signal);
1014
- const result = await pi.exec("git", args, { cwd, signal, timeout: GIT_STATUS_TIMEOUT_MS });
995
+ const result = await pi.exec("git", args, { cwd, signal, timeout: GIT_STATUS_TIMEOUT_MS, maxBuffer });
996
+ if (result.truncated) {
997
+ throw new Error(`git ${args.slice(0, 2).join(" ")} output exceeded the ${maxBuffer}-byte limit.`);
998
+ }
1015
999
  if (result.killed) {
1016
1000
  throwIfAborted(signal);
1017
1001
  throw new Error(`git ${args.slice(0, 2).join(" ")} timed out.`);
@@ -1070,11 +1054,7 @@ function registerWorktreeCommand(pi, settings, getMenuOwner) {
1070
1054
  description: "Interactively manage Git worktrees and their default root",
1071
1055
  handler: async (args, ctx) => {
1072
1056
  if (args.trim()) {
1073
- safeNotify(
1074
- ctx,
1075
- "/worktree does not accept arguments; run it without arguments to open the menu.",
1076
- "warning"
1077
- );
1057
+ safeNotify(ctx, "/worktree does not accept arguments; run it without arguments to open the menu.", "warning");
1078
1058
  return;
1079
1059
  }
1080
1060
  if (!ctx.hasUI) {
@@ -1131,12 +1111,7 @@ function registerWorktreeCommand(pi, settings, getMenuOwner) {
1131
1111
  status: async ({ signal }) => {
1132
1112
  try {
1133
1113
  const statusRecords = await listWorktrees(pi, ctx.cwd, signal);
1134
- state.statusCards = await loadWorktreeStatusCards(
1135
- pi,
1136
- statusRecords,
1137
- currentPath,
1138
- signal
1139
- );
1114
+ state.statusCards = await loadWorktreeStatusCards(pi, statusRecords, currentPath, signal);
1140
1115
  if (signal.aborted || !owner.isCurrent()) return { kind: "close" };
1141
1116
  return { kind: "to", screen: "status" };
1142
1117
  } catch (error) {
@@ -1166,9 +1141,7 @@ function registerWorktreeCommand(pi, settings, getMenuOwner) {
1166
1141
  async function configureRootFlow(ctx, settings) {
1167
1142
  const current = await settings.reload();
1168
1143
  if (!current.canSave) {
1169
- throw new Error(
1170
- current.warning ?? `Fix ${settings.getPath()} before changing pi-worktree settings.`
1171
- );
1144
+ throw new Error(current.warning ?? `Fix ${settings.getPath()} before changing pi-worktree settings.`);
1172
1145
  }
1173
1146
  const requested = await ctx.ui.input(
1174
1147
  "Worktree root (blank restores ~/.worktrees)",
@@ -1190,9 +1163,7 @@ async function addFlow(pi, ctx, records, worktreeRoot) {
1190
1163
  throw new Error("The main worktree is bare; pi-worktree cannot derive a safe default path.");
1191
1164
  }
1192
1165
  if (!existsSync4(main.path)) {
1193
- throw new Error(
1194
- `The registered main worktree path is stale: ${main.path}. Repair it with Git first.`
1195
- );
1166
+ throw new Error(`The registered main worktree path is stale: ${main.path}. Repair it with Git first.`);
1196
1167
  }
1197
1168
  const requestedBranch = await ctx.ui.input("Branch for the new worktree", "feat/my-change");
1198
1169
  if (requestedBranch === void 0) return;
@@ -1237,9 +1208,7 @@ async function addFlow(pi, ctx, records, worktreeRoot) {
1237
1208
  stripTerminalControls(suggestedPath)
1238
1209
  );
1239
1210
  if (requestedPath === void 0) return;
1240
- const targetPath = pathIdentity(
1241
- requestedPath.trim() ? resolve2(ctx.cwd, requestedPath.trim()) : suggestedPath
1242
- );
1211
+ const targetPath = pathIdentity(requestedPath.trim() ? resolve2(ctx.cwd, requestedPath.trim()) : suggestedPath);
1243
1212
  assertTargetFilesystemAvailable(targetPath);
1244
1213
  const pathCollision = records.find((record) => pathsEqual(record.path, targetPath));
1245
1214
  if (pathCollision) {
@@ -1251,15 +1220,11 @@ async function addFlow(pi, ctx, records, worktreeRoot) {
1251
1220
  const latestRecords = await listWorktrees(pi, ctx.cwd, ctx.signal);
1252
1221
  const latestOccupied = worktreeForBranch(latestRecords, branch);
1253
1222
  if (latestOccupied) {
1254
- throw new Error(
1255
- `Branch ${branch} is now checked out at ${latestOccupied.path}; select it again.`
1256
- );
1223
+ throw new Error(`Branch ${branch} is now checked out at ${latestOccupied.path}; select it again.`);
1257
1224
  }
1258
1225
  const latestPathCollision = latestRecords.find((record) => pathsEqual(record.path, targetPath));
1259
1226
  if (latestPathCollision) {
1260
- throw new Error(
1261
- `The target path is now registered as a worktree: ${latestPathCollision.path}. Select it again.`
1262
- );
1227
+ throw new Error(`The target path is now registered as a worktree: ${latestPathCollision.path}. Select it again.`);
1263
1228
  }
1264
1229
  const branchStillExists = await localBranchExists(pi, ctx.cwd, branch, ctx.signal);
1265
1230
  if (branchStillExists !== branchExists) {
@@ -1278,9 +1243,7 @@ async function addFlow(pi, ctx, records, worktreeRoot) {
1278
1243
  const updated = await listWorktrees(pi, ctx.cwd, ctx.signal);
1279
1244
  const verified = updated.find((record) => pathsEqual(record.path, targetPath));
1280
1245
  if (!verified || verified.branch !== branch || verified.head !== provenance.oid) {
1281
- throw new Error(
1282
- "the expected path, branch, and approved HEAD were not present in Git porcelain output"
1283
- );
1246
+ throw new Error("the expected path, branch, and approved HEAD were not present in Git porcelain output");
1284
1247
  }
1285
1248
  created = verified;
1286
1249
  } catch (error) {
@@ -1289,10 +1252,7 @@ async function addFlow(pi, ctx, records, worktreeRoot) {
1289
1252
  );
1290
1253
  }
1291
1254
  safeNotify(ctx, `Created worktree ${targetPath} on branch ${branch}.`, "info");
1292
- if (await ctx.ui.confirm(
1293
- "Switch Pi workspace?",
1294
- stripTerminalControls(`Continue this conversation in ${targetPath}?`)
1295
- )) {
1255
+ if (await ctx.ui.confirm("Switch Pi workspace?", stripTerminalControls(`Continue this conversation in ${targetPath}?`))) {
1296
1256
  const latest = await revalidateWorktreeIdentity(pi, ctx, created);
1297
1257
  if (latest.prunableReason !== void 0 || !existsSync4(latest.path)) {
1298
1258
  throw new Error("The newly created worktree became unavailable; select it again.");
@@ -1329,9 +1289,7 @@ function assertTargetFilesystemAvailable(targetPath) {
1329
1289
  }
1330
1290
  const unsafeAncestor = unresolvableSymlinkAncestor(targetPath);
1331
1291
  if (unsafeAncestor) {
1332
- throw new Error(
1333
- `The target path has an unresolvable symbolic-link ancestor: ${unsafeAncestor}.`
1334
- );
1292
+ throw new Error(`The target path has an unresolvable symbolic-link ancestor: ${unsafeAncestor}.`);
1335
1293
  }
1336
1294
  }
1337
1295
  async function switchFlow(pi, ctx, records, currentPath, signal) {
@@ -1350,13 +1308,7 @@ async function removeFlow(pi, ctx, records, currentPath, signal) {
1350
1308
  const candidates = records.filter(
1351
1309
  (record) => !record.isMain && !record.bare && !pathsEqual(record.path, currentPath)
1352
1310
  );
1353
- const selected = await selectWorktree(
1354
- ctx,
1355
- "Remove linked worktree",
1356
- candidates,
1357
- currentPath,
1358
- signal
1359
- );
1311
+ const selected = await selectWorktree(ctx, "Remove linked worktree", candidates, currentPath, signal);
1360
1312
  if (!selected) return;
1361
1313
  if (selected.lockedReason !== void 0) {
1362
1314
  throw new Error(
@@ -1366,9 +1318,7 @@ async function removeFlow(pi, ctx, records, currentPath, signal) {
1366
1318
  if (selected.prunableReason !== void 0 || !existsSync4(selected.path)) {
1367
1319
  throw new Error("The selected worktree path is stale. Use prune instead of remove.");
1368
1320
  }
1369
- const inventory = classifyRemovalInventory(
1370
- await worktreeInventory(pi, selected.path, ctx.signal)
1371
- );
1321
+ const inventory = classifyRemovalInventory(await worktreeInventory(pi, selected.path, ctx.signal));
1372
1322
  if (inventory.protected.length > 0) {
1373
1323
  throw new Error(
1374
1324
  `Removal refused because ${selected.path} contains tracked, untracked, index-flagged, or submodule data:
@@ -1392,13 +1342,7 @@ ${recoveryWarning.trimStart()}` : `${ignoredWarning}${recoveryWarning}`;
1392
1342
  )) {
1393
1343
  return;
1394
1344
  }
1395
- await assertAdministrativeHistoryUnchanged(
1396
- pi,
1397
- ctx,
1398
- selected.path,
1399
- administrativePath,
1400
- approvedHistoryRisks
1401
- );
1345
+ await assertAdministrativeHistoryUnchanged(pi, ctx, selected.path, administrativePath, approvedHistoryRisks);
1402
1346
  const beforeRemoval = await listWorktrees(pi, ctx.cwd, ctx.signal);
1403
1347
  const latest = beforeRemoval.find((record) => pathsEqual(record.path, selected.path));
1404
1348
  if (!latest) throw new Error(`Worktree ${selected.path} is no longer registered.`);
@@ -1406,13 +1350,9 @@ ${recoveryWarning.trimStart()}` : `${ignoredWarning}${recoveryWarning}`;
1406
1350
  throw new Error(`Worktree ${selected.path} changed identity; select it again.`);
1407
1351
  }
1408
1352
  if (latest.isMain || latest.lockedReason !== void 0 || latest.prunableReason !== void 0) {
1409
- throw new Error(
1410
- `Worktree ${selected.path} changed state after confirmation; removal was refused.`
1411
- );
1353
+ throw new Error(`Worktree ${selected.path} changed state after confirmation; removal was refused.`);
1412
1354
  }
1413
- const latestInventory = classifyRemovalInventory(
1414
- await worktreeInventory(pi, latest.path, ctx.signal)
1415
- );
1355
+ const latestInventory = classifyRemovalInventory(await worktreeInventory(pi, latest.path, ctx.signal));
1416
1356
  if (latestInventory.protected.length > 0) {
1417
1357
  throw new Error(
1418
1358
  `Removal refused because new protected local data appeared after confirmation:
@@ -1426,13 +1366,7 @@ ${latestInventory.ignored.join("\n") || "(none)"}`
1426
1366
  );
1427
1367
  }
1428
1368
  await assertDetachedHeadIsDurable(pi, ctx, latest);
1429
- await assertAdministrativeHistoryUnchanged(
1430
- pi,
1431
- ctx,
1432
- latest.path,
1433
- administrativePath,
1434
- approvedHistoryRisks
1435
- );
1369
+ await assertAdministrativeHistoryUnchanged(pi, ctx, latest.path, administrativePath, approvedHistoryRisks);
1436
1370
  await removeWorktree(pi, ctx.cwd, latest.path, ctx.signal);
1437
1371
  const updated = await listWorktrees(pi, ctx.cwd, ctx.signal);
1438
1372
  if (updated.some((record) => pathsEqual(record.path, selected.path))) {
@@ -1441,9 +1375,7 @@ ${latestInventory.ignored.join("\n") || "(none)"}`
1441
1375
  safeNotify(ctx, `Removed worktree ${selected.path}. Its branch was preserved.`, "info");
1442
1376
  }
1443
1377
  async function pruneFlow(pi, ctx, records) {
1444
- for (const record of records.filter(
1445
- (candidate) => candidate.prunableReason !== void 0 && candidate.detached
1446
- )) {
1378
+ for (const record of records.filter((candidate) => candidate.prunableReason !== void 0 && candidate.detached)) {
1447
1379
  await assertDetachedHeadIsDurable(pi, ctx, record);
1448
1380
  }
1449
1381
  const preview = await prunePreview(pi, ctx.cwd, ctx.signal);
@@ -1463,9 +1395,7 @@ ${safePreview}`, "warning");
1463
1395
  return;
1464
1396
  }
1465
1397
  const latest = await listWorktrees(pi, ctx.cwd, ctx.signal);
1466
- for (const record of latest.filter(
1467
- (candidate) => candidate.prunableReason !== void 0 && candidate.detached
1468
- )) {
1398
+ for (const record of latest.filter((candidate) => candidate.prunableReason !== void 0 && candidate.detached)) {
1469
1399
  await assertDetachedHeadIsDurable(pi, ctx, record);
1470
1400
  }
1471
1401
  const beforePreviewHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
@@ -1478,19 +1408,11 @@ ${safePreview}`, "warning");
1478
1408
  throw new Error("Stale worktree metadata changed after confirmation; run prune again.");
1479
1409
  }
1480
1410
  const output = await pruneWorktrees(pi, ctx.cwd, ctx.signal);
1481
- safeNotify(
1482
- ctx,
1483
- output ? `Pruned stale worktree metadata:
1484
- ${output}` : "Pruned stale worktree metadata.",
1485
- "info"
1486
- );
1411
+ safeNotify(ctx, output ? `Pruned stale worktree metadata:
1412
+ ${output}` : "Pruned stale worktree metadata.", "info");
1487
1413
  }
1488
1414
  async function assertAdministrativeHistoryUnchanged(pi, ctx, selectedPath, approvedAdministrativePath, approvedHistoryRisks) {
1489
- const latestAdministrativePath = await worktreeAdministrativeDirectory(
1490
- pi,
1491
- selectedPath,
1492
- ctx.signal
1493
- );
1415
+ const latestAdministrativePath = await worktreeAdministrativeDirectory(pi, selectedPath, ctx.signal);
1494
1416
  const latestHistoryRisks = historyRisks(
1495
1417
  selectedPath,
1496
1418
  await unreachableAdministrativeHistoryOids(pi, ctx, latestAdministrativePath)
@@ -1522,10 +1444,7 @@ async function inspectAdministrativePruneCandidates(pi, ctx) {
1522
1444
  );
1523
1445
  }
1524
1446
  risks.push(
1525
- ...historyRisks(
1526
- candidate.id,
1527
- await unreachableAdministrativeHistoryOids(pi, ctx, candidate.administrativePath)
1528
- )
1447
+ ...historyRisks(candidate.id, await unreachableAdministrativeHistoryOids(pi, ctx, candidate.administrativePath))
1529
1448
  );
1530
1449
  }
1531
1450
  return normalizeAdministrativeHistoryRisks(risks);
@@ -1549,9 +1468,7 @@ function sameAdministrativeHistoryRisks(left, right) {
1549
1468
  }
1550
1469
  function formatAdministrativeRecoveryWarning(risks) {
1551
1470
  if (risks.length === 0) return "";
1552
- const entries = risks.map(
1553
- (risk) => `${stripTerminalControls(risk.label)}: ${risk.oids.map(stripTerminalControls).join(", ")}`
1554
- ).join("; ");
1471
+ const entries = risks.map((risk) => `${stripTerminalControls(risk.label)}: ${risk.oids.map(stripTerminalControls).join(", ")}`).join("; ");
1555
1472
  return ` Administrative recovery warning: these commits are not reachable from a branch, tag, or remote ref: ${entries}. Discarding their recovery pointers means they may later be garbage-collected.`;
1556
1473
  }
1557
1474
  function classifyRemovalInventory(lines) {
@@ -1578,8 +1495,7 @@ ${ignored.map(stripTerminalControls).join("\n")}`;
1578
1495
  }
1579
1496
  async function assertDetachedHeadIsDurable(pi, ctx, record) {
1580
1497
  if (!record.detached) return;
1581
- if (!record.head)
1582
- throw new Error(`Detached worktree ${record.path} has no HEAD object; refusing.`);
1498
+ if (!record.head) throw new Error(`Detached worktree ${record.path} has no HEAD object; refusing.`);
1583
1499
  const refs = await durableRefsContaining(pi, ctx.cwd, record.head, ctx.signal);
1584
1500
  if (refs.length === 0) {
1585
1501
  throw new Error(
@@ -1808,12 +1724,7 @@ function createWorktreeSettingsRuntime(options = {}) {
1808
1724
  state = { ...state, warning: latest.warning, canSave: false };
1809
1725
  throw new Error(`Fix the pi-worktree settings file at ${getPath()} before changing it.`);
1810
1726
  }
1811
- await saveWorktreeSettings(
1812
- latest.document ?? {},
1813
- configuredRoot,
1814
- getPath(),
1815
- options.operations
1816
- );
1727
+ await saveWorktreeSettings(latest.document ?? {}, configuredRoot, getPath(), options.operations);
1817
1728
  state = {
1818
1729
  effectiveRoot,
1819
1730
  source: configuredRoot === void 0 ? "default" : "user",