@firstpick/pi-package-webui 0.6.4 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/pi-webui.mjs CHANGED
@@ -40,9 +40,11 @@ import {
40
40
  WORKTREE_ERROR_CODES,
41
41
  createGitWorktree,
42
42
  gitWorktreeErrorPayload,
43
+ isGitLockFailure,
43
44
  listGitWorktrees,
44
45
  openGitWorktree,
45
46
  pathInside,
47
+ pruneGitWorktrees,
46
48
  removeGitWorktree,
47
49
  } from "../lib/git-worktrees.mjs";
48
50
 
@@ -1116,17 +1118,21 @@ function runCommand(command, args, { cwd, timeoutMs = 2000, maxOutputLength = 20
1116
1118
  return new Promise((resolve) => {
1117
1119
  const child = spawn(command, args, {
1118
1120
  cwd,
1121
+ // LC_ALL=C keeps tool output in English so error classification works
1122
+ // regardless of locale.
1123
+ env: { ...process.env, LC_ALL: "C" },
1119
1124
  stdio: ["ignore", "pipe", "pipe"],
1120
1125
  windowsHide: true,
1121
1126
  });
1122
1127
  let stdout = "";
1123
1128
  let stderr = "";
1129
+ let stdoutTruncated = false;
1124
1130
  let settled = false;
1125
1131
  const finish = (result) => {
1126
1132
  if (settled) return;
1127
1133
  settled = true;
1128
1134
  clearTimeout(timeout);
1129
- resolve(result);
1135
+ resolve({ stdoutTruncated, ...result });
1130
1136
  };
1131
1137
  const timeout = setTimeout(() => {
1132
1138
  child.kill("SIGKILL");
@@ -1134,7 +1140,10 @@ function runCommand(command, args, { cwd, timeoutMs = 2000, maxOutputLength = 20
1134
1140
  }, timeoutMs);
1135
1141
  child.stdout.on("data", (chunk) => {
1136
1142
  stdout += String(chunk);
1137
- if (stdout.length > maxOutputLength) stdout = stdout.slice(-maxOutputLength);
1143
+ if (stdout.length > maxOutputLength) {
1144
+ stdout = stdout.slice(-maxOutputLength);
1145
+ stdoutTruncated = true;
1146
+ }
1138
1147
  });
1139
1148
  child.stderr.on("data", (chunk) => {
1140
1149
  stderr += String(chunk);
@@ -3943,6 +3952,7 @@ let activeGitWorkflowProcess = null;
3943
3952
  const GIT_CHANGES_COMMAND_TIMEOUT_MS = 5000;
3944
3953
  const GIT_CHANGES_DIFF_MAX_OUTPUT = 500_000;
3945
3954
  const GIT_PULL_TIMEOUT_MS = 15 * 60 * 1000;
3955
+ const GIT_STATUS_KIND_RANK = Object.freeze({ changed: 0, untracked: 1, modified: 2, staged: 3, conflicted: 4 });
3946
3956
 
3947
3957
  async function getGitRoot(cwd) {
3948
3958
  const result = await runCommand("git", ["rev-parse", "--show-toplevel"], { cwd, timeoutMs: 2000 });
@@ -3952,9 +3962,11 @@ async function getGitRoot(cwd) {
3952
3962
  return path.resolve(result.stdout.trim());
3953
3963
  }
3954
3964
 
3955
- async function runGitReadCommand(root, args, { timeoutMs = GIT_CHANGES_COMMAND_TIMEOUT_MS, maxOutputLength = GIT_CHANGES_DIFF_MAX_OUTPUT } = {}) {
3965
+ async function runGitReadCommandDetailed(root, args, { timeoutMs = GIT_CHANGES_COMMAND_TIMEOUT_MS, maxOutputLength = GIT_CHANGES_DIFF_MAX_OUTPUT } = {}) {
3956
3966
  const result = await runCommand("git", args, { cwd: root, timeoutMs, maxOutputLength });
3957
- if (result.exitCode === 0 && !result.timedOut && !result.error) return result.stdout;
3967
+ if (result.exitCode === 0 && !result.timedOut && !result.error) {
3968
+ return { output: result.stdout, truncated: result.stdoutTruncated === true, capBytes: maxOutputLength };
3969
+ }
3958
3970
  const command = formatGitCommand(args);
3959
3971
  const message = result.timedOut
3960
3972
  ? `${command} timed out`
@@ -3962,6 +3974,10 @@ async function runGitReadCommand(root, args, { timeoutMs = GIT_CHANGES_COMMAND_T
3962
3974
  throw new Error(String(message).trim());
3963
3975
  }
3964
3976
 
3977
+ async function runGitReadCommand(root, args, options = {}) {
3978
+ return (await runGitReadCommandDetailed(root, args, options)).output;
3979
+ }
3980
+
3965
3981
  function gitBranchFromPorcelainStatus(statusText) {
3966
3982
  for (const line of String(statusText || "").split(/\r?\n/)) {
3967
3983
  if (!line.startsWith("# branch.head ")) continue;
@@ -4003,6 +4019,118 @@ function summarizeGitPorcelainStatus(statusText) {
4003
4019
  return summary;
4004
4020
  }
4005
4021
 
4022
+ function normalizeGitStatusPath(value = "") {
4023
+ return String(value || "").replace(/\\/g, "/").replace(/^\.\/+/, "").replace(/\/+$/g, "");
4024
+ }
4025
+
4026
+ function gitStatusKindFromPorcelainEntry(entry = {}) {
4027
+ const x = entry.x || " ";
4028
+ const y = entry.y || " ";
4029
+ if (x === "?" && y === "?") return "untracked";
4030
+ if (x === "U" || y === "U" || (x === "A" && y === "A") || (x === "D" && y === "D")) return "conflicted";
4031
+ if (x !== " " && x !== "?" && x !== ".") return "staged";
4032
+ if (y !== " " && y !== "?" && y !== ".") return "modified";
4033
+ return "changed";
4034
+ }
4035
+
4036
+ function gitStatusLabelFromPorcelainEntry(entry = {}) {
4037
+ const x = entry.x || " ";
4038
+ const y = entry.y || " ";
4039
+ if (x === "?" && y === "?") return "??";
4040
+ return `${x}${y}`.replace(/\s/g, "").trim() || "•";
4041
+ }
4042
+
4043
+ function mergeGitStatusIndexEntry(index, repoPath, patch = {}) {
4044
+ const key = normalizeGitStatusPath(repoPath);
4045
+ if (!key) return;
4046
+ const existing = index.get(key) || { changed: true, kind: "changed", status: "", direct: false, changedDescendants: 0 };
4047
+ const existingRank = GIT_STATUS_KIND_RANK[existing.kind] ?? 0;
4048
+ const nextRank = GIT_STATUS_KIND_RANK[patch.kind] ?? 0;
4049
+ index.set(key, {
4050
+ changed: true,
4051
+ kind: nextRank > existingRank ? patch.kind : existing.kind,
4052
+ status: patch.direct === true ? (patch.status || existing.status || "") : (existing.status || ""),
4053
+ direct: existing.direct === true || patch.direct === true,
4054
+ changedDescendants: (Number(existing.changedDescendants || 0) || 0) + (Number(patch.changedDescendants || 0) || 0),
4055
+ });
4056
+ }
4057
+
4058
+ function addGitStatusAncestorEntries(index, repoPath, kind) {
4059
+ const parts = normalizeGitStatusPath(repoPath).split("/").filter(Boolean);
4060
+ parts.pop();
4061
+ let current = "";
4062
+ for (const part of parts) {
4063
+ current = current ? `${current}/${part}` : part;
4064
+ mergeGitStatusIndexEntry(index, current, { kind, changedDescendants: 1 });
4065
+ }
4066
+ }
4067
+
4068
+ function buildGitStatusIndexFromPorcelain(statusText = "") {
4069
+ const index = new Map();
4070
+ for (const entry of parseGitPorcelainZEntries(statusText)) {
4071
+ const filePath = normalizeGitStatusPath(entry.path);
4072
+ if (!filePath) continue;
4073
+ const kind = gitStatusKindFromPorcelainEntry(entry);
4074
+ mergeGitStatusIndexEntry(index, filePath, { kind, status: gitStatusLabelFromPorcelainEntry(entry), direct: true });
4075
+ addGitStatusAncestorEntries(index, filePath, kind);
4076
+ if (entry.oldPath) addGitStatusAncestorEntries(index, entry.oldPath, kind);
4077
+ }
4078
+ return index;
4079
+ }
4080
+
4081
+ async function readWorkspaceGitStatusIndex(workspaceRoot) {
4082
+ try {
4083
+ const root = await getGitRoot(workspaceRoot);
4084
+ const statusText = await runGitReadCommand(root, ["status", "--porcelain=v1", "-z", "--untracked-files=all"], { maxOutputLength: 120_000 });
4085
+ return { root, entries: buildGitStatusIndexFromPorcelain(statusText) };
4086
+ } catch {
4087
+ return null;
4088
+ }
4089
+ }
4090
+
4091
+ function gitStatusForWorkspaceEntry(workspaceRoot, entry, gitStatus) {
4092
+ if (!gitStatus?.root || !gitStatus.entries?.size || !entry?.path) return null;
4093
+ const absolute = path.resolve(workspaceRoot, entry.path);
4094
+ if (absolute !== gitStatus.root && !pathInside(gitStatus.root, absolute)) return null;
4095
+ const repoPath = normalizeGitStatusPath(path.relative(gitStatus.root, absolute).split(path.sep).join("/"));
4096
+ const status = gitStatus.entries.get(repoPath);
4097
+ if (!status?.changed) return null;
4098
+ return {
4099
+ changed: true,
4100
+ kind: status.kind || "changed",
4101
+ status: status.status || "",
4102
+ direct: status.direct === true,
4103
+ changedDescendants: Number(status.changedDescendants || 0) || 0,
4104
+ };
4105
+ }
4106
+
4107
+ function withFileTreeGitStatus(entries = [], workspaceRoot, gitStatus) {
4108
+ if (!gitStatus?.entries?.size) return entries;
4109
+ return entries.map((entry) => {
4110
+ const status = gitStatusForWorkspaceEntry(workspaceRoot, entry, gitStatus);
4111
+ return status ? { ...entry, gitStatus: status } : entry;
4112
+ });
4113
+ }
4114
+
4115
+ function fileTreeGitStatusPayload(workspaceRoot, gitStatus) {
4116
+ if (!gitStatus?.root || !gitStatus.entries?.size) return null;
4117
+ const root = path.resolve(workspaceRoot);
4118
+ const entries = [];
4119
+ for (const [repoPath, status] of gitStatus.entries.entries()) {
4120
+ const absolute = path.resolve(gitStatus.root, repoPath);
4121
+ if (absolute !== root && !pathInside(root, absolute)) continue;
4122
+ entries.push({
4123
+ path: path.relative(root, absolute).split(path.sep).join("/"),
4124
+ changed: true,
4125
+ kind: status.kind || "changed",
4126
+ status: status.status || "",
4127
+ direct: status.direct === true,
4128
+ changedDescendants: Number(status.changedDescendants || 0) || 0,
4129
+ });
4130
+ }
4131
+ return { root: gitStatus.root, entries };
4132
+ }
4133
+
4006
4134
  function resolveGitRelativePath(root, relativePath) {
4007
4135
  const normalized = String(relativePath || "").trim();
4008
4136
  if (!normalized || normalized.includes("\0")) throw new Error("Invalid git path");
@@ -4067,23 +4195,31 @@ async function gitUpstreamRef(root) {
4067
4195
 
4068
4196
  async function readGitIncomingChanges(root, summary) {
4069
4197
  const upstream = await gitUpstreamRef(root);
4198
+ const ahead = Number(summary?.ahead || 0) || 0;
4199
+ const behind = Number(summary?.behind || 0) || 0;
4200
+ const diverged = ahead > 0 && behind > 0;
4070
4201
  const remote = {
4071
4202
  upstream,
4072
- behind: Number(summary?.behind || 0) || 0,
4073
- canPull: !!upstream && (Number(summary?.behind || 0) || 0) > 0,
4203
+ ahead,
4204
+ behind,
4205
+ diverged,
4206
+ // Fast-forward pull is only possible when we are strictly behind.
4207
+ canPull: !!upstream && behind > 0 && !diverged,
4074
4208
  };
4075
- if (!remote.canPull) return { remote, section: null };
4209
+ if (!upstream || behind <= 0) return { remote, section: null };
4076
4210
 
4077
4211
  const diffArgs = ["diff", "--no-ext-diff", "--no-color", "--find-renames", "--unified=0", "--src-prefix=a/", "--dst-prefix=b/", "HEAD..@{upstream}"];
4078
4212
  try {
4079
- const diff = await runGitReadCommand(root, diffArgs);
4213
+ const diff = await runGitReadCommandDetailed(root, diffArgs);
4080
4214
  return {
4081
4215
  remote,
4082
4216
  section: {
4083
4217
  key: "incoming",
4084
4218
  label: `Incoming from ${upstream}`,
4085
4219
  command: `git diff --unified=0 HEAD..${upstream}`,
4086
- diff: diff.trimEnd(),
4220
+ diff: diff.output.trimEnd(),
4221
+ truncated: diff.truncated,
4222
+ capBytes: diff.capBytes,
4087
4223
  },
4088
4224
  };
4089
4225
  } catch (error) {
@@ -4093,10 +4229,13 @@ async function readGitIncomingChanges(root, summary) {
4093
4229
 
4094
4230
  async function pullGitChanges(cwd) {
4095
4231
  const root = await getGitRoot(cwd);
4096
- const payload = gitWorkflowCommandPayload(await runGitWorkflowCommand(["pull", "--ff-only"], { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS }));
4232
+ const payload = await runGuardedGitMutation(["pull", "--ff-only"], { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS });
4097
4233
  if (payload.data) payload.data.root = root;
4098
4234
  if (payload.ok) payload.data.changes = await readGitChanges(root);
4099
- else payload.error = (payload.data?.stderr || payload.data?.stdout || payload.error || "git pull --ff-only failed").trim();
4235
+ else {
4236
+ payload.error = (payload.data?.stderr || payload.data?.stdout || payload.error || "git pull --ff-only failed").trim();
4237
+ applyGitSyncFailure(payload);
4238
+ }
4100
4239
  return payload;
4101
4240
  }
4102
4241
 
@@ -4106,8 +4245,8 @@ async function readGitChanges(cwd) {
4106
4245
  const [statusText, porcelainStatusText, unstagedDiff, stagedDiff, untrackedText] = await Promise.all([
4107
4246
  runGitReadCommand(root, ["status", "--short", "--branch", "--untracked-files=all"], { maxOutputLength: 120_000 }),
4108
4247
  runGitReadCommand(root, ["status", "--porcelain=2", "--branch", "--untracked-files=all"], { maxOutputLength: 120_000 }),
4109
- runGitReadCommand(root, diffArgs),
4110
- runGitReadCommand(root, ["diff", "--cached", "--no-ext-diff", "--no-color", "--find-renames", "--unified=0", "--src-prefix=a/", "--dst-prefix=b/"]),
4248
+ runGitReadCommandDetailed(root, diffArgs),
4249
+ runGitReadCommandDetailed(root, ["diff", "--cached", "--no-ext-diff", "--no-color", "--find-renames", "--unified=0", "--src-prefix=a/", "--dst-prefix=b/"]),
4111
4250
  runGitReadCommand(root, ["ls-files", "--others", "--exclude-standard"], { maxOutputLength: 120_000 }),
4112
4251
  ]);
4113
4252
  const summary = summarizeGitPorcelainStatus(porcelainStatusText);
@@ -4124,13 +4263,670 @@ async function readGitChanges(cwd) {
4124
4263
  status: statusText.trimEnd(),
4125
4264
  sections: [
4126
4265
  incoming.section,
4127
- { key: "staged", label: "Staged", command: "git diff --cached --unified=0", diff: stagedDiff.trimEnd() },
4128
- { key: "unstaged", label: "Unstaged", command: "git diff --unified=0", diff: unstagedDiff.trimEnd() },
4266
+ { key: "staged", label: "Staged", command: "git diff --cached --unified=0", diff: stagedDiff.output.trimEnd(), truncated: stagedDiff.truncated, capBytes: stagedDiff.capBytes },
4267
+ { key: "unstaged", label: "Unstaged", command: "git diff --unified=0", diff: unstagedDiff.output.trimEnd(), truncated: unstagedDiff.truncated, capBytes: unstagedDiff.capBytes },
4129
4268
  ].filter(Boolean),
4130
4269
  untracked,
4131
4270
  };
4132
4271
  }
4133
4272
 
4273
+ const GIT_LOCK_RETRY_ATTEMPTS = 3;
4274
+ const GIT_LOCK_RETRY_DELAY_MS = 250;
4275
+ const GIT_FETCH_TIMEOUT_MS = 2 * 60 * 1000;
4276
+ const GIT_CONFLICT_PREVIEW_MAX_BYTES = 200_000;
4277
+ const GIT_STASH_PATCH_MAX_OUTPUT = 200_000;
4278
+ const PROTECTED_GIT_BRANCHES = new Set(["main", "master"]);
4279
+
4280
+ const sleepMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4281
+
4282
+ function requireConfirmed(body, action) {
4283
+ if (body?.confirmed !== true) throw makeHttpError(409, `${action} requires confirmed: true.`);
4284
+ }
4285
+
4286
+ // Retry transient index.lock contention before reporting failure; the shared
4287
+ // isGitLockFailure classifier keeps this consistent with worktree mutations.
4288
+ async function runGitMutationCommand(args, options = {}) {
4289
+ let result;
4290
+ for (let attempt = 0; attempt < GIT_LOCK_RETRY_ATTEMPTS; attempt++) {
4291
+ result = await runGitWorkflowCommand(args, options);
4292
+ const ok = result.exitCode === 0 && !result.timedOut && !result.cancelled && !result.error;
4293
+ if (ok || !isGitLockFailure(result)) return result;
4294
+ if (attempt < GIT_LOCK_RETRY_ATTEMPTS - 1) await sleepMs(GIT_LOCK_RETRY_DELAY_MS * (attempt + 1));
4295
+ }
4296
+ return result;
4297
+ }
4298
+
4299
+ function gitMutationPayload(result) {
4300
+ const payload = gitWorkflowCommandPayload(result);
4301
+ if (!payload.ok) {
4302
+ if (isGitLockFailure(result)) {
4303
+ payload.code = "REPO_BUSY";
4304
+ payload.hint = "Another git process is using this repository. Retry once it finishes.";
4305
+ }
4306
+ payload.error = String(result?.stderr || result?.stdout || payload.error || "git command failed").trim();
4307
+ }
4308
+ return payload;
4309
+ }
4310
+
4311
+ async function runGuardedGitMutation(args, options = {}) {
4312
+ try {
4313
+ return gitMutationPayload(await runGitMutationCommand(args, options));
4314
+ } catch (error) {
4315
+ if (/already running/i.test(error?.message || "")) {
4316
+ return { ok: false, code: "REPO_BUSY", error: sanitizeError(error), hint: "Another git workflow command is already running in the Web UI." };
4317
+ }
4318
+ throw error;
4319
+ }
4320
+ }
4321
+
4322
+ // Turn raw git remote-operation stderr into an actionable state. Returns null
4323
+ // when no known pattern matches (caller keeps the raw error).
4324
+ function classifyGitSyncFailure(result, { push = false } = {}) {
4325
+ const text = `${result?.stderr || ""}\n${result?.stdout || ""}`.toLowerCase();
4326
+ if (result?.timedOut) return { code: "NETWORK", hint: "The remote did not respond before the timeout. Check connectivity and retry." };
4327
+ if (isGitLockFailure(result)) return { code: "REPO_BUSY", hint: "Another git process is using this repository. Retry once it finishes." };
4328
+ if (/terminal prompts disabled|authentication failed|permission denied|access denied|could not read username|could not read password|publickey|invalid credentials/.test(text)) {
4329
+ return { code: "AUTH", hint: "Authentication failed and interactive prompts are disabled in the Web UI. Refresh your credentials or SSH agent in a terminal, then retry." };
4330
+ }
4331
+ if (/could not resolve host|failed to connect|connection (?:refused|reset|timed out)|network is unreachable|operation timed out/.test(text)) {
4332
+ return { code: "NETWORK", hint: "The remote could not be reached. Check connectivity and retry." };
4333
+ }
4334
+ if (push && /protected branch|gh006/.test(text)) {
4335
+ return { code: "PROTECTED_BRANCH", hint: "The remote refused the push because the branch is protected. Push to a feature branch and open a PR instead." };
4336
+ }
4337
+ if (push && /\[rejected\]|non-fast-forward|fetch first|updates were rejected/.test(text)) {
4338
+ return { code: "NON_FAST_FORWARD", hint: "The remote has commits you don't have. Fetch and review the incoming diff, then integrate before pushing." };
4339
+ }
4340
+ if (push && /has no upstream branch/.test(text)) {
4341
+ return { code: "NO_UPSTREAM", hint: "The current branch has no upstream. Push with 'set upstream' to publish it." };
4342
+ }
4343
+ if (!push && /not possible to fast-forward|divergent branches|need to specify how to reconcile/.test(text)) {
4344
+ return { code: "DIVERGED", hint: "Local and remote branches have diverged. Fetch, review the incoming diff, then merge or rebase explicitly — or integrate in a worktree." };
4345
+ }
4346
+ if (!push && /no tracking information/.test(text)) {
4347
+ return { code: "NO_UPSTREAM", hint: "The current branch has no upstream to pull from. Set one or pull with an explicit remote/branch." };
4348
+ }
4349
+ if (/would be overwritten/.test(text)) {
4350
+ return { code: "DIRTY_WORKTREE", hint: "Local changes would be overwritten. Stash or commit them first." };
4351
+ }
4352
+ if (/conflict/.test(text)) {
4353
+ return { code: "CONFLICTS", hint: "Conflicts were created. Resolve them in the conflicts panel, then continue or abort the operation." };
4354
+ }
4355
+ return null;
4356
+ }
4357
+
4358
+ function applyGitSyncFailure(payload, { push = false } = {}) {
4359
+ if (payload.ok || payload.code) return payload;
4360
+ const classified = classifyGitSyncFailure(payload.data, { push });
4361
+ if (classified) {
4362
+ payload.code = classified.code;
4363
+ payload.hint = classified.hint;
4364
+ }
4365
+ return payload;
4366
+ }
4367
+
4368
+ async function fetchGitChanges(cwd) {
4369
+ const root = await getGitRoot(cwd);
4370
+ const payload = await runGuardedGitMutation(
4371
+ ["-c", "credential.interactive=false", "fetch", "--prune"],
4372
+ { cwd: root, timeoutMs: GIT_FETCH_TIMEOUT_MS, label: "git fetch --prune" },
4373
+ );
4374
+ if (payload.data) payload.data.root = root;
4375
+ if (payload.ok) {
4376
+ // git fetch reports ref updates on stderr.
4377
+ payload.data.summary = `${payload.data.stderr || ""}\n${payload.data.stdout || ""}`.trim();
4378
+ payload.data.changes = await readGitChanges(root);
4379
+ } else {
4380
+ applyGitSyncFailure(payload);
4381
+ }
4382
+ return payload;
4383
+ }
4384
+
4385
+ async function integrateGitUpstream(cwd, body = {}) {
4386
+ const mode = String(body.mode || "").trim();
4387
+ if (!["merge", "rebase"].includes(mode)) throw makeHttpError(400, "mode must be 'merge' or 'rebase'");
4388
+ requireConfirmed(body, `Running git ${mode} against the upstream`);
4389
+ const root = await getGitRoot(cwd);
4390
+ const upstream = await gitUpstreamRef(root);
4391
+ if (!upstream) throw makeHttpError(409, "No upstream is configured for the current branch");
4392
+ const args = mode === "merge" ? ["merge", "--no-edit", "@{upstream}"] : ["-c", "core.editor=true", "rebase", "@{upstream}"];
4393
+ const payload = await runGuardedGitMutation(args, { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS, label: `git ${mode} ${upstream}` });
4394
+ if (payload.data) {
4395
+ payload.data.root = root;
4396
+ payload.data.upstream = upstream;
4397
+ payload.data.mode = mode;
4398
+ }
4399
+ if (payload.ok) payload.data.changes = await readGitChanges(root);
4400
+ else applyGitSyncFailure(payload);
4401
+ return payload;
4402
+ }
4403
+
4404
+ // ---- Git operation (merge/rebase/cherry-pick/revert/bisect) lifecycle ----
4405
+
4406
+ async function pathEntryExists(target) {
4407
+ try {
4408
+ await stat(target);
4409
+ return true;
4410
+ } catch {
4411
+ return false;
4412
+ }
4413
+ }
4414
+
4415
+ async function gitDirPath(root) {
4416
+ const out = await runGitReadCommand(root, ["rev-parse", "--git-dir"], { maxOutputLength: 10_000 });
4417
+ const dir = out.trim();
4418
+ return path.isAbsolute(dir) ? dir : path.resolve(root, dir);
4419
+ }
4420
+
4421
+ async function detectGitOperationKind(root) {
4422
+ const gitDir = await gitDirPath(root);
4423
+ if ((await pathEntryExists(path.join(gitDir, "rebase-merge"))) || (await pathEntryExists(path.join(gitDir, "rebase-apply")))) return "rebase";
4424
+ if (await pathEntryExists(path.join(gitDir, "MERGE_HEAD"))) return "merge";
4425
+ if (await pathEntryExists(path.join(gitDir, "CHERRY_PICK_HEAD"))) return "cherry-pick";
4426
+ if (await pathEntryExists(path.join(gitDir, "REVERT_HEAD"))) return "revert";
4427
+ if (await pathEntryExists(path.join(gitDir, "BISECT_LOG"))) return "bisect";
4428
+ return null;
4429
+ }
4430
+
4431
+ function gitOperationCommands(kind) {
4432
+ switch (kind) {
4433
+ case "merge":
4434
+ return { continue: ["commit", "--no-edit"], abort: ["merge", "--abort"], skip: null };
4435
+ case "rebase":
4436
+ return { continue: ["-c", "core.editor=true", "rebase", "--continue"], abort: ["rebase", "--abort"], skip: ["-c", "core.editor=true", "rebase", "--skip"] };
4437
+ case "cherry-pick":
4438
+ return { continue: ["-c", "core.editor=true", "cherry-pick", "--continue"], abort: ["cherry-pick", "--abort"], skip: ["-c", "core.editor=true", "cherry-pick", "--skip"] };
4439
+ case "revert":
4440
+ return { continue: ["-c", "core.editor=true", "revert", "--continue"], abort: ["revert", "--abort"], skip: ["-c", "core.editor=true", "revert", "--skip"] };
4441
+ default:
4442
+ return null;
4443
+ }
4444
+ }
4445
+
4446
+ function parseGitConflictEntries(porcelainText) {
4447
+ const entries = [];
4448
+ for (const line of String(porcelainText || "").split(/\r?\n/)) {
4449
+ if (!line.startsWith("u ")) continue;
4450
+ // u XY sub m1 m2 m3 mW h1 h2 h3 path — 10 space-separated fields, then path.
4451
+ const fields = [];
4452
+ let start = 0;
4453
+ for (let index = 0; index < 10; index++) {
4454
+ const next = line.indexOf(" ", start);
4455
+ if (next === -1) break;
4456
+ fields.push(line.slice(start, next));
4457
+ start = next + 1;
4458
+ }
4459
+ fields.push(line.slice(start));
4460
+ const entryPath = fields[10] || "";
4461
+ if (entryPath) entries.push({ path: entryPath, status: fields[1] || "UU" });
4462
+ }
4463
+ return entries;
4464
+ }
4465
+
4466
+ function extractConflictMarkerHunks(content, { contextLines = 2, maxHunks = 8, maxLinesPerHunk = 80 } = {}) {
4467
+ const lines = content.split(/\r?\n/);
4468
+ const hunks = [];
4469
+ for (let index = 0; index < lines.length && hunks.length < maxHunks; index++) {
4470
+ if (!lines[index].startsWith("<<<<<<<")) continue;
4471
+ let end = index;
4472
+ while (end < lines.length - 1 && !lines[end].startsWith(">>>>>>>")) end++;
4473
+ const start = Math.max(0, index - contextLines);
4474
+ const stop = Math.min(lines.length - 1, end + contextLines);
4475
+ hunks.push({
4476
+ startLine: start + 1,
4477
+ truncated: stop - start + 1 > maxLinesPerHunk,
4478
+ lines: lines.slice(start, Math.min(stop + 1, start + maxLinesPerHunk)),
4479
+ });
4480
+ index = end;
4481
+ }
4482
+ return hunks;
4483
+ }
4484
+
4485
+ async function readGitConflictPreview(root, relPath) {
4486
+ try {
4487
+ const filePath = resolveGitRelativePath(root, relPath);
4488
+ const info = await stat(filePath).catch(() => null);
4489
+ if (!info) return { kind: "missing" };
4490
+ if (!info.isFile()) return { kind: "unsupported", size: info.size };
4491
+ if (info.size > GIT_CONFLICT_PREVIEW_MAX_BYTES) return { kind: "large", size: info.size };
4492
+ const buffer = await readFile(filePath);
4493
+ if (isLikelyBinaryBuffer(buffer)) return { kind: "binary", size: info.size };
4494
+ const content = buffer.toString("utf8");
4495
+ return {
4496
+ kind: "text",
4497
+ size: info.size,
4498
+ hasMarkers: /^<{7}(?: |$)/m.test(content),
4499
+ hunks: extractConflictMarkerHunks(content),
4500
+ };
4501
+ } catch (error) {
4502
+ return { kind: "error", error: sanitizeError(error) };
4503
+ }
4504
+ }
4505
+
4506
+ async function readGitOperationSnapshot(cwd) {
4507
+ const root = await getGitRoot(cwd);
4508
+ const porcelainText = await runGitReadCommand(root, ["status", "--porcelain=2", "--branch", "--untracked-files=all"], { maxOutputLength: 120_000 });
4509
+ const summary = summarizeGitPorcelainStatus(porcelainText);
4510
+ const kind = await detectGitOperationKind(root);
4511
+ const conflictEntries = parseGitConflictEntries(porcelainText);
4512
+ const conflicts = [];
4513
+ for (const entry of conflictEntries) {
4514
+ conflicts.push({ ...entry, preview: await readGitConflictPreview(root, entry.path) });
4515
+ }
4516
+ const commands = gitOperationCommands(kind);
4517
+ let bisect = null;
4518
+ if (kind === "bisect") {
4519
+ const log = await runGitReadCommand(root, ["bisect", "log"], { maxOutputLength: 60_000 }).catch(() => "");
4520
+ bisect = { log: log.trimEnd().split(/\r?\n/).slice(-20).join("\n") };
4521
+ }
4522
+ return {
4523
+ root,
4524
+ branch: gitBranchFromPorcelainStatus(porcelainText),
4525
+ operation: kind,
4526
+ summary,
4527
+ conflicts,
4528
+ canContinue: Boolean(kind) && kind !== "bisect" && conflictEntries.length === 0,
4529
+ canSkip: Boolean(commands?.skip),
4530
+ commands: commands
4531
+ ? {
4532
+ continue: formatGitCommand(commands.continue.filter((arg) => arg !== "-c" && arg !== "core.editor=true")),
4533
+ abort: formatGitCommand(commands.abort),
4534
+ ...(commands.skip ? { skip: formatGitCommand(commands.skip.filter((arg) => arg !== "-c" && arg !== "core.editor=true")) } : {}),
4535
+ }
4536
+ : null,
4537
+ bisect,
4538
+ generatedAt: new Date().toISOString(),
4539
+ };
4540
+ }
4541
+
4542
+ async function gitOperationStageFile(cwd, body = {}) {
4543
+ const root = await getGitRoot(cwd);
4544
+ const kind = await detectGitOperationKind(root);
4545
+ if (!kind) throw makeHttpError(409, "No git operation is in progress");
4546
+ const rel = normalizeGitRelativePath(root, body.path);
4547
+ const payload = await runGuardedGitMutation(["add", "--", rel], { cwd: root, label: `git add -- ${rel}` });
4548
+ if (payload.data) payload.data.root = root;
4549
+ if (payload.ok) payload.data.operation = await readGitOperationSnapshot(root);
4550
+ return payload;
4551
+ }
4552
+
4553
+ async function gitOperationAction(cwd, action, body = {}) {
4554
+ const root = await getGitRoot(cwd);
4555
+ const kind = await detectGitOperationKind(root);
4556
+ if (!kind) throw makeHttpError(409, "No git operation is in progress");
4557
+ if (kind === "bisect") throw makeHttpError(409, "Bisect is controlled through /api/git-operation/bisect");
4558
+ const commands = gitOperationCommands(kind);
4559
+
4560
+ let args;
4561
+ if (action === "continue") {
4562
+ const porcelainText = await runGitReadCommand(root, ["status", "--porcelain=2"], { maxOutputLength: 120_000 });
4563
+ if (parseGitConflictEntries(porcelainText).length > 0) {
4564
+ return { ok: false, code: "UNMERGED_PATHS", error: "Unmerged paths remain. Resolve and stage every conflicted file before continuing." };
4565
+ }
4566
+ args = commands.continue;
4567
+ } else if (action === "skip") {
4568
+ if (!commands.skip) throw makeHttpError(409, `git ${kind} does not support skip`);
4569
+ args = commands.skip;
4570
+ } else if (action === "abort") {
4571
+ requireConfirmed(body, `Aborting the ${kind} operation discards its in-progress state and`);
4572
+ args = commands.abort;
4573
+ } else {
4574
+ throw makeHttpError(400, "Unknown git operation action");
4575
+ }
4576
+
4577
+ const payload = await runGuardedGitMutation(args, { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS });
4578
+ if (payload.data) {
4579
+ payload.data.root = root;
4580
+ payload.data.kind = kind;
4581
+ }
4582
+ if (payload.ok) payload.data.operation = await readGitOperationSnapshot(root);
4583
+ else applyGitSyncFailure(payload);
4584
+ return payload;
4585
+ }
4586
+
4587
+ const GIT_BISECT_VERDICTS = new Set(["good", "bad", "old", "new", "skip", "reset"]);
4588
+
4589
+ async function gitBisectAction(cwd, body = {}) {
4590
+ const verdict = String(body.verdict || "").trim().toLowerCase();
4591
+ if (!GIT_BISECT_VERDICTS.has(verdict)) throw makeHttpError(400, "verdict must be one of good, bad, old, new, skip, reset");
4592
+ const root = await getGitRoot(cwd);
4593
+ const kind = await detectGitOperationKind(root);
4594
+ if (kind !== "bisect") throw makeHttpError(409, "No git bisect is in progress");
4595
+ if (verdict === "reset") requireConfirmed(body, "Resetting the bisect session");
4596
+ const payload = await runGuardedGitMutation(["bisect", verdict], { cwd: root });
4597
+ if (payload.data) payload.data.root = root;
4598
+ if (payload.ok) payload.data.operation = await readGitOperationSnapshot(root);
4599
+ return payload;
4600
+ }
4601
+
4602
+ // ---- Stash ----
4603
+
4604
+ function cleanGitStashRef(value) {
4605
+ const ref = String(value || "").trim();
4606
+ if (!/^stash@\{\d{1,4}\}$/.test(ref)) throw makeHttpError(400, "stash ref must look like stash@{0}");
4607
+ return ref;
4608
+ }
4609
+
4610
+ async function readGitStashes(cwd) {
4611
+ const root = await getGitRoot(cwd);
4612
+ const out = await runGitReadCommand(root, ["stash", "list", "--format=%gd%x09%at%x09%gs"], { maxOutputLength: 120_000 });
4613
+ const stashes = out
4614
+ .split(/\r?\n/)
4615
+ .filter(Boolean)
4616
+ .map((line) => {
4617
+ const [ref, epoch, ...subject] = line.split("\t");
4618
+ return { ref: ref || "", epochSeconds: Number.parseInt(epoch || "0", 10) || 0, subject: subject.join("\t") };
4619
+ })
4620
+ .filter((entry) => entry.ref);
4621
+ return { root, stashes, generatedAt: new Date().toISOString() };
4622
+ }
4623
+
4624
+ async function readGitStashPreview(cwd, requestedRef) {
4625
+ const root = await getGitRoot(cwd);
4626
+ const ref = cleanGitStashRef(requestedRef);
4627
+ const [statText, patchText] = await Promise.all([
4628
+ runGitReadCommand(root, ["stash", "show", "--include-untracked", "--stat", ref], { maxOutputLength: 120_000 }).catch((error) => `(${sanitizeError(error)})`),
4629
+ runGitReadCommand(root, ["stash", "show", "--include-untracked", "-p", ref], { maxOutputLength: GIT_STASH_PATCH_MAX_OUTPUT }).catch(() => ""),
4630
+ ]);
4631
+ return { root, ref, stat: statText.trimEnd(), patch: patchText.trimEnd() };
4632
+ }
4633
+
4634
+ async function saveGitStash(cwd, body = {}) {
4635
+ const root = await getGitRoot(cwd);
4636
+ const args = ["stash", "push"];
4637
+ if (body.includeUntracked === true) args.push("--include-untracked");
4638
+ if (body.message) args.push("-m", cleanGitCommitMessageInput(body.message));
4639
+ const payload = await runGuardedGitMutation(args, { cwd: root });
4640
+ if (payload.data) payload.data.root = root;
4641
+ if (payload.ok) payload.data.stashes = (await readGitStashes(root)).stashes;
4642
+ return payload;
4643
+ }
4644
+
4645
+ async function applyGitStash(cwd, body = {}, { pop = false } = {}) {
4646
+ const root = await getGitRoot(cwd);
4647
+ const ref = cleanGitStashRef(body.ref);
4648
+ const payload = await runGuardedGitMutation(["stash", pop ? "pop" : "apply", ref], { cwd: root });
4649
+ if (payload.data) {
4650
+ payload.data.root = root;
4651
+ payload.data.ref = ref;
4652
+ }
4653
+ if (payload.ok) payload.data.stashes = (await readGitStashes(root)).stashes;
4654
+ else if (!payload.code && /conflict/i.test(payload.error || "")) {
4655
+ payload.code = "CONFLICTS";
4656
+ payload.hint = pop
4657
+ ? "The stash conflicts with the working tree; git kept the stash entry. Resolve the conflicts, then drop the stash manually."
4658
+ : "The stash conflicts with the working tree. Resolve the conflicts or reset the working tree.";
4659
+ }
4660
+ return payload;
4661
+ }
4662
+
4663
+ async function dropGitStash(cwd, body = {}) {
4664
+ requireConfirmed(body, "Dropping a stash permanently deletes it and");
4665
+ const root = await getGitRoot(cwd);
4666
+ const ref = cleanGitStashRef(body.ref);
4667
+ const payload = await runGuardedGitMutation(["stash", "drop", ref], { cwd: root });
4668
+ if (payload.data) {
4669
+ payload.data.root = root;
4670
+ payload.data.ref = ref;
4671
+ }
4672
+ if (payload.ok) payload.data.stashes = (await readGitStashes(root)).stashes;
4673
+ return payload;
4674
+ }
4675
+
4676
+ // ---- File-level staging ----
4677
+
4678
+ async function stageGitFile(cwd, body = {}) {
4679
+ const root = await getGitRoot(cwd);
4680
+ const rel = normalizeGitRelativePath(root, body.path);
4681
+ const payload = await runGuardedGitMutation(["add", "--", rel], { cwd: root, label: `git add -- ${rel}` });
4682
+ if (payload.data) payload.data.root = root;
4683
+ if (payload.ok) payload.data.changes = await readGitChanges(root);
4684
+ return payload;
4685
+ }
4686
+
4687
+ async function unstageGitFile(cwd, body = {}) {
4688
+ const root = await getGitRoot(cwd);
4689
+ const rel = normalizeGitRelativePath(root, body.path);
4690
+ let payload = await runGuardedGitMutation(["restore", "--staged", "--", rel], { cwd: root, label: `git restore --staged -- ${rel}` });
4691
+ if (!payload.ok && /HEAD/.test(payload.error || "")) {
4692
+ // Unborn branch (no commit yet): restore --staged has no HEAD to restore from.
4693
+ payload = await runGuardedGitMutation(["rm", "--cached", "-r", "--", rel], { cwd: root, label: `git rm --cached -- ${rel}` });
4694
+ }
4695
+ if (payload.data) payload.data.root = root;
4696
+ if (payload.ok) payload.data.changes = await readGitChanges(root);
4697
+ return payload;
4698
+ }
4699
+
4700
+ async function discardGitFile(cwd, body = {}) {
4701
+ requireConfirmed(body, "Discarding file changes is destructive and");
4702
+ const root = await getGitRoot(cwd);
4703
+ const rel = normalizeGitRelativePath(root, body.path);
4704
+ const payload = await runGuardedGitMutation(["restore", "--", rel], { cwd: root, label: `git restore -- ${rel}` });
4705
+ if (payload.data) payload.data.root = root;
4706
+ if (payload.ok) payload.data.changes = await readGitChanges(root);
4707
+ return payload;
4708
+ }
4709
+
4710
+ async function deleteGitUntrackedFile(cwd, body = {}) {
4711
+ requireConfirmed(body, "Deleting an untracked file is destructive and");
4712
+ const root = await getGitRoot(cwd);
4713
+ const rel = normalizeGitRelativePath(root, body.path);
4714
+ const listed = await runGitReadCommand(root, ["ls-files", "--others", "--exclude-standard", "--", rel], { maxOutputLength: 120_000 });
4715
+ const files = listed.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
4716
+ if (!files.includes(rel)) throw makeHttpError(409, `Not an untracked file: ${rel}`);
4717
+ await rm(resolveGitRelativePath(root, rel));
4718
+ return { ok: true, data: { root, path: rel, deleted: true, changes: await readGitChanges(root) } };
4719
+ }
4720
+
4721
+ // ---- Undo / recovery ----
4722
+
4723
+ async function readGitUndoState(cwd) {
4724
+ const root = await getGitRoot(cwd);
4725
+ const [parentProbe, porcelainText, upstream, operation, lastLog] = await Promise.all([
4726
+ runCommand("git", ["rev-parse", "--verify", "--quiet", "HEAD~1"], { cwd: root, timeoutMs: 2000 }),
4727
+ runGitReadCommand(root, ["status", "--porcelain=2", "--branch"], { maxOutputLength: 120_000 }),
4728
+ gitUpstreamRef(root),
4729
+ detectGitOperationKind(root),
4730
+ runGitReadCommand(root, ["log", "-1", "--format=%h%x09%s"], { maxOutputLength: 10_000 }).catch(() => ""),
4731
+ ]);
4732
+ const summary = summarizeGitPorcelainStatus(porcelainText);
4733
+ const hasParent = parentProbe.exitCode === 0;
4734
+ const [lastHash = "", ...subjectParts] = lastLog.trim().split("\t");
4735
+ const lastSubject = subjectParts.join("\t");
4736
+ // With an upstream, "unpushed" means ahead > 0; without one nothing has been
4737
+ // published through this branch's tracking ref.
4738
+ const unpushed = upstream ? summary.ahead > 0 : true;
4739
+ return {
4740
+ root,
4741
+ hasParent,
4742
+ upstream,
4743
+ operation,
4744
+ summary,
4745
+ lastCommit: lastHash ? { hash: lastHash, subject: lastSubject } : null,
4746
+ canUndoLastCommit: hasParent && unpushed && !operation,
4747
+ canAmendMessage: Boolean(lastHash) && unpushed && !operation && summary.staged === 0,
4748
+ };
4749
+ }
4750
+
4751
+ async function undoLastGitCommit(cwd, body = {}) {
4752
+ requireConfirmed(body, "Undoing the last commit rewrites HEAD and");
4753
+ const state = await readGitUndoState(cwd);
4754
+ if (!state.hasParent) throw makeHttpError(409, "HEAD has no parent commit to undo to");
4755
+ if (state.operation) throw makeHttpError(409, `Cannot undo during a ${state.operation} operation`);
4756
+ if (!state.canUndoLastCommit) throw makeHttpError(409, "The last commit is already pushed to the upstream; undoing it would rewrite published history");
4757
+ const payload = await runGuardedGitMutation(["reset", "--soft", "HEAD~1"], { cwd: state.root });
4758
+ if (payload.data) {
4759
+ payload.data.root = state.root;
4760
+ payload.data.undoneCommit = state.lastCommit;
4761
+ payload.data.restoreCommand = "git reset --soft ORIG_HEAD";
4762
+ }
4763
+ if (payload.ok) payload.data.changes = await readGitChanges(state.root);
4764
+ return payload;
4765
+ }
4766
+
4767
+ async function amendLastGitCommitMessage(cwd, body = {}) {
4768
+ requireConfirmed(body, "Amending the last commit rewrites HEAD and");
4769
+ const message = cleanGitCommitMessageInput(body.message);
4770
+ const state = await readGitUndoState(cwd);
4771
+ if (!state.lastCommit) throw makeHttpError(409, "There is no commit to amend");
4772
+ if (state.operation) throw makeHttpError(409, `Cannot amend during a ${state.operation} operation`);
4773
+ if (state.summary.staged > 0) throw makeHttpError(409, "Staged changes present; amending now would silently add them to the last commit. Unstage or commit them first.");
4774
+ if (!state.canAmendMessage) throw makeHttpError(409, "The last commit is already pushed to the upstream; amending it would rewrite published history");
4775
+ const payload = await runGuardedGitMutation(["commit", "--amend", "-m", message], { cwd: state.root, label: "git commit --amend -m <message>" });
4776
+ if (payload.data) {
4777
+ payload.data.root = state.root;
4778
+ payload.data.previousCommit = state.lastCommit;
4779
+ payload.data.restoreCommand = "git reset --soft ORIG_HEAD";
4780
+ }
4781
+ return payload;
4782
+ }
4783
+
4784
+ async function readGitReflog(cwd) {
4785
+ const root = await getGitRoot(cwd);
4786
+ const out = await runGitReadCommand(root, ["reflog", "-n", "20", "--format=%h%x09%gd%x09%cI%x09%gs"], { maxOutputLength: 120_000 });
4787
+ const entries = out
4788
+ .split(/\r?\n/)
4789
+ .filter(Boolean)
4790
+ .map((line) => {
4791
+ const [hash, selector, date, ...subject] = line.split("\t");
4792
+ return { hash: hash || "", selector: selector || "", date: date || "", subject: subject.join("\t") };
4793
+ });
4794
+ return { root, entries, generatedAt: new Date().toISOString() };
4795
+ }
4796
+
4797
+ // ---- Submodules ----
4798
+
4799
+ async function readGitSubmodules(cwd) {
4800
+ const root = await getGitRoot(cwd);
4801
+ if (!(await regularFileExists(path.join(root, ".gitmodules")))) {
4802
+ return { root, hasSubmodules: false, submodules: [], dirty: 0 };
4803
+ }
4804
+ const out = await runGitReadCommand(root, ["submodule", "status", "--recursive"], { timeoutMs: 30_000, maxOutputLength: 200_000 });
4805
+ const submodules = out
4806
+ .split(/\r?\n/)
4807
+ .filter(Boolean)
4808
+ .map((line) => {
4809
+ const flag = line[0] || " ";
4810
+ const rest = line.slice(1).trim();
4811
+ const firstSpace = rest.indexOf(" ");
4812
+ const sha = firstSpace === -1 ? rest : rest.slice(0, firstSpace);
4813
+ const remainder = firstSpace === -1 ? "" : rest.slice(firstSpace + 1);
4814
+ const describeMatch = remainder.match(/^(.*?)( \([^)]*\))?$/);
4815
+ return {
4816
+ sha,
4817
+ path: (describeMatch?.[1] ?? remainder).trim(),
4818
+ describe: describeMatch?.[2] ? describeMatch[2].trim().replace(/^\(|\)$/g, "") : "",
4819
+ state: flag === "-" ? "uninitialized" : flag === "+" ? "out-of-sync" : flag === "U" ? "conflicts" : "clean",
4820
+ };
4821
+ });
4822
+ return { root, hasSubmodules: true, submodules, dirty: submodules.filter((item) => item.state !== "clean").length };
4823
+ }
4824
+
4825
+ async function updateGitSubmodules(cwd, body = {}) {
4826
+ requireConfirmed(body, "Recursively updating submodules can check out new commits and");
4827
+ const root = await getGitRoot(cwd);
4828
+ const payload = await runGuardedGitMutation(["submodule", "update", "--init", "--recursive"], { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS });
4829
+ if (payload.data) payload.data.root = root;
4830
+ if (payload.ok) payload.data.submodules = (await readGitSubmodules(root)).submodules;
4831
+ return payload;
4832
+ }
4833
+
4834
+ // ---- Tags ----
4835
+
4836
+ function cleanGitTagName(value) {
4837
+ const name = String(value || "").trim();
4838
+ if (!name || name.includes("\0") || name.includes("@{") || name.startsWith("-") || name.startsWith("/") || /\s/.test(name)) {
4839
+ throw makeHttpError(400, "Invalid tag name");
4840
+ }
4841
+ return name;
4842
+ }
4843
+
4844
+ async function validateGitTagName(root, name) {
4845
+ const result = await runCommand("git", ["check-ref-format", `refs/tags/${name}`], { cwd: root, timeoutMs: 5000 });
4846
+ if (result.exitCode !== 0) throw makeHttpError(400, `Invalid tag name: ${name}`);
4847
+ }
4848
+
4849
+ async function readGitTags(cwd) {
4850
+ const root = await getGitRoot(cwd);
4851
+ const [headOut, recentOut] = await Promise.all([
4852
+ runGitReadCommand(root, ["tag", "--points-at", "HEAD", "--sort=-creatordate"], { maxOutputLength: 60_000 }).catch(() => ""),
4853
+ runGitReadCommand(
4854
+ root,
4855
+ ["for-each-ref", "refs/tags", "--sort=-creatordate", "--count=30", "--format=%(refname:short)%09%(objecttype)%09%(objectname:short)%09%(*objectname:short)%09%(creatordate:iso8601)%09%(subject)"],
4856
+ { maxOutputLength: 120_000 },
4857
+ ).catch(() => ""),
4858
+ ]);
4859
+ const headTags = headOut.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
4860
+ const tags = recentOut
4861
+ .split(/\r?\n/)
4862
+ .filter(Boolean)
4863
+ .map((line) => {
4864
+ const [name, objectType, objectName, target, date, ...subject] = line.split("\t");
4865
+ return {
4866
+ name: name || "",
4867
+ annotated: objectType === "tag",
4868
+ target: (objectType === "tag" ? target : objectName) || "",
4869
+ date: date || "",
4870
+ subject: subject.join("\t"),
4871
+ atHead: headTags.includes(name || ""),
4872
+ };
4873
+ });
4874
+ return { root, headTags, tags, generatedAt: new Date().toISOString() };
4875
+ }
4876
+
4877
+ async function createGitTag(cwd, body = {}) {
4878
+ requireConfirmed(body, "Creating a tag");
4879
+ const root = await getGitRoot(cwd);
4880
+ const name = cleanGitTagName(body.name);
4881
+ await validateGitTagName(root, name);
4882
+ const message = cleanGitCommitMessageInput(body.message || name);
4883
+ const payload = await runGuardedGitMutation(["tag", "-a", name, "-m", message], { cwd: root, label: `git tag -a ${name} -m <message>` });
4884
+ if (payload.data) {
4885
+ payload.data.root = root;
4886
+ payload.data.tag = name;
4887
+ // Tags never leave the machine implicitly; pushing stays a separate,
4888
+ // explicit action.
4889
+ payload.data.pushCommand = `git push ${"origin"} ${name}`;
4890
+ }
4891
+ if (payload.ok) payload.data.tags = (await readGitTags(root)).tags;
4892
+ return payload;
4893
+ }
4894
+
4895
+ // ---- Signing diagnostics ----
4896
+
4897
+ async function readGitSigningDiagnostics(cwd) {
4898
+ const root = await getGitRoot(cwd);
4899
+ const readConfig = async (args) => {
4900
+ const result = await runCommand("git", ["config", ...args], { cwd: root, timeoutMs: 2000 });
4901
+ return result.exitCode === 0 ? result.stdout.trim() : "";
4902
+ };
4903
+ const [gpgSign, gpgFormat, signingKey, lastLog] = await Promise.all([
4904
+ readConfig(["--bool", "--get", "commit.gpgsign"]),
4905
+ readConfig(["--get", "gpg.format"]),
4906
+ readConfig(["--get", "user.signingkey"]),
4907
+ runGitReadCommand(root, ["log", "-1", "--format=%h%x09%G?%x09%GS"], { maxOutputLength: 10_000 }).catch(() => ""),
4908
+ ]);
4909
+ const [lastHash = "", signState = "", signer = ""] = lastLog.trim().split("\t");
4910
+ const commitSignRequired = gpgSign.toLowerCase() === "true";
4911
+ const normalizedState = signState.trim().toUpperCase();
4912
+ const mismatch = commitSignRequired && (!normalizedState || normalizedState === "N" || normalizedState === "E");
4913
+ const suggestions = [];
4914
+ if (mismatch) {
4915
+ if (!signingKey) suggestions.push({ label: "Set your signing key (repo only)", command: "git config user.signingkey <KEY-ID>" });
4916
+ suggestions.push({ label: "Re-sign the last commit", command: "git commit --amend --no-edit -S" });
4917
+ suggestions.push({ label: "Disable signing for this repository", command: "git config commit.gpgsign false" });
4918
+ }
4919
+ return {
4920
+ root,
4921
+ commitSignRequired,
4922
+ gpgFormat: gpgFormat || "(default: gpg)",
4923
+ signingKey: signingKey || "(not set)",
4924
+ lastCommit: lastHash ? { hash: lastHash, signState: normalizedState || "N", signer } : null,
4925
+ mismatch,
4926
+ suggestions,
4927
+ };
4928
+ }
4929
+
4134
4930
  function gitWorkflowMessageCwd(root, cwd) {
4135
4931
  const messageCwd = path.resolve(String(cwd || root));
4136
4932
  if (!pathInside(root, messageCwd)) throw new Error(`Git workflow cwd must stay inside repository root: ${messageCwd}`);
@@ -4404,7 +5200,7 @@ async function prepareInitialRepositoryFiles(cwd, { repoName: repoNameInput, sta
4404
5200
  await writeFile(before.gitignorePath, gitignoreLinesForStack(stack, before.detectedStack), "utf8");
4405
5201
  gitignoreCreated = true;
4406
5202
  }
4407
- const payload = gitWorkflowCommandPayload(await runGitWorkflowCommand(["add", "--", "README.md", ".gitignore"], { cwd: before.root, label: "git add README.md .gitignore" }));
5203
+ const payload = gitMutationPayload(await runGitMutationCommand(["add", "--", "README.md", ".gitignore"], { cwd: before.root, label: "git add README.md .gitignore" }));
4408
5204
  if (payload.data) {
4409
5205
  payload.data.root = before.root;
4410
5206
  payload.data.readme = { path: before.readmePath, exists: true, created: !before.readmeExists };
@@ -4508,7 +5304,7 @@ async function switchGitBranch(cwd, branch, { create = false } = {}) {
4508
5304
  return { ok: true, data: { command: `git switch ${targetBranch}`, stdout: "", stderr: "", exitCode: 0, branch: targetBranch, root, switched: false, created: false } };
4509
5305
  }
4510
5306
  const args = create ? ["switch", "-c", targetBranch] : ["switch", targetBranch];
4511
- const payload = gitWorkflowCommandPayload(await runGitWorkflowCommand(args, { cwd: root, timeoutMs: 10 * 60 * 1000 }));
5307
+ const payload = gitMutationPayload(await runGitMutationCommand(args, { cwd: root, timeoutMs: 10 * 60 * 1000 }));
4512
5308
  if (payload.ok) {
4513
5309
  payload.data.branch = targetBranch;
4514
5310
  payload.data.root = root;
@@ -4835,7 +5631,9 @@ function runWorkflowCommand(command, args, { cwd, label = formatWorkflowCommand(
4835
5631
  return new Promise((resolve) => {
4836
5632
  const child = spawn(command, args, {
4837
5633
  cwd,
4838
- env: { ...process.env, GIT_TERMINAL_PROMPT: process.env.GIT_TERMINAL_PROMPT || "0", GH_PROMPT_DISABLED: process.env.GH_PROMPT_DISABLED || "1" },
5634
+ // LC_ALL=C keeps git/gh output in English so failure classification
5635
+ // (classifyGitSyncFailure, isGitLockFailure) works regardless of locale.
5636
+ env: { ...process.env, GIT_TERMINAL_PROMPT: process.env.GIT_TERMINAL_PROMPT || "0", GH_PROMPT_DISABLED: process.env.GH_PROMPT_DISABLED || "1", LC_ALL: "C" },
4839
5637
  stdio: ["ignore", "pipe", "pipe"],
4840
5638
  windowsHide: true,
4841
5639
  });
@@ -4899,6 +5697,33 @@ function gitWorkflowCommandPayload(result) {
4899
5697
  };
4900
5698
  }
4901
5699
 
5700
+ // Read-only workflow lookups are safe over GET; everything else mutates the
5701
+ // repository (or process state, for cancel) and must be POST. Method + access
5702
+ // guard are enforced at the router before dispatch — never dispatch on path
5703
+ // alone, or cross-origin GETs (image/script tags) could drive git mutations.
5704
+ const GIT_WORKFLOW_READONLY_PATHS = new Set([
5705
+ "/api/git-workflow/message",
5706
+ "/api/git-workflow/default-commit-message",
5707
+ "/api/git-workflow/branch-name",
5708
+ "/api/git-workflow/pr-description",
5709
+ "/api/git-workflow/init-files-status",
5710
+ ]);
5711
+
5712
+ const GIT_WORKFLOW_MUTATING_PATHS = new Set([
5713
+ "/api/git-workflow/init",
5714
+ "/api/git-workflow/readme",
5715
+ "/api/git-workflow/initial-commit",
5716
+ "/api/git-workflow/main-branch",
5717
+ "/api/git-workflow/remote",
5718
+ "/api/git-workflow/init-push",
5719
+ "/api/git-workflow/add",
5720
+ "/api/git-workflow/branch",
5721
+ "/api/git-workflow/commit",
5722
+ "/api/git-workflow/push",
5723
+ "/api/git-workflow/create-pr",
5724
+ "/api/git-workflow/cancel",
5725
+ ]);
5726
+
4902
5727
  async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.cwd) {
4903
5728
  const tab = tabOrCwd && typeof tabOrCwd === "object" ? tabOrCwd : null;
4904
5729
  const cwd = tab?.cwd || tabOrCwd || options.cwd;
@@ -4914,25 +5739,25 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
4914
5739
  return { ok: true, data: await readGitWorkflowPrDescription(cwd) };
4915
5740
  case "/api/git-workflow/init":
4916
5741
  await ensureOutsideGitRepository(cwd);
4917
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["init"], { cwd }));
5742
+ return gitMutationPayload(await runGitMutationCommand(["init"], { cwd }));
4918
5743
  case "/api/git-workflow/init-files-status":
4919
5744
  return { ok: true, data: await initialRepositoryFilesStatus(cwd) };
4920
5745
  case "/api/git-workflow/readme":
4921
5746
  return prepareInitialRepositoryFiles(cwd, { repoName: body.repoName, stack: body.stack });
4922
5747
  case "/api/git-workflow/initial-commit": {
4923
5748
  const root = await getGitRoot(cwd);
4924
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["commit", "-m", "Initial commit"], { cwd: root, label: "git commit -m \"Initial commit\"" }));
5749
+ return gitMutationPayload(await runGitMutationCommand(["commit", "-m", "Initial commit"], { cwd: root, label: "git commit -m \"Initial commit\"" }));
4925
5750
  }
4926
5751
  case "/api/git-workflow/main-branch": {
4927
5752
  const root = await getGitRoot(cwd);
4928
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["branch", "-M", "main"], { cwd: root }));
5753
+ return gitMutationPayload(await runGitMutationCommand(["branch", "-M", "main"], { cwd: root }));
4929
5754
  }
4930
5755
  case "/api/git-workflow/remote": {
4931
5756
  const root = await getGitRoot(cwd);
4932
5757
  const username = cleanGitHubUsername(body.username);
4933
5758
  const repoName = cleanGitHubRepoName(body.repoName);
4934
5759
  const remoteUrl = gitHubOriginUrl(username, repoName);
4935
- const payload = gitWorkflowCommandPayload(await runGitWorkflowCommand(["remote", "add", "origin", remoteUrl], { cwd: root }));
5760
+ const payload = gitMutationPayload(await runGitMutationCommand(["remote", "add", "origin", remoteUrl], { cwd: root }));
4936
5761
  if (payload.data) {
4937
5762
  payload.data.root = root;
4938
5763
  payload.data.remote = "origin";
@@ -4944,11 +5769,11 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
4944
5769
  }
4945
5770
  case "/api/git-workflow/init-push": {
4946
5771
  const root = await getGitRoot(cwd);
4947
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["push", "-u", "origin", "main"], { cwd: root, timeoutMs: 15 * 60 * 1000 }));
5772
+ return applyGitSyncFailure(gitMutationPayload(await runGitMutationCommand(["push", "-u", "origin", "main"], { cwd: root, timeoutMs: 15 * 60 * 1000 })), { push: true });
4948
5773
  }
4949
5774
  case "/api/git-workflow/add":
4950
5775
  await getGitRoot(cwd);
4951
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["add", "."], { cwd }));
5776
+ return gitMutationPayload(await runGitMutationCommand(["add", "."], { cwd }));
4952
5777
  case "/api/git-workflow/branch": {
4953
5778
  if (!tab) throw new Error("Git workflow branch worktree requires a Web UI tab");
4954
5779
  return { ok: true, data: await createGitWorkflowBranchWorktree(tab, body) };
@@ -4959,32 +5784,45 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
4959
5784
  if (variant === "input") {
4960
5785
  const root = await getGitRoot(cwd);
4961
5786
  const message = cleanGitCommitMessageInput(body.message);
4962
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["commit", "-m", message], { cwd: root, label: "git commit -m <input message>" }));
5787
+ return gitMutationPayload(await runGitMutationCommand(["commit", "-m", message], { cwd: root, label: "git commit -m <input message>" }));
4963
5788
  }
4964
5789
  const messages = await readGitWorkflowMessages(cwd);
4965
5790
  if (variant === "short") {
4966
5791
  const message = messages.short.trim();
4967
5792
  if (!message) throw new Error(`${messages.shortPath} is empty`);
4968
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["commit", "-m", message], { cwd: messages.root, label: "git commit -m <dev/COMMIT/staged-commit-short.txt>" }));
5793
+ return gitMutationPayload(await runGitMutationCommand(["commit", "-m", message], { cwd: messages.root, label: "git commit -m <dev/COMMIT/staged-commit-short.txt>" }));
4969
5794
  }
4970
5795
  if (!messages.long.trim()) throw new Error(`${messages.longPath} is empty`);
4971
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["commit", "-F", messages.longPath], { cwd: messages.root, label: "git commit -F dev/COMMIT/staged-commit-long.txt" }));
5796
+ return gitMutationPayload(await runGitMutationCommand(["commit", "-F", messages.longPath], { cwd: messages.root, label: "git commit -F dev/COMMIT/staged-commit-long.txt" }));
4972
5797
  }
4973
5798
  case "/api/git-workflow/push": {
4974
5799
  const root = await getGitRoot(cwd);
5800
+ const currentBranch = await currentGitBranch(root);
5801
+ const protectedBranch = PROTECTED_GIT_BRANCHES.has(currentBranch);
4975
5802
  if (body.setUpstream) {
4976
- const currentBranch = await currentGitBranch(root);
4977
5803
  const requestedBranch = body.branch ? cleanGitBranchName(body.branch) : currentBranch;
4978
5804
  if (requestedBranch !== currentBranch) throw new Error(`Current branch is ${currentBranch}, not ${requestedBranch}`);
4979
5805
  const remote = await defaultGitRemote(root);
4980
- const payload = gitWorkflowCommandPayload(await runGitWorkflowCommand(["push", "-u", remote, currentBranch], { cwd: root, label: `git push -u ${remote} ${currentBranch}`, timeoutMs: 15 * 60 * 1000 }));
4981
- if (payload.ok) {
5806
+ const payload = await runGuardedGitMutation(["push", "-u", remote, currentBranch], { cwd: root, label: `git push -u ${remote} ${currentBranch}`, timeoutMs: 15 * 60 * 1000 });
5807
+ if (payload.data) {
4982
5808
  payload.data.branch = currentBranch;
4983
- payload.data.remote = remote;
5809
+ payload.data.protectedBranch = protectedBranch;
5810
+ if (payload.ok) payload.data.remote = remote;
4984
5811
  }
4985
- return payload;
5812
+ return applyGitSyncFailure(payload, { push: true });
4986
5813
  }
4987
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["push"], { cwd: root, timeoutMs: 15 * 60 * 1000 }));
5814
+ // Plain --force is never offered; --force-with-lease still refuses to
5815
+ // clobber remote commits we have not seen, and requires confirmation.
5816
+ const forceWithLease = body.forceWithLease === true;
5817
+ if (forceWithLease) requireConfirmed(body, `Force-pushing ${currentBranch} (--force-with-lease) rewrites the remote branch and`);
5818
+ const args = forceWithLease ? ["push", "--force-with-lease"] : ["push"];
5819
+ const payload = await runGuardedGitMutation(args, { cwd: root, timeoutMs: 15 * 60 * 1000 });
5820
+ if (payload.data) {
5821
+ payload.data.branch = currentBranch;
5822
+ payload.data.protectedBranch = protectedBranch;
5823
+ payload.data.forceWithLease = forceWithLease;
5824
+ }
5825
+ return applyGitSyncFailure(payload, { push: true });
4988
5826
  }
4989
5827
  case "/api/git-workflow/create-pr": {
4990
5828
  const root = await getGitRoot(cwd);
@@ -8189,13 +9027,17 @@ async function getFileTreeData(tab, requestedPath = "") {
8189
9027
  const resolved = await resolveWorkspacePath(tab, requestedPath);
8190
9028
  if (!resolved.info?.isDirectory()) throw makeHttpError(400, "Path is not a directory");
8191
9029
  const dirents = await readdir(resolved.targetPath, { withFileTypes: true });
8192
- const listed = await statFileTreeEntries(resolved.targetPath, dirents, resolved.root, resolved.realRoot);
9030
+ const [listed, gitStatus] = await Promise.all([
9031
+ statFileTreeEntries(resolved.targetPath, dirents, resolved.root, resolved.realRoot),
9032
+ readWorkspaceGitStatusIndex(resolved.root),
9033
+ ]);
8193
9034
  return {
8194
9035
  root: resolved.root,
8195
9036
  displayRoot: displayPath(resolved.root),
8196
9037
  path: resolved.relative,
8197
9038
  displayPath: displayPath(resolved.targetPath),
8198
- entries: listed.entries,
9039
+ entries: withFileTreeGitStatus(listed.entries, resolved.root, gitStatus),
9040
+ gitStatus: fileTreeGitStatusPayload(resolved.root, gitStatus),
8199
9041
  truncated: listed.truncated,
8200
9042
  total: listed.total,
8201
9043
  };
@@ -8222,6 +9064,7 @@ async function getFileSearchData(tab, rawQuery = "") {
8222
9064
  }
8223
9065
  const resolved = await resolveWorkspacePath(tab, "");
8224
9066
  if (!resolved.info?.isDirectory()) throw makeHttpError(400, "Workspace root is not a directory");
9067
+ const gitStatus = await readWorkspaceGitStatusIndex(resolved.root);
8225
9068
  const queryLower = query.toLowerCase();
8226
9069
  const entries = [];
8227
9070
  const queue = [{ dirPath: resolved.root, relative: "", depth: 0 }];
@@ -8283,7 +9126,8 @@ async function getFileSearchData(tab, rawQuery = "") {
8283
9126
  root: resolved.root,
8284
9127
  displayRoot: displayPath(resolved.root),
8285
9128
  query,
8286
- entries,
9129
+ entries: withFileTreeGitStatus(entries, resolved.root, gitStatus),
9130
+ gitStatus: fileTreeGitStatusPayload(resolved.root, gitStatus),
8287
9131
  truncated,
8288
9132
  total: entries.length,
8289
9133
  scanned,
@@ -8345,6 +9189,103 @@ async function saveFileContentData(tab, body = {}) {
8345
9189
  };
8346
9190
  }
8347
9191
 
9192
+ function workspaceRelativePath(root, targetPath) {
9193
+ return path.relative(root, targetPath).split(path.sep).join("/");
9194
+ }
9195
+
9196
+ function fileOperationEntryType(info) {
9197
+ if (info?.isDirectory?.()) return "directory";
9198
+ if (info?.isFile?.()) return "file";
9199
+ return "other";
9200
+ }
9201
+
9202
+ function assertWorkspaceEntryMutable(resolved, action) {
9203
+ if (!resolved.relative) throw makeHttpError(400, `Workspace root cannot be ${action}`);
9204
+ const type = fileOperationEntryType(resolved.info);
9205
+ if (type !== "file" && type !== "directory") throw makeHttpError(400, "Only regular files and directories can be modified from WebUI");
9206
+ return type;
9207
+ }
9208
+
9209
+ async function existingDestinationStats(targetPath) {
9210
+ try {
9211
+ return await stat(targetPath);
9212
+ } catch (error) {
9213
+ if (error?.code === "ENOENT") return null;
9214
+ throw makeHttpError(400, `Cannot access destination: ${displayPath(targetPath)}`);
9215
+ }
9216
+ }
9217
+
9218
+ async function resolveWorkspaceMoveDestination(tab, source, rawDestination = "") {
9219
+ const destinationText = String(rawDestination || "").trim();
9220
+ if (!destinationText) throw makeHttpError(400, "Destination path is required");
9221
+ if (destinationText.includes("\0")) throw makeHttpError(400, "Destination path cannot contain null bytes");
9222
+
9223
+ const candidatePath = path.isAbsolute(destinationText) ? path.resolve(destinationText) : path.resolve(source.root, destinationText);
9224
+ if (candidatePath !== source.root && !pathInside(source.root, candidatePath)) throw makeHttpError(403, "Destination path must stay inside the active tab working directory");
9225
+
9226
+ const candidateInfo = await existingDestinationStats(candidatePath);
9227
+ let targetPath = candidatePath;
9228
+ let targetInfo = candidateInfo;
9229
+ if (candidateInfo?.isDirectory?.()) {
9230
+ targetPath = path.join(candidatePath, path.basename(source.targetPath));
9231
+ targetInfo = await existingDestinationStats(targetPath);
9232
+ }
9233
+
9234
+ if (path.resolve(targetPath) === path.resolve(source.targetPath)) throw makeHttpError(400, "Source and destination are the same path");
9235
+ if (targetInfo) throw makeHttpError(409, `Destination already exists: ${workspaceRelativePath(source.root, targetPath)}`);
9236
+ if (source.info?.isDirectory?.() && pathInside(source.targetPath, targetPath)) throw makeHttpError(400, "A directory cannot be moved into itself or one of its descendants");
9237
+
9238
+ const parentPath = path.dirname(targetPath);
9239
+ if (parentPath !== source.root && !pathInside(source.root, parentPath)) throw makeHttpError(403, "Destination parent must stay inside the active tab working directory");
9240
+ const parentInfo = await stat(parentPath).catch((error) => {
9241
+ if (error?.code === "ENOENT") throw makeHttpError(404, `Destination parent not found: ${displayPath(parentPath)}`);
9242
+ throw makeHttpError(400, `Cannot access destination parent: ${displayPath(parentPath)}`);
9243
+ });
9244
+ if (!parentInfo?.isDirectory?.()) throw makeHttpError(400, "Destination parent is not a directory");
9245
+ const realParent = await realpath(parentPath).catch(() => parentPath);
9246
+ if (realParent !== source.realRoot && !pathInside(source.realRoot, realParent)) throw makeHttpError(403, "Destination parent escapes the active tab working directory");
9247
+
9248
+ return {
9249
+ targetPath,
9250
+ relative: workspaceRelativePath(source.root, targetPath),
9251
+ parentPath: workspaceRelativePath(source.root, parentPath),
9252
+ };
9253
+ }
9254
+
9255
+ async function deleteFileSystemEntryData(tab, body = {}) {
9256
+ if (body.confirmed !== true) throw makeHttpError(409, "Deleting files or directories requires confirmed: true");
9257
+ const resolved = await resolveWorkspacePath(tab, body.path || body.filePath || "");
9258
+ const type = assertWorkspaceEntryMutable(resolved, "deleted");
9259
+ await rm(resolved.targetPath, { recursive: type === "directory" });
9260
+ return {
9261
+ path: resolved.relative,
9262
+ name: path.basename(resolved.targetPath),
9263
+ type,
9264
+ parentPath: workspaceRelativePath(resolved.root, path.dirname(resolved.targetPath)),
9265
+ deleted: true,
9266
+ };
9267
+ }
9268
+
9269
+ async function moveFileSystemEntryData(tab, body = {}) {
9270
+ if (body.confirmed !== true) throw makeHttpError(409, "Moving files or directories requires confirmed: true");
9271
+ const source = await resolveWorkspacePath(tab, body.path || body.filePath || body.sourcePath || "");
9272
+ const type = assertWorkspaceEntryMutable(source, "moved");
9273
+ const destination = await resolveWorkspaceMoveDestination(tab, source, body.toPath || body.destinationPath || body.destination || "");
9274
+ await rename(source.targetPath, destination.targetPath);
9275
+ const nextStats = await stat(destination.targetPath).catch(() => null);
9276
+ return {
9277
+ path: source.relative,
9278
+ destination: destination.relative,
9279
+ name: path.basename(destination.targetPath),
9280
+ type,
9281
+ parentPath: workspaceRelativePath(source.root, path.dirname(source.targetPath)),
9282
+ destinationParentPath: destination.parentPath,
9283
+ moved: true,
9284
+ size: nextStats?.size,
9285
+ mtimeMs: nextStats?.mtimeMs,
9286
+ };
9287
+ }
9288
+
8348
9289
  function defaultEditorCommand(targetPath) {
8349
9290
  if (platform() === "win32") return { command: "cmd", args: ["/c", "start", "", targetPath] };
8350
9291
  if (platform() === "darwin") return { command: "open", args: [targetPath] };
@@ -9862,6 +10803,24 @@ const server = createServer(async (req, res) => {
9862
10803
  return;
9863
10804
  }
9864
10805
 
10806
+ if (url.pathname === "/api/files" && req.method === "DELETE") {
10807
+ requireLocalhostRoute(req, url.pathname);
10808
+ const body = await readJsonBody(req);
10809
+ const tab = getRequestedTab(req, url, body);
10810
+ ensureNaturalConversationRouteAllowed(tab, "file deletion is blocked");
10811
+ sendJson(res, 200, { ok: true, data: await deleteFileSystemEntryData(tab, body) });
10812
+ return;
10813
+ }
10814
+
10815
+ if (url.pathname === "/api/files/move" && req.method === "POST") {
10816
+ requireLocalhostRoute(req, url.pathname);
10817
+ const body = await readJsonBody(req);
10818
+ const tab = getRequestedTab(req, url, body);
10819
+ ensureNaturalConversationRouteAllowed(tab, "file moves are blocked");
10820
+ sendJson(res, 200, { ok: true, data: await moveFileSystemEntryData(tab, body) });
10821
+ return;
10822
+ }
10823
+
9865
10824
  if (url.pathname === "/api/files/search" && req.method === "GET") {
9866
10825
  const tab = getRequestedTab(req, url);
9867
10826
  sendJson(res, 200, { ok: true, data: await getFileSearchData(tab, url.searchParams.get("q") || url.searchParams.get("query") || "") });
@@ -10292,15 +11251,89 @@ const server = createServer(async (req, res) => {
10292
11251
  return;
10293
11252
  }
10294
11253
 
10295
- if (url.pathname.startsWith("/api/git-workflow/")) {
10296
- const body = req.method === "POST" ? await readJsonBody(req) : {};
10297
- const tab = getRequestedTab(req, url, body);
10298
- if (req.method !== "GET") ensureNaturalConversationRouteAllowed(tab, "git workflow actions are blocked");
10299
- const response = await handleGitWorkflowRequest(url.pathname, body, tab);
10300
- if (response) {
10301
- sendJson(res, 200, response);
11254
+ {
11255
+ const gitActionError = (error) => {
11256
+ sendJson(res, error?.statusCode || 200, { ok: false, ...(error?.code ? { code: error.code } : {}), error: sanitizeError(error) });
11257
+ };
11258
+ const GIT_READ_ROUTES = {
11259
+ "/api/git-operation": (cwd) => readGitOperationSnapshot(cwd),
11260
+ "/api/git-stash": (cwd) => readGitStashes(cwd),
11261
+ "/api/git-stash/show": (cwd) => readGitStashPreview(cwd, url.searchParams.get("ref") || ""),
11262
+ "/api/git-undo": (cwd) => readGitUndoState(cwd),
11263
+ "/api/git-reflog": (cwd) => readGitReflog(cwd),
11264
+ "/api/git-submodules": (cwd) => readGitSubmodules(cwd),
11265
+ "/api/git-tags": (cwd) => readGitTags(cwd),
11266
+ "/api/git-signing": (cwd) => readGitSigningDiagnostics(cwd),
11267
+ "/api/git-worktrees/prune": (cwd) => pruneGitWorktrees(cwd, { dryRun: true }),
11268
+ };
11269
+ if (req.method === "GET" && GIT_READ_ROUTES[url.pathname]) {
11270
+ const tab = getRequestedTab(req, url);
11271
+ try {
11272
+ sendJson(res, 200, { ok: true, data: await GIT_READ_ROUTES[url.pathname](tab.cwd) });
11273
+ } catch (error) {
11274
+ gitActionError(error);
11275
+ }
10302
11276
  return;
10303
11277
  }
11278
+
11279
+ const GIT_MUTATION_ROUTES = {
11280
+ "/api/git-fetch": (cwd) => fetchGitChanges(cwd),
11281
+ "/api/git-changes/integrate": (cwd, body) => integrateGitUpstream(cwd, body),
11282
+ "/api/git-changes/stage-file": (cwd, body) => stageGitFile(cwd, body),
11283
+ "/api/git-changes/unstage-file": (cwd, body) => unstageGitFile(cwd, body),
11284
+ "/api/git-changes/discard-file": (cwd, body) => discardGitFile(cwd, body),
11285
+ "/api/git-changes/delete-untracked": (cwd, body) => deleteGitUntrackedFile(cwd, body),
11286
+ "/api/git-operation/continue": (cwd, body) => gitOperationAction(cwd, "continue", body),
11287
+ "/api/git-operation/skip": (cwd, body) => gitOperationAction(cwd, "skip", body),
11288
+ "/api/git-operation/abort": (cwd, body) => gitOperationAction(cwd, "abort", body),
11289
+ "/api/git-operation/stage-file": (cwd, body) => gitOperationStageFile(cwd, body),
11290
+ "/api/git-operation/bisect": (cwd, body) => gitBisectAction(cwd, body),
11291
+ "/api/git-stash/save": (cwd, body) => saveGitStash(cwd, body),
11292
+ "/api/git-stash/apply": (cwd, body) => applyGitStash(cwd, body),
11293
+ "/api/git-stash/pop": (cwd, body) => applyGitStash(cwd, body, { pop: true }),
11294
+ "/api/git-stash/drop": (cwd, body) => dropGitStash(cwd, body),
11295
+ "/api/git-undo/last-commit": (cwd, body) => undoLastGitCommit(cwd, body),
11296
+ "/api/git-undo/amend-message": (cwd, body) => amendLastGitCommitMessage(cwd, body),
11297
+ "/api/git-submodules/update": (cwd, body) => updateGitSubmodules(cwd, body),
11298
+ "/api/git-tags/create": (cwd, body) => createGitTag(cwd, body),
11299
+ "/api/git-worktrees/prune": (cwd, body) => {
11300
+ requireConfirmed(body, "Pruning stale worktree records");
11301
+ return pruneGitWorktrees(cwd, { dryRun: false });
11302
+ },
11303
+ };
11304
+ if (req.method === "POST" && GIT_MUTATION_ROUTES[url.pathname]) {
11305
+ const body = await readJsonBody(req);
11306
+ const tab = getRequestedTab(req, url, body);
11307
+ ensureNaturalConversationRouteAllowed(tab, "git actions are blocked");
11308
+ try {
11309
+ const payload = await GIT_MUTATION_ROUTES[url.pathname](tab.cwd, body);
11310
+ sendJson(res, 200, payload && typeof payload === "object" && "ok" in payload ? payload : { ok: true, data: payload });
11311
+ } catch (error) {
11312
+ gitActionError(error);
11313
+ }
11314
+ return;
11315
+ }
11316
+ }
11317
+
11318
+ if (url.pathname.startsWith("/api/git-workflow/")) {
11319
+ const readOnlyWorkflow = GIT_WORKFLOW_READONLY_PATHS.has(url.pathname);
11320
+ const mutatingWorkflow = GIT_WORKFLOW_MUTATING_PATHS.has(url.pathname);
11321
+ if (readOnlyWorkflow || mutatingWorkflow) {
11322
+ const requiredMethod = mutatingWorkflow ? "POST" : "GET";
11323
+ if (req.method !== requiredMethod) {
11324
+ res.setHeader("Allow", requiredMethod);
11325
+ sendJson(res, 405, { ok: false, error: `${url.pathname} requires ${requiredMethod}` });
11326
+ return;
11327
+ }
11328
+ const body = mutatingWorkflow ? await readJsonBody(req) : {};
11329
+ const tab = getRequestedTab(req, url, body);
11330
+ if (mutatingWorkflow) ensureNaturalConversationRouteAllowed(tab, "git workflow actions are blocked");
11331
+ const response = await handleGitWorkflowRequest(url.pathname, body, tab);
11332
+ if (response) {
11333
+ sendJson(res, 200, response);
11334
+ return;
11335
+ }
11336
+ }
10304
11337
  }
10305
11338
 
10306
11339
  const getCommand = req.method === "GET" ? commandFromGet(url.pathname) : undefined;