@firstpick/pi-package-webui 0.11.1 → 0.11.2
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/DEVELOPMENT.md +151 -12
- package/README.md +34 -6
- package/TECHNICAL.md +75 -8
- package/bin/pi-webui.mjs +5390 -11423
- package/index.ts +10 -3
- package/lib/component-update-state.mjs +2 -2
- package/lib/git-workflow-preference-values.mjs +122 -0
- package/lib/git-workflow-preferences.mjs +35 -563
- package/lib/package-updates.mjs +260 -0
- package/lib/rpc-supervisor-client.mjs +8 -4
- package/lib/server/app-runners.mjs +1667 -0
- package/lib/server/codex-fast-mode.mjs +161 -0
- package/lib/server/conversation-mode.mjs +218 -0
- package/lib/server/conversation-voice.mjs +318 -0
- package/lib/server/extension-ui-requests.mjs +114 -0
- package/lib/server/git-generation.mjs +459 -0
- package/lib/server/git-mutations.mjs +1827 -0
- package/lib/server/git-reads.mjs +608 -0
- package/lib/server/git-worktree-sessions.mjs +408 -0
- package/lib/server/helper-requests.mjs +82 -0
- package/lib/server/no-project-workspaces.mjs +103 -0
- package/lib/server/rpc-transports.mjs +394 -0
- package/lib/server/settings-store.mjs +544 -0
- package/lib/server/sse-delivery.mjs +138 -0
- package/lib/server/workspace-files.mjs +563 -0
- package/lib/update/supervisor.mjs +4 -0
- package/lib/webui-workspaces.mjs +2 -0
- package/package.json +4 -4
- package/public/activity-agents-controller.mjs +269 -0
- package/public/activity-events-controller.mjs +236 -0
- package/public/activity-intercom-controller.mjs +627 -0
- package/public/activity-queue-controller.mjs +534 -0
- package/public/activity-todo-view.mjs +89 -0
- package/public/activity-usage-controller.mjs +589 -0
- package/public/app.js +3761 -3886
- package/public/conversation-overview.css +84 -0
- package/public/conversation-overview.mjs +193 -0
- package/public/draft-conversations.mjs +135 -0
- package/public/focused-composer-controls.css +111 -0
- package/public/focused-composer-controls.mjs +143 -0
- package/public/focused-composer-disclosure.mjs +223 -0
- package/public/focused-shell-adapter.css +264 -0
- package/public/focused-shell-adapter.mjs +257 -0
- package/public/index.html +137 -80
- package/public/model-catalog-order.mjs +63 -0
- package/public/platform-event-stream.mjs +64 -0
- package/public/project-artifact-controller.mjs +218 -0
- package/public/project-file-viewer-controller.mjs +383 -0
- package/public/project-git-tools-controller.mjs +181 -0
- package/public/project-runners-controller.mjs +220 -0
- package/public/service-worker.js +52 -1
- package/public/session-attention-scheduler.mjs +182 -0
- package/public/session-composer-store.mjs +56 -0
- package/public/session-context.mjs +51 -0
- package/public/session-extension-requests.mjs +63 -0
- package/public/session-shelf-state.mjs +151 -0
- package/public/session-shelves.css +171 -0
- package/public/session-shelves.mjs +95 -0
- package/public/settings-navigation-controller.mjs +249 -0
- package/public/settings-navigation.css +61 -0
- package/public/settings-resource-controller.mjs +232 -0
- package/public/settings-workspace.css +19 -0
- package/public/settings-workspace.mjs +175 -0
- package/public/shell-actions.mjs +87 -0
- package/public/shell-attention-inbox.css +72 -0
- package/public/shell-attention-inbox.mjs +198 -0
- package/public/shell-context-actions.css +61 -0
- package/public/shell-context-actions.mjs +168 -0
- package/public/shell-inspector-resize.mjs +124 -0
- package/public/shell-navigation-resize.mjs +107 -0
- package/public/shell-navigation.mjs +127 -0
- package/public/shell-preferences.mjs +108 -0
- package/public/shell-surfaces.mjs +99 -0
- package/public/shell-tools-launcher.css +97 -0
- package/public/shell-tools-launcher.mjs +222 -0
- package/public/shell-view-host.mjs +115 -0
- package/public/shell-workspace.css +266 -0
- package/public/shell-workspace.mjs +402 -0
- package/public/sidebar-update-menu.css +190 -0
- package/public/sidebar-update-menu.mjs +512 -0
- package/public/styles.css +320 -169
- package/public/subagent-launch-slot-state.mjs +2 -2
- package/public/themed-selects.css +156 -0
- package/public/workspace-choices.mjs +104 -0
- package/tests/activity-agents-controller.test.mjs +652 -0
- package/tests/activity-events-controller.test.mjs +511 -0
- package/tests/app-runner-terminal-static.test.mjs +3 -3
- package/tests/append-system-http.test.mjs +7 -6
- package/tests/append-system-selector-static.test.mjs +6 -6
- package/tests/aur-review-widget-static.test.mjs +11 -3
- package/tests/boot-failure-diagnostics.test.mjs +8 -3
- package/tests/browser/activity-intercom-controller.spec.mjs +457 -0
- package/tests/browser/activity-navigation-integration.spec.mjs +45 -0
- package/tests/browser/activity-owner-integration.spec.mjs +201 -0
- package/tests/browser/activity-queue-controller.spec.mjs +405 -0
- package/tests/browser/activity-section-picker.spec.mjs +294 -0
- package/tests/browser/activity-todo-view.spec.mjs +60 -0
- package/tests/browser/activity-usage-controller.spec.mjs +416 -0
- package/tests/browser/compact-layout-integration.spec.mjs +58 -0
- package/tests/browser/composer-action-grid-reorder.spec.mjs +16 -0
- package/tests/browser/composer-disclosure.spec.mjs +389 -0
- package/tests/browser/composer-toolbar-polish.spec.mjs +343 -0
- package/tests/browser/control-deck-component-updates.spec.mjs +5 -14
- package/tests/browser/control-deck-side-panels.spec.mjs +27 -12
- package/tests/browser/control-visibility.spec.mjs +5 -0
- package/tests/browser/controls-layout.spec.mjs +21 -2
- package/tests/browser/conversation-overview.spec.mjs +251 -0
- package/tests/browser/draft-conversations.spec.mjs +276 -0
- package/tests/browser/empty-startup-fixture.mjs +135 -0
- package/tests/browser/empty-startup.spec.mjs +282 -0
- package/tests/browser/events-tree-context-menu.spec.mjs +1 -0
- package/tests/browser/focused-composer-more.spec.mjs +127 -0
- package/tests/browser/focused-model-shortcuts.spec.mjs +120 -0
- package/tests/browser/focused-navigation-fixture.mjs +32 -0
- package/tests/browser/focused-project-activity.spec.mjs +111 -0
- package/tests/browser/focused-shell-integration.spec.mjs +208 -0
- package/tests/browser/folder-picker-layout-fixture.mjs +13 -0
- package/tests/browser/folder-picker-layout.spec.mjs +302 -0
- package/tests/browser/footer-model-advanced-layout.spec.mjs +27 -14
- package/tests/browser/git-setup-cancel.spec.mjs +251 -0
- package/tests/browser/guided-git-fallback.spec.mjs +40 -21
- package/tests/browser/inspector-header.spec.mjs +221 -0
- package/tests/browser/inspector-overview-integration.spec.mjs +104 -0
- package/tests/browser/inspector-resize.spec.mjs +227 -0
- package/tests/browser/inspector-topic-overflow.spec.mjs +56 -0
- package/tests/browser/interaction-action-discovery.spec.mjs +332 -0
- package/tests/browser/interaction-attention-inbox.spec.mjs +364 -0
- package/tests/browser/interaction-attention-integration.spec.mjs +53 -0
- package/tests/browser/interaction-composer-controls.spec.mjs +267 -0
- package/tests/browser/interaction-composer-integration.spec.mjs +175 -0
- package/tests/browser/interaction-continuity.spec.mjs +50 -26
- package/tests/browser/interaction-model-picker.spec.mjs +86 -0
- package/tests/browser/last-terminal-close.spec.mjs +280 -0
- package/tests/browser/mobile-foundation.spec.mjs +172 -20
- package/tests/browser/model-catalog-groups.spec.mjs +104 -0
- package/tests/browser/more-row-menus.spec.mjs +258 -0
- package/tests/browser/new-tab-hit-target.spec.mjs +228 -0
- package/tests/browser/no-project-conversation.spec.mjs +113 -0
- package/tests/browser/optimistic-prompt.spec.mjs +3 -0
- package/tests/browser/overhaul-w7-accessibility.spec.mjs +227 -0
- package/tests/browser/overhaul-w7-capabilities.spec.mjs +298 -0
- package/tests/browser/overhaul-w7-companions.spec.mjs +290 -0
- package/tests/browser/overhaul-w7-focus-repairs.spec.mjs +210 -0
- package/tests/browser/overhaul-w7-layout-repairs.spec.mjs +183 -0
- package/tests/browser/overhaul-w7-parent-repairs.spec.mjs +97 -0
- package/tests/browser/overhaul-w7-pwa.spec.mjs +247 -0
- package/tests/browser/overhaul-w7-responsive.spec.mjs +450 -0
- package/tests/browser/overhaul-w7-update.spec.mjs +215 -0
- package/tests/browser/overhaul-w7-zoom.spec.mjs +243 -0
- package/tests/browser/overview-agent-ownership.spec.mjs +45 -0
- package/tests/browser/persistent-ui-layout.spec.mjs +3 -0
- package/tests/browser/project-artifact-controller.spec.mjs +324 -0
- package/tests/browser/project-artifact-integration.spec.mjs +103 -0
- package/tests/browser/project-file-buffer-integration.spec.mjs +230 -0
- package/tests/browser/project-git-tools-integration.spec.mjs +369 -0
- package/tests/browser/session-fixture.mjs +118 -0
- package/tests/browser/session-ownership.spec.mjs +175 -0
- package/tests/browser/session-shelves-integration.spec.mjs +219 -0
- package/tests/browser/session-shelves.spec.mjs +340 -0
- package/tests/browser/session-sidebar-resize.spec.mjs +138 -0
- package/tests/browser/session-summary.spec.mjs +17 -12
- package/tests/browser/settings-complete-home.spec.mjs +463 -0
- package/tests/browser/settings-entrypoint.spec.mjs +104 -0
- package/tests/browser/settings-navigation-controller.spec.mjs +383 -0
- package/tests/browser/settings-navigation-integration.spec.mjs +348 -0
- package/tests/browser/settings-resource-lifetime.spec.mjs +349 -0
- package/tests/browser/settings-workspace-integration.spec.mjs +132 -0
- package/tests/browser/shell-ownership.spec.mjs +398 -0
- package/tests/browser/shell-rollout-fixture.mjs +259 -0
- package/tests/browser/shell-rollout.spec.mjs +357 -0
- package/tests/browser/shell-tools-launcher.spec.mjs +260 -0
- package/tests/browser/shell-workspace.spec.mjs +433 -0
- package/tests/browser/side-panel-section-reorder.spec.mjs +3 -1
- package/tests/browser/sidebar-floating-tooltips.spec.mjs +37 -0
- package/tests/browser/sidebar-update-integration.spec.mjs +277 -0
- package/tests/browser/sidebar-update-menu.spec.mjs +402 -0
- package/tests/browser/sidebar-update-progress.spec.mjs +472 -0
- package/tests/browser/stream-output-isolation.spec.mjs +6 -3
- package/tests/browser/themed-selects.spec.mjs +297 -0
- package/tests/browser/thread-start-flow.spec.mjs +481 -0
- package/tests/browser/ui-polish-activity-controls.spec.mjs +177 -0
- package/tests/browser/ui-polish-features.spec.mjs +85 -0
- package/tests/browser/ui-polish-file-header.spec.mjs +43 -0
- package/tests/browser/ui-polish-local-git.spec.mjs +183 -0
- package/tests/browser/ui-polish-mobile-recovery.spec.mjs +36 -0
- package/tests/browser/ui-polish-navigation.spec.mjs +127 -0
- package/tests/browser/ui-polish-session-actions.spec.mjs +282 -0
- package/tests/browser/user-noticeable-fixes.spec.mjs +10 -3
- package/tests/browser/windows-drive-parent.spec.mjs +4 -2
- package/tests/browser/workspace-draft-selection.spec.mjs +266 -0
- package/tests/codex-fast-mode-static.test.mjs +16 -11
- package/tests/codex-speed-mode-browser-state.test.mjs +6 -3
- package/tests/codex-usage-source.test.mjs +4 -3
- package/tests/component-update-api-static.test.mjs +2 -2
- package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
- package/tests/control-deck-component-updates-static.test.mjs +9 -4
- package/tests/control-visibility-static.test.mjs +3 -3
- package/tests/controls-layout-static.test.mjs +5 -5
- package/tests/conversation-overview-adapter.test.mjs +100 -0
- package/tests/document-artifact-static.test.mjs +2 -1
- package/tests/draft-conversations.test.mjs +205 -0
- package/tests/empty-startup-launcher.test.mjs +197 -0
- package/tests/events-tree-context-menu-static.test.mjs +22 -18
- package/tests/fake-pi-session-ownership.test.mjs +302 -0
- package/tests/fast-mode-client-static.test.mjs +1 -1
- package/tests/feature-decision-output-popup-static.test.mjs +2 -2
- package/tests/feature-system-prompt-optional-feature-static.test.mjs +1 -1
- package/tests/file-viewer-image-static.test.mjs +15 -11
- package/tests/file-viewer-search-static.test.mjs +5 -5
- package/tests/fixtures/fake-pi.mjs +41 -9
- package/tests/footer-provider-usage-visual-static.test.mjs +7 -6
- package/tests/foreground-transcript-catch-up-static.test.mjs +7 -4
- package/tests/git-footer-context-menu-static.test.mjs +1 -1
- package/tests/git-panel-file-preview-static.test.mjs +41 -48
- package/tests/git-panel-live-updates-static.test.mjs +2 -1
- package/tests/git-workflow-dispatch.test.mjs +66 -0
- package/tests/git-workflow-preferences.test.mjs +9 -1
- package/tests/guided-git-activation-static.test.mjs +14 -11
- package/tests/guided-git-fallback-ui-static.test.mjs +8 -5
- package/tests/guided-git-message-reliability-static.test.mjs +10 -6
- package/tests/guided-git-publication-backend-static.test.mjs +16 -11
- package/tests/http-endpoints-harness.test.mjs +21 -9
- package/tests/interaction-state-stability-static.test.mjs +4 -3
- package/tests/intercom-conversation-viewer-static.test.mjs +29 -17
- package/tests/intercom-tag-layout-static.test.mjs +13 -12
- package/tests/intercom-tag-overflow-layout.test.mjs +11 -10
- package/tests/main-output-loading-static.test.mjs +4 -4
- package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
- package/tests/mobile-compact-layout.test.mjs +2 -2
- package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
- package/tests/mobile-foundation-static.test.mjs +10 -7
- package/tests/mobile-phone-experience-static.test.mjs +3 -2
- package/tests/mobile-static.test.mjs +173 -135
- package/tests/model-catalog-order.test.mjs +103 -0
- package/tests/native-parity.test.mjs +6 -4
- package/tests/native-session-choice-owner.test.mjs +102 -0
- package/tests/native-update-lifecycle.test.mjs +10 -5
- package/tests/no-project-http-harness.test.mjs +328 -0
- package/tests/no-project-navigation.test.mjs +54 -0
- package/tests/no-project-workspaces.test.mjs +77 -0
- package/tests/open-issue-wizard-static.test.mjs +1 -1
- package/tests/optional-feature-migration-frontend.test.mjs +4 -4
- package/tests/optional-feature-prompt-impact-static.test.mjs +3 -3
- package/tests/package-updates.test.mjs +630 -0
- package/tests/persistent-ui-layout-static.test.mjs +3 -3
- package/tests/platform-event-stream.test.mjs +253 -0
- package/tests/project-file-viewer-controller.test.mjs +652 -0
- package/tests/project-git-tools-adapter.test.mjs +103 -0
- package/tests/project-git-tools-controller.test.mjs +577 -0
- package/tests/project-runners-controller.test.mjs +453 -0
- package/tests/prompt-input-vertical-scroll-static.test.mjs +3 -3
- package/tests/prompt-routing-input-clear-static.test.mjs +2 -2
- package/tests/questionnaire-dialog.test.mjs +6 -6
- package/tests/queue-edit-reorder-static.test.mjs +48 -51
- package/tests/rpc-supervisor-host.test.mjs +4 -1
- package/tests/safety-guard-auto-review-static.test.mjs +1 -1
- package/tests/sampling-native-controls-user-flow.test.mjs +7 -1
- package/tests/server-app-runners.test.mjs +536 -0
- package/tests/server-codex-fast-mode.test.mjs +346 -0
- package/tests/server-conversation-mode.test.mjs +386 -0
- package/tests/server-conversation-voice.test.mjs +426 -0
- package/tests/server-extension-ui-requests.test.mjs +357 -0
- package/tests/server-git-generation.test.mjs +558 -0
- package/tests/server-git-mutations.test.mjs +729 -0
- package/tests/server-git-reads.test.mjs +381 -0
- package/tests/server-git-worktree-sessions.test.mjs +502 -0
- package/tests/server-helper-requests.test.mjs +364 -0
- package/tests/server-rpc-transports.test.mjs +553 -0
- package/tests/server-settings-store.test.mjs +132 -0
- package/tests/server-shell-rollout.test.mjs +478 -0
- package/tests/server-sse-delivery.test.mjs +410 -0
- package/tests/server-workspace-files.test.mjs +546 -0
- package/tests/session-attention-scheduler.test.mjs +514 -0
- package/tests/session-composer-store.test.mjs +153 -0
- package/tests/session-context.test.mjs +134 -0
- package/tests/session-extension-requests.test.mjs +193 -0
- package/tests/session-ownership-adapter.test.mjs +130 -0
- package/tests/session-sampling-ui-static.test.mjs +10 -4
- package/tests/session-send-lifetime.test.mjs +140 -0
- package/tests/session-shelf-state.test.mjs +348 -0
- package/tests/session-shelves-adapter.test.mjs +79 -0
- package/tests/session-summary-lifetime.test.mjs +54 -0
- package/tests/settings-resource-controller.test.mjs +548 -0
- package/tests/shell-action-adapter.test.mjs +169 -0
- package/tests/shell-actions.test.mjs +182 -0
- package/tests/shell-navigation.test.mjs +348 -0
- package/tests/shell-preferences.test.mjs +367 -0
- package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
- package/tests/stream-output-isolation-static.test.mjs +1 -1
- package/tests/subagent-gate-visibility.test.mjs +1 -1
- package/tests/subagent-launch-slot-state.test.mjs +2 -2
- package/tests/subagent-launch-slots-static.test.mjs +1 -1
- package/tests/subagent-observability-static.test.mjs +2 -2
- package/tests/subagent-reliability-integration.test.mjs +13 -30
- package/tests/syntax-highlighting-static.test.mjs +3 -3
- package/tests/tab-close-continuity-static.test.mjs +1 -1
- package/tests/tab-metadata-ordering.test.mjs +99 -0
- package/tests/terminal-cwd-grouping-static.test.mjs +2 -2
- package/tests/terminal-tab-prompt-tooltip-static.test.mjs +2 -0
- package/tests/terminal-tab-workspace-static.test.mjs +5 -4
- package/tests/terminal-tabs-resize-static.test.mjs +1 -1
- package/tests/theme-customizer-static.test.mjs +1 -1
- package/tests/thread-display-title.test.mjs +44 -0
- package/tests/update-api-harness.test.mjs +15 -14
- package/tests/update-tab-restore-harness.test.mjs +3 -0
- package/tests/webui-settings-locking.test.mjs +2 -2
- package/tests/windows-drive-cwd-picker-static.test.mjs +7 -9
- package/tests/workspace-choices.test.mjs +114 -0
- package/tests/workspace-save-load-static.test.mjs +7 -4
|
@@ -0,0 +1,1827 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { constants as fsConstants } from "node:fs";
|
|
4
|
+
import { lstat, mkdir, open, readFile, readdir, realpath, rm, stat, writeFile } from "node:fs/promises";
|
|
5
|
+
import { platform } from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { classifyGitPathFailure, findWindowsReservedGitPath, windowsReservedGitPathFailure } from "../git-command-errors.mjs";
|
|
8
|
+
import { WORKTREE_ERROR_CODES, isGitLockFailure, listGitWorktrees, pathInside } from "../git-worktrees.mjs";
|
|
9
|
+
import { gitMessageArtifactPairReadiness, readStableGitMessageArtifactPair, sameGitMessageArtifactPair } from "../git-message-artifacts.mjs";
|
|
10
|
+
|
|
11
|
+
let activeGitWorkflowProcess = null;
|
|
12
|
+
const GIT_PULL_TIMEOUT_MS = 15 * 60 * 1000;
|
|
13
|
+
// Must remain byte-for-byte aligned with pi-extension-aur-review/src/git.ts.
|
|
14
|
+
const STAGED_CONTENT_HASH_DOMAIN = "firstpick/aur-review/staged-content/v1\0";
|
|
15
|
+
const STAGED_CONTENT_HASH_TIMEOUT_MS = 10_000;
|
|
16
|
+
const STAGED_CONTENT_HASH_OUTPUT_LIMIT = 4 * 1024 * 1024;
|
|
17
|
+
const STAGED_CONTENT_HASH_ARGS = [
|
|
18
|
+
"-c", "core.quotepath=false",
|
|
19
|
+
"-c", "diff.external=",
|
|
20
|
+
"diff", "--cached", "--binary", "--full-index", "--no-ext-diff", "--no-textconv", "--no-renames", "--",
|
|
21
|
+
];
|
|
22
|
+
const GITIGNORE_MAX_BYTES = 5 * 1024 * 1024;
|
|
23
|
+
const gitignoreMutationQueues = new Map();
|
|
24
|
+
const GIT_LOCK_RETRY_ATTEMPTS = 3;
|
|
25
|
+
const GIT_LOCK_RETRY_DELAY_MS = 250;
|
|
26
|
+
const GIT_FETCH_TIMEOUT_MS = 2 * 60 * 1000;
|
|
27
|
+
const GIT_CONFLICT_PREVIEW_MAX_BYTES = 200_000;
|
|
28
|
+
const GIT_STASH_PATCH_MAX_OUTPUT = 200_000;
|
|
29
|
+
const PROTECTED_GIT_BRANCHES = new Set(["main", "master"]);
|
|
30
|
+
const NO_REMOTE_HINT = "No push destination is configured. Publish this repository or add a Git remote, then retry.";
|
|
31
|
+
|
|
32
|
+
const sleepMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
33
|
+
const GIT_BISECT_VERDICTS = new Set(["good", "bad", "old", "new", "skip", "reset"]);
|
|
34
|
+
const GIT_WORKFLOW_MESSAGE_PAIR_SETTLE_MS = 80;
|
|
35
|
+
|
|
36
|
+
function formatWorkflowCommand(command, args) {
|
|
37
|
+
return [command, ...args.map((arg) => (/\s/.test(arg) ? JSON.stringify(arg) : arg))].join(" ");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function formatGitCommand(args) {
|
|
41
|
+
return formatWorkflowCommand("git", args);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function createGitMutationService({
|
|
45
|
+
runCommand,
|
|
46
|
+
makeHttpError,
|
|
47
|
+
makeUserFacingError,
|
|
48
|
+
formatBytes,
|
|
49
|
+
sanitizeError,
|
|
50
|
+
formatCliError,
|
|
51
|
+
formatCommandSpawnError,
|
|
52
|
+
getGitRoot,
|
|
53
|
+
runGitReadCommandDetailed,
|
|
54
|
+
runGitReadCommand,
|
|
55
|
+
readGitChanges,
|
|
56
|
+
resolveGitRelativePath,
|
|
57
|
+
normalizeGitRelativePath,
|
|
58
|
+
isLikelyBinaryBuffer,
|
|
59
|
+
parseGitPorcelainZEntries,
|
|
60
|
+
gitBranchFromPorcelainStatus,
|
|
61
|
+
summarizeGitPorcelainStatus,
|
|
62
|
+
gitUpstreamRef,
|
|
63
|
+
}) {
|
|
64
|
+
/**
|
|
65
|
+
* Keep binary cached-diff bytes separate from runCommand's text buffering.
|
|
66
|
+
* Decoding them would change the staged-content approval token.
|
|
67
|
+
*/
|
|
68
|
+
function runGitStagedContentHashCommand(root) {
|
|
69
|
+
return new Promise((resolve, reject) => {
|
|
70
|
+
const child = spawn("git", STAGED_CONTENT_HASH_ARGS, {
|
|
71
|
+
cwd: root,
|
|
72
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
73
|
+
windowsHide: true,
|
|
74
|
+
env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1", LC_ALL: "C" },
|
|
75
|
+
});
|
|
76
|
+
const stdout = [];
|
|
77
|
+
const stderr = [];
|
|
78
|
+
let stdoutBytes = 0;
|
|
79
|
+
let stderrBytes = 0;
|
|
80
|
+
let settled = false;
|
|
81
|
+
const finish = (error, result) => {
|
|
82
|
+
if (settled) return;
|
|
83
|
+
settled = true;
|
|
84
|
+
clearTimeout(timeout);
|
|
85
|
+
if (error) reject(error);
|
|
86
|
+
else resolve(result);
|
|
87
|
+
};
|
|
88
|
+
const stop = (message) => {
|
|
89
|
+
try { child.kill("SIGKILL"); } catch { /* process already exited */ }
|
|
90
|
+
finish(makeUserFacingError(message));
|
|
91
|
+
};
|
|
92
|
+
const timeout = setTimeout(() => stop(`git diff --cached timed out after ${STAGED_CONTENT_HASH_TIMEOUT_MS / 1000} seconds`), STAGED_CONTENT_HASH_TIMEOUT_MS);
|
|
93
|
+
child.stdout.on("data", (chunk) => {
|
|
94
|
+
const bytes = Buffer.from(chunk);
|
|
95
|
+
stdoutBytes += bytes.length;
|
|
96
|
+
if (stdoutBytes > STAGED_CONTENT_HASH_OUTPUT_LIMIT) {
|
|
97
|
+
stop(`git diff --cached output exceeded the ${STAGED_CONTENT_HASH_OUTPUT_LIMIT / 1024 / 1024} MiB staged-content safety limit`);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
stdout.push(bytes);
|
|
101
|
+
});
|
|
102
|
+
child.stderr.on("data", (chunk) => {
|
|
103
|
+
const bytes = Buffer.from(chunk);
|
|
104
|
+
stderrBytes += bytes.length;
|
|
105
|
+
if (stderrBytes <= 64 * 1024) stderr.push(bytes);
|
|
106
|
+
});
|
|
107
|
+
child.on("error", (error) => finish(makeUserFacingError(formatCommandSpawnError("git", error))));
|
|
108
|
+
child.on("close", (exitCode) => {
|
|
109
|
+
if (exitCode !== 0) {
|
|
110
|
+
const detail = Buffer.concat(stderr).toString("utf8").trim().slice(0, 1200);
|
|
111
|
+
finish(makeUserFacingError(detail ? `git diff --cached failed: ${detail}` : `git diff --cached failed with exit code ${exitCode ?? "unknown"}`));
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
finish(null, Buffer.concat(stdout));
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function stagedContentHashFromDiff(stagedDiff) {
|
|
120
|
+
return createHash("sha256").update(STAGED_CONTENT_HASH_DOMAIN).update(stagedDiff).digest("hex");
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function readStagedContentHash(root) {
|
|
124
|
+
// `git diff --cached` correctly compares the index to the empty tree when
|
|
125
|
+
// HEAD is unborn, so no HEAD lookup is needed (or allowed) here.
|
|
126
|
+
const stagedDiff = await runGitStagedContentHashCommand(root);
|
|
127
|
+
return {
|
|
128
|
+
stagedDiff,
|
|
129
|
+
hasStagedChanges: stagedDiff.length > 0,
|
|
130
|
+
stagedContentHash: stagedDiff.length > 0 ? stagedContentHashFromDiff(stagedDiff) : null,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Read-only same-tab digest of the exact staged content git can commit. */
|
|
135
|
+
async function stagedContentHashForTab(tab) {
|
|
136
|
+
const root = await getGitRoot(tab.cwd);
|
|
137
|
+
const staged = await readStagedContentHash(root);
|
|
138
|
+
return { root, hasStagedChanges: staged.hasStagedChanges, stagedContentHash: staged.stagedContentHash };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function expectedStagedContentHashFromBody(body = {}) {
|
|
142
|
+
const expected = body?.expectedStagedContentHash;
|
|
143
|
+
if (expected === undefined) return ""; // Legacy Guided Git flow: no review was required.
|
|
144
|
+
if (typeof expected !== "string" || !/^[a-f0-9]{64}$/i.test(expected)) {
|
|
145
|
+
throw makeHttpError(400, "expectedStagedContentHash must be a SHA-256 hex digest");
|
|
146
|
+
}
|
|
147
|
+
return expected;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function assertExpectedStagedContentHash(tab, body = {}) {
|
|
151
|
+
const expected = expectedStagedContentHashFromBody(body);
|
|
152
|
+
if (!expected) return "";
|
|
153
|
+
const current = await stagedContentHashForTab(tab);
|
|
154
|
+
if (!current.hasStagedChanges || current.stagedContentHash !== expected) {
|
|
155
|
+
throw makeHttpError(409, "Staged content changed after manual approval. Return to Stage and request a new manual review before continuing.");
|
|
156
|
+
}
|
|
157
|
+
return expected;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
function serializeGitignoreMutation(root, mutation) {
|
|
162
|
+
const previous = gitignoreMutationQueues.get(root) || Promise.resolve();
|
|
163
|
+
const current = previous.catch(() => {}).then(mutation);
|
|
164
|
+
gitignoreMutationQueues.set(root, current);
|
|
165
|
+
return current.finally(() => {
|
|
166
|
+
if (gitignoreMutationQueues.get(root) === current) gitignoreMutationQueues.delete(root);
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function gitignoreEntryForTarget(root, requestedPath, kind) {
|
|
171
|
+
if (kind !== "file" && kind !== "folder") throw makeHttpError(400, "Gitignore target kind must be file or folder");
|
|
172
|
+
if (typeof requestedPath !== "string" || requestedPath.length === 0) throw makeHttpError(400, "Gitignore target path is required");
|
|
173
|
+
if (/[\0-\x1f\x7f]/.test(requestedPath)) throw makeHttpError(400, "Gitignore target path cannot contain control characters");
|
|
174
|
+
|
|
175
|
+
const slashPath = requestedPath.replace(/\\/g, "/");
|
|
176
|
+
if (path.posix.isAbsolute(slashPath) || path.win32.isAbsolute(requestedPath) || /^[A-Za-z]:/.test(requestedPath)) {
|
|
177
|
+
throw makeHttpError(400, "Gitignore target path must be repository-relative");
|
|
178
|
+
}
|
|
179
|
+
const segments = slashPath.split("/").filter(Boolean);
|
|
180
|
+
if (!segments.length || segments.some((segment) => segment === "." || segment === "..")) {
|
|
181
|
+
throw makeHttpError(400, "Gitignore target path cannot be the repository root or contain traversal segments");
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const normalized = segments.join("/");
|
|
185
|
+
const target = path.resolve(root, ...segments);
|
|
186
|
+
const relative = path.relative(root, target);
|
|
187
|
+
if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
188
|
+
throw makeHttpError(400, "Gitignore target path must stay inside the repository");
|
|
189
|
+
}
|
|
190
|
+
const escaped = normalized.replace(/([*?\[\] ])/g, "\\$1");
|
|
191
|
+
return { path: normalized, kind, entry: `/${escaped}${kind === "folder" ? "/" : ""}` };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function sameFileIdentity(first, second) {
|
|
195
|
+
return first?.dev === second?.dev && first?.ino === second?.ino;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function gitignoreHasExactEntry(content, entry) {
|
|
199
|
+
const existing = content.toString("latin1").split(/\r\n|\n|\r/);
|
|
200
|
+
return existing.includes(Buffer.from(entry, "utf8").toString("latin1"));
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function appendGitignoreEntry(root, entry) {
|
|
204
|
+
const target = path.join(root, ".gitignore");
|
|
205
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
206
|
+
let before;
|
|
207
|
+
try {
|
|
208
|
+
before = await lstat(target);
|
|
209
|
+
} catch (error) {
|
|
210
|
+
if (error?.code !== "ENOENT") throw error;
|
|
211
|
+
before = null;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (!before) {
|
|
215
|
+
let handle;
|
|
216
|
+
try {
|
|
217
|
+
handle = await open(target, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | (fsConstants.O_NOFOLLOW || 0), 0o666);
|
|
218
|
+
await handle.writeFile(`${entry}\n`, "utf8");
|
|
219
|
+
return true;
|
|
220
|
+
} catch (error) {
|
|
221
|
+
if (error?.code === "EEXIST" && attempt === 0) continue;
|
|
222
|
+
throw error;
|
|
223
|
+
} finally {
|
|
224
|
+
await handle?.close();
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (before.isSymbolicLink() || !before.isFile()) throw makeHttpError(409, "Repository .gitignore must be a regular file and cannot be a symbolic link");
|
|
229
|
+
if (before.nlink !== 1) throw makeHttpError(409, "Repository .gitignore must have exactly one hard link; replace linked copies with a regular file before retrying");
|
|
230
|
+
|
|
231
|
+
let handle;
|
|
232
|
+
try {
|
|
233
|
+
handle = await open(target, fsConstants.O_RDWR | fsConstants.O_APPEND | (fsConstants.O_NOFOLLOW || 0));
|
|
234
|
+
const opened = await handle.stat();
|
|
235
|
+
if (!opened.isFile() || !sameFileIdentity(before, opened)) throw makeHttpError(409, "Repository .gitignore changed while it was being opened");
|
|
236
|
+
if (opened.nlink !== 1) throw makeHttpError(409, "Repository .gitignore must have exactly one hard link; replace linked copies with a regular file before retrying");
|
|
237
|
+
if (opened.size > GITIGNORE_MAX_BYTES) throw makeHttpError(409, `Repository .gitignore exceeds the ${formatBytes(GITIGNORE_MAX_BYTES)} safe modification limit`);
|
|
238
|
+
const content = await handle.readFile();
|
|
239
|
+
if (gitignoreHasExactEntry(content, entry)) return false;
|
|
240
|
+
const newline = content.includes(Buffer.from("\r\n")) ? "\r\n" : "\n";
|
|
241
|
+
const lastByte = content.length ? content[content.length - 1] : null;
|
|
242
|
+
const separator = content.length && lastByte !== 0x0a && lastByte !== 0x0d ? newline : "";
|
|
243
|
+
await handle.writeFile(`${separator}${entry}${newline}`, "utf8");
|
|
244
|
+
return true;
|
|
245
|
+
} catch (error) {
|
|
246
|
+
if (error?.code === "ENOENT" && attempt === 0) continue;
|
|
247
|
+
if (error?.code === "ELOOP") throw makeHttpError(409, "Repository .gitignore cannot be a symbolic link");
|
|
248
|
+
throw error;
|
|
249
|
+
} finally {
|
|
250
|
+
await handle?.close();
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async function addGitignoreEntry(cwd, body = {}) {
|
|
256
|
+
try {
|
|
257
|
+
const root = await realpath(await getGitRoot(cwd));
|
|
258
|
+
const target = gitignoreEntryForTarget(root, body.path, body.kind);
|
|
259
|
+
const added = await serializeGitignoreMutation(root, () => appendGitignoreEntry(root, target.entry));
|
|
260
|
+
return { root, ...target, added, changes: await readGitChanges(root) };
|
|
261
|
+
} catch (error) {
|
|
262
|
+
if (error?.statusCode) throw error;
|
|
263
|
+
const wrapped = makeHttpError(500, formatCliError(error));
|
|
264
|
+
if (error?.code) wrapped.code = error.code;
|
|
265
|
+
throw wrapped;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async function pullGitChanges(cwd, { remote } = {}) {
|
|
270
|
+
const root = await getGitRoot(cwd);
|
|
271
|
+
const pullArgs = ["pull", "--ff-only"];
|
|
272
|
+
if (remote === "origin") pullArgs.push("origin");
|
|
273
|
+
else if (remote) throw new Error(`Unsupported Git pull remote: ${String(remote)}`);
|
|
274
|
+
const payload = await runGuardedGitMutation(pullArgs, { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS });
|
|
275
|
+
if (payload.data) payload.data.root = root;
|
|
276
|
+
if (payload.ok) payload.data.changes = await readGitChanges(root);
|
|
277
|
+
else {
|
|
278
|
+
payload.error = (payload.data?.stderr || payload.data?.stdout || payload.error || "git pull --ff-only failed").trim();
|
|
279
|
+
applyGitSyncFailure(payload);
|
|
280
|
+
}
|
|
281
|
+
return payload;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function requireConfirmed(body, action) {
|
|
285
|
+
if (body?.confirmed !== true) throw makeHttpError(409, `${action} requires confirmed: true.`);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Retry transient index.lock contention before reporting failure; the shared
|
|
289
|
+
// isGitLockFailure classifier keeps this consistent with worktree mutations.
|
|
290
|
+
async function runGitMutationCommand(args, options = {}) {
|
|
291
|
+
let result;
|
|
292
|
+
for (let attempt = 0; attempt < GIT_LOCK_RETRY_ATTEMPTS; attempt++) {
|
|
293
|
+
result = await runGitWorkflowCommand(args, options);
|
|
294
|
+
const ok = result.exitCode === 0 && !result.timedOut && !result.cancelled && !result.error;
|
|
295
|
+
if (ok || !isGitLockFailure(result)) return result;
|
|
296
|
+
if (attempt < GIT_LOCK_RETRY_ATTEMPTS - 1) await sleepMs(GIT_LOCK_RETRY_DELAY_MS * (attempt + 1));
|
|
297
|
+
}
|
|
298
|
+
return result;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function gitMutationPayload(result) {
|
|
302
|
+
const payload = gitWorkflowCommandPayload(result);
|
|
303
|
+
if (!payload.ok) {
|
|
304
|
+
let pathFailure = null;
|
|
305
|
+
if (isGitLockFailure(result)) {
|
|
306
|
+
payload.code = "REPO_BUSY";
|
|
307
|
+
payload.hint = "Another git process is using this repository. Retry once it finishes.";
|
|
308
|
+
} else {
|
|
309
|
+
pathFailure = classifyGitPathFailure(result);
|
|
310
|
+
if (pathFailure) Object.assign(payload, pathFailure);
|
|
311
|
+
}
|
|
312
|
+
payload.error = pathFailure?.error || String(result?.stderr || result?.stdout || payload.error || "git command failed").trim();
|
|
313
|
+
}
|
|
314
|
+
return payload;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
async function gitAddAllPayload(cwd) {
|
|
318
|
+
await getGitRoot(cwd);
|
|
319
|
+
if (platform() === "win32") {
|
|
320
|
+
const untrackedText = await runGitReadCommand(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--", "."]);
|
|
321
|
+
const invalidPath = findWindowsReservedGitPath(untrackedText);
|
|
322
|
+
const pathFailure = windowsReservedGitPathFailure(invalidPath);
|
|
323
|
+
if (pathFailure) return { ok: false, ...pathFailure };
|
|
324
|
+
}
|
|
325
|
+
return gitMutationPayload(await runGitMutationCommand(["add", "."], { cwd }));
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
async function runGuardedGitMutation(args, options = {}) {
|
|
329
|
+
try {
|
|
330
|
+
return gitMutationPayload(await runGitMutationCommand(args, options));
|
|
331
|
+
} catch (error) {
|
|
332
|
+
if (/already running/i.test(error?.message || "")) {
|
|
333
|
+
return { ok: false, code: "REPO_BUSY", error: sanitizeError(error), hint: "Another git workflow command is already running in the Web UI." };
|
|
334
|
+
}
|
|
335
|
+
throw error;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Turn raw git remote-operation stderr into an actionable state. Returns null
|
|
340
|
+
// when no known pattern matches (caller keeps the raw error).
|
|
341
|
+
function classifyGitSyncFailure(result, { push = false } = {}) {
|
|
342
|
+
const text = `${result?.stderr || ""}\n${result?.stdout || ""}`.toLowerCase();
|
|
343
|
+
if (result?.timedOut) return { code: "NETWORK", hint: "The remote did not respond before the timeout. Check connectivity and retry." };
|
|
344
|
+
if (isGitLockFailure(result)) return { code: "REPO_BUSY", hint: "Another git process is using this repository. Retry once it finishes." };
|
|
345
|
+
if (/terminal prompts disabled|authentication failed|permission denied|access denied|could not read username|could not read password|publickey|invalid credentials/.test(text)) {
|
|
346
|
+
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." };
|
|
347
|
+
}
|
|
348
|
+
if (/could not resolve host|failed to connect|connection (?:refused|reset|timed out)|network is unreachable|operation timed out/.test(text)) {
|
|
349
|
+
return { code: "NETWORK", hint: "The remote could not be reached. Check connectivity and retry." };
|
|
350
|
+
}
|
|
351
|
+
if (push && /fatal:\s+no configured push destination\./.test(text)) {
|
|
352
|
+
return { code: "NO_REMOTE", hint: NO_REMOTE_HINT };
|
|
353
|
+
}
|
|
354
|
+
if (push && /protected branch|gh006/.test(text)) {
|
|
355
|
+
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." };
|
|
356
|
+
}
|
|
357
|
+
if (push && /\[rejected\]|non-fast-forward|fetch first|updates were rejected/.test(text)) {
|
|
358
|
+
return { code: "NON_FAST_FORWARD", hint: "The remote has commits you don't have. Fetch and review the incoming diff, then integrate before pushing." };
|
|
359
|
+
}
|
|
360
|
+
if (push && /has no upstream branch/.test(text)) {
|
|
361
|
+
return { code: "NO_UPSTREAM", hint: "The current branch has no upstream. Push with 'set upstream' to publish it." };
|
|
362
|
+
}
|
|
363
|
+
if (!push && /not possible to fast-forward|divergent branches|need to specify how to reconcile/.test(text)) {
|
|
364
|
+
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." };
|
|
365
|
+
}
|
|
366
|
+
if (!push && /no tracking information/.test(text)) {
|
|
367
|
+
return { code: "NO_UPSTREAM", hint: "The current branch has no upstream to pull from. Set one or pull with an explicit remote/branch." };
|
|
368
|
+
}
|
|
369
|
+
if (/would be overwritten/.test(text)) {
|
|
370
|
+
return { code: "DIRTY_WORKTREE", hint: "Local changes would be overwritten. Stash or commit them first." };
|
|
371
|
+
}
|
|
372
|
+
if (/conflict/.test(text)) {
|
|
373
|
+
return { code: "CONFLICTS", hint: "Conflicts were created. Resolve them in the conflicts panel, then continue or abort the operation." };
|
|
374
|
+
}
|
|
375
|
+
return null;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function applyGitSyncFailure(payload, { push = false } = {}) {
|
|
379
|
+
if (payload.ok || payload.code) return payload;
|
|
380
|
+
const classified = classifyGitSyncFailure(payload.data, { push });
|
|
381
|
+
if (classified) {
|
|
382
|
+
payload.code = classified.code;
|
|
383
|
+
payload.hint = classified.hint;
|
|
384
|
+
}
|
|
385
|
+
return payload;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async function fetchGitChanges(cwd) {
|
|
389
|
+
const root = await getGitRoot(cwd);
|
|
390
|
+
const payload = await runGuardedGitMutation(
|
|
391
|
+
["-c", "credential.interactive=false", "fetch", "--prune"],
|
|
392
|
+
{ cwd: root, timeoutMs: GIT_FETCH_TIMEOUT_MS, label: "git fetch --prune" },
|
|
393
|
+
);
|
|
394
|
+
if (payload.data) payload.data.root = root;
|
|
395
|
+
if (payload.ok) {
|
|
396
|
+
// git fetch reports ref updates on stderr.
|
|
397
|
+
payload.data.summary = `${payload.data.stderr || ""}\n${payload.data.stdout || ""}`.trim();
|
|
398
|
+
payload.data.changes = await readGitChanges(root);
|
|
399
|
+
} else {
|
|
400
|
+
applyGitSyncFailure(payload);
|
|
401
|
+
}
|
|
402
|
+
return payload;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
async function integrateGitUpstream(cwd, body = {}) {
|
|
406
|
+
const mode = String(body.mode || "").trim();
|
|
407
|
+
if (!["merge", "rebase"].includes(mode)) throw makeHttpError(400, "mode must be 'merge' or 'rebase'");
|
|
408
|
+
requireConfirmed(body, `Running git ${mode} against the upstream`);
|
|
409
|
+
const root = await getGitRoot(cwd);
|
|
410
|
+
const upstream = await gitUpstreamRef(root);
|
|
411
|
+
if (!upstream) throw makeHttpError(409, "No upstream is configured for the current branch");
|
|
412
|
+
const args = mode === "merge" ? ["merge", "--no-edit", "@{upstream}"] : ["-c", "core.editor=true", "rebase", "@{upstream}"];
|
|
413
|
+
const payload = await runGuardedGitMutation(args, { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS, label: `git ${mode} ${upstream}` });
|
|
414
|
+
if (payload.data) {
|
|
415
|
+
payload.data.root = root;
|
|
416
|
+
payload.data.upstream = upstream;
|
|
417
|
+
payload.data.mode = mode;
|
|
418
|
+
}
|
|
419
|
+
if (payload.ok) payload.data.changes = await readGitChanges(root);
|
|
420
|
+
else applyGitSyncFailure(payload);
|
|
421
|
+
return payload;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// ---- Git operation (merge/rebase/cherry-pick/revert/bisect) lifecycle ----
|
|
425
|
+
|
|
426
|
+
async function pathEntryExists(target) {
|
|
427
|
+
try {
|
|
428
|
+
await stat(target);
|
|
429
|
+
return true;
|
|
430
|
+
} catch {
|
|
431
|
+
return false;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
async function gitDirPath(root) {
|
|
436
|
+
const out = await runGitReadCommand(root, ["rev-parse", "--git-dir"], { maxOutputLength: 10_000 });
|
|
437
|
+
const dir = out.trim();
|
|
438
|
+
return path.isAbsolute(dir) ? dir : path.resolve(root, dir);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
async function detectGitOperationKind(root) {
|
|
442
|
+
const gitDir = await gitDirPath(root);
|
|
443
|
+
if ((await pathEntryExists(path.join(gitDir, "rebase-merge"))) || (await pathEntryExists(path.join(gitDir, "rebase-apply")))) return "rebase";
|
|
444
|
+
if (await pathEntryExists(path.join(gitDir, "MERGE_HEAD"))) return "merge";
|
|
445
|
+
if (await pathEntryExists(path.join(gitDir, "CHERRY_PICK_HEAD"))) return "cherry-pick";
|
|
446
|
+
if (await pathEntryExists(path.join(gitDir, "REVERT_HEAD"))) return "revert";
|
|
447
|
+
if (await pathEntryExists(path.join(gitDir, "BISECT_LOG"))) return "bisect";
|
|
448
|
+
return null;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function gitOperationCommands(kind) {
|
|
452
|
+
switch (kind) {
|
|
453
|
+
case "merge":
|
|
454
|
+
return { continue: ["commit", "--no-edit"], abort: ["merge", "--abort"], skip: null };
|
|
455
|
+
case "rebase":
|
|
456
|
+
return { continue: ["-c", "core.editor=true", "rebase", "--continue"], abort: ["rebase", "--abort"], skip: ["-c", "core.editor=true", "rebase", "--skip"] };
|
|
457
|
+
case "cherry-pick":
|
|
458
|
+
return { continue: ["-c", "core.editor=true", "cherry-pick", "--continue"], abort: ["cherry-pick", "--abort"], skip: ["-c", "core.editor=true", "cherry-pick", "--skip"] };
|
|
459
|
+
case "revert":
|
|
460
|
+
return { continue: ["-c", "core.editor=true", "revert", "--continue"], abort: ["revert", "--abort"], skip: ["-c", "core.editor=true", "revert", "--skip"] };
|
|
461
|
+
default:
|
|
462
|
+
return null;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function parseGitConflictEntries(porcelainText) {
|
|
467
|
+
const entries = [];
|
|
468
|
+
for (const line of String(porcelainText || "").split(/\r?\n/)) {
|
|
469
|
+
if (!line.startsWith("u ")) continue;
|
|
470
|
+
// u XY sub m1 m2 m3 mW h1 h2 h3 path — 10 space-separated fields, then path.
|
|
471
|
+
const fields = [];
|
|
472
|
+
let start = 0;
|
|
473
|
+
for (let index = 0; index < 10; index++) {
|
|
474
|
+
const next = line.indexOf(" ", start);
|
|
475
|
+
if (next === -1) break;
|
|
476
|
+
fields.push(line.slice(start, next));
|
|
477
|
+
start = next + 1;
|
|
478
|
+
}
|
|
479
|
+
fields.push(line.slice(start));
|
|
480
|
+
const entryPath = fields[10] || "";
|
|
481
|
+
if (entryPath) entries.push({ path: entryPath, status: fields[1] || "UU" });
|
|
482
|
+
}
|
|
483
|
+
return entries;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
function extractConflictMarkerHunks(content, { contextLines = 2, maxHunks = 8, maxLinesPerHunk = 80 } = {}) {
|
|
487
|
+
const lines = content.split(/\r?\n/);
|
|
488
|
+
const hunks = [];
|
|
489
|
+
for (let index = 0; index < lines.length && hunks.length < maxHunks; index++) {
|
|
490
|
+
if (!lines[index].startsWith("<<<<<<<")) continue;
|
|
491
|
+
let end = index;
|
|
492
|
+
while (end < lines.length - 1 && !lines[end].startsWith(">>>>>>>")) end++;
|
|
493
|
+
const start = Math.max(0, index - contextLines);
|
|
494
|
+
const stop = Math.min(lines.length - 1, end + contextLines);
|
|
495
|
+
hunks.push({
|
|
496
|
+
startLine: start + 1,
|
|
497
|
+
truncated: stop - start + 1 > maxLinesPerHunk,
|
|
498
|
+
lines: lines.slice(start, Math.min(stop + 1, start + maxLinesPerHunk)),
|
|
499
|
+
});
|
|
500
|
+
index = end;
|
|
501
|
+
}
|
|
502
|
+
return hunks;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
async function readGitConflictPreview(root, relPath) {
|
|
506
|
+
try {
|
|
507
|
+
const filePath = resolveGitRelativePath(root, relPath);
|
|
508
|
+
const info = await stat(filePath).catch(() => null);
|
|
509
|
+
if (!info) return { kind: "missing" };
|
|
510
|
+
if (!info.isFile()) return { kind: "unsupported", size: info.size };
|
|
511
|
+
if (info.size > GIT_CONFLICT_PREVIEW_MAX_BYTES) return { kind: "large", size: info.size };
|
|
512
|
+
const buffer = await readFile(filePath);
|
|
513
|
+
if (isLikelyBinaryBuffer(buffer)) return { kind: "binary", size: info.size };
|
|
514
|
+
const content = buffer.toString("utf8");
|
|
515
|
+
return {
|
|
516
|
+
kind: "text",
|
|
517
|
+
size: info.size,
|
|
518
|
+
hasMarkers: /^<{7}(?: |$)/m.test(content),
|
|
519
|
+
hunks: extractConflictMarkerHunks(content),
|
|
520
|
+
};
|
|
521
|
+
} catch (error) {
|
|
522
|
+
return { kind: "error", error: sanitizeError(error) };
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
async function readGitOperationSnapshot(cwd) {
|
|
527
|
+
const root = await getGitRoot(cwd);
|
|
528
|
+
const porcelainText = await runGitReadCommand(root, ["status", "--porcelain=2", "--branch", "--untracked-files=all"], { maxOutputLength: 120_000 });
|
|
529
|
+
const summary = summarizeGitPorcelainStatus(porcelainText);
|
|
530
|
+
const kind = await detectGitOperationKind(root);
|
|
531
|
+
const conflictEntries = parseGitConflictEntries(porcelainText);
|
|
532
|
+
const conflicts = [];
|
|
533
|
+
for (const entry of conflictEntries) {
|
|
534
|
+
conflicts.push({ ...entry, preview: await readGitConflictPreview(root, entry.path) });
|
|
535
|
+
}
|
|
536
|
+
const commands = gitOperationCommands(kind);
|
|
537
|
+
let bisect = null;
|
|
538
|
+
if (kind === "bisect") {
|
|
539
|
+
const log = await runGitReadCommand(root, ["bisect", "log"], { maxOutputLength: 60_000 }).catch(() => "");
|
|
540
|
+
bisect = { log: log.trimEnd().split(/\r?\n/).slice(-20).join("\n") };
|
|
541
|
+
}
|
|
542
|
+
return {
|
|
543
|
+
root,
|
|
544
|
+
branch: gitBranchFromPorcelainStatus(porcelainText),
|
|
545
|
+
operation: kind,
|
|
546
|
+
summary,
|
|
547
|
+
conflicts,
|
|
548
|
+
canContinue: Boolean(kind) && kind !== "bisect" && conflictEntries.length === 0,
|
|
549
|
+
canSkip: Boolean(commands?.skip),
|
|
550
|
+
commands: commands
|
|
551
|
+
? {
|
|
552
|
+
continue: formatGitCommand(commands.continue.filter((arg) => arg !== "-c" && arg !== "core.editor=true")),
|
|
553
|
+
abort: formatGitCommand(commands.abort),
|
|
554
|
+
...(commands.skip ? { skip: formatGitCommand(commands.skip.filter((arg) => arg !== "-c" && arg !== "core.editor=true")) } : {}),
|
|
555
|
+
}
|
|
556
|
+
: null,
|
|
557
|
+
bisect,
|
|
558
|
+
generatedAt: new Date().toISOString(),
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
async function gitOperationStageFile(cwd, body = {}) {
|
|
563
|
+
const root = await getGitRoot(cwd);
|
|
564
|
+
const kind = await detectGitOperationKind(root);
|
|
565
|
+
if (!kind) throw makeHttpError(409, "No git operation is in progress");
|
|
566
|
+
const rel = normalizeGitRelativePath(root, body.path);
|
|
567
|
+
const payload = await runGuardedGitMutation(["add", "--", rel], { cwd: root, label: `git add -- ${rel}` });
|
|
568
|
+
if (payload.data) payload.data.root = root;
|
|
569
|
+
if (payload.ok) payload.data.operation = await readGitOperationSnapshot(root);
|
|
570
|
+
return payload;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
async function gitOperationAction(cwd, action, body = {}) {
|
|
574
|
+
const root = await getGitRoot(cwd);
|
|
575
|
+
const kind = await detectGitOperationKind(root);
|
|
576
|
+
if (!kind) throw makeHttpError(409, "No git operation is in progress");
|
|
577
|
+
if (kind === "bisect") throw makeHttpError(409, "Bisect is controlled through /api/git-operation/bisect");
|
|
578
|
+
const commands = gitOperationCommands(kind);
|
|
579
|
+
|
|
580
|
+
let args;
|
|
581
|
+
if (action === "continue") {
|
|
582
|
+
const porcelainText = await runGitReadCommand(root, ["status", "--porcelain=2"], { maxOutputLength: 120_000 });
|
|
583
|
+
if (parseGitConflictEntries(porcelainText).length > 0) {
|
|
584
|
+
return { ok: false, code: "UNMERGED_PATHS", error: "Unmerged paths remain. Resolve and stage every conflicted file before continuing." };
|
|
585
|
+
}
|
|
586
|
+
args = commands.continue;
|
|
587
|
+
} else if (action === "skip") {
|
|
588
|
+
if (!commands.skip) throw makeHttpError(409, `git ${kind} does not support skip`);
|
|
589
|
+
args = commands.skip;
|
|
590
|
+
} else if (action === "abort") {
|
|
591
|
+
requireConfirmed(body, `Aborting the ${kind} operation discards its in-progress state and`);
|
|
592
|
+
args = commands.abort;
|
|
593
|
+
} else {
|
|
594
|
+
throw makeHttpError(400, "Unknown git operation action");
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
const payload = await runGuardedGitMutation(args, { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS });
|
|
598
|
+
if (payload.data) {
|
|
599
|
+
payload.data.root = root;
|
|
600
|
+
payload.data.kind = kind;
|
|
601
|
+
}
|
|
602
|
+
if (payload.ok) payload.data.operation = await readGitOperationSnapshot(root);
|
|
603
|
+
else applyGitSyncFailure(payload);
|
|
604
|
+
return payload;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
async function gitBisectAction(cwd, body = {}) {
|
|
609
|
+
const verdict = String(body.verdict || "").trim().toLowerCase();
|
|
610
|
+
if (!GIT_BISECT_VERDICTS.has(verdict)) throw makeHttpError(400, "verdict must be one of good, bad, old, new, skip, reset");
|
|
611
|
+
const root = await getGitRoot(cwd);
|
|
612
|
+
const kind = await detectGitOperationKind(root);
|
|
613
|
+
if (kind !== "bisect") throw makeHttpError(409, "No git bisect is in progress");
|
|
614
|
+
if (verdict === "reset") requireConfirmed(body, "Resetting the bisect session");
|
|
615
|
+
const payload = await runGuardedGitMutation(["bisect", verdict], { cwd: root });
|
|
616
|
+
if (payload.data) payload.data.root = root;
|
|
617
|
+
if (payload.ok) payload.data.operation = await readGitOperationSnapshot(root);
|
|
618
|
+
return payload;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// ---- Stash ----
|
|
622
|
+
|
|
623
|
+
function cleanGitStashRef(value) {
|
|
624
|
+
const ref = String(value || "").trim();
|
|
625
|
+
if (!/^stash@\{\d{1,4}\}$/.test(ref)) throw makeHttpError(400, "stash ref must look like stash@{0}");
|
|
626
|
+
return ref;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
async function readGitStashes(cwd) {
|
|
630
|
+
const root = await getGitRoot(cwd);
|
|
631
|
+
const out = await runGitReadCommand(root, ["stash", "list", "--format=%gd%x09%at%x09%gs"], { maxOutputLength: 120_000 });
|
|
632
|
+
const stashes = out
|
|
633
|
+
.split(/\r?\n/)
|
|
634
|
+
.filter(Boolean)
|
|
635
|
+
.map((line) => {
|
|
636
|
+
const [ref, epoch, ...subject] = line.split("\t");
|
|
637
|
+
return { ref: ref || "", epochSeconds: Number.parseInt(epoch || "0", 10) || 0, subject: subject.join("\t") };
|
|
638
|
+
})
|
|
639
|
+
.filter((entry) => entry.ref);
|
|
640
|
+
return { root, stashes, generatedAt: new Date().toISOString() };
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
async function readGitStashPreview(cwd, requestedRef) {
|
|
644
|
+
const root = await getGitRoot(cwd);
|
|
645
|
+
const ref = cleanGitStashRef(requestedRef);
|
|
646
|
+
const [statText, patchText] = await Promise.all([
|
|
647
|
+
runGitReadCommand(root, ["stash", "show", "--include-untracked", "--stat", ref], { maxOutputLength: 120_000 }).catch((error) => `(${sanitizeError(error)})`),
|
|
648
|
+
runGitReadCommand(root, ["stash", "show", "--include-untracked", "-p", ref], { maxOutputLength: GIT_STASH_PATCH_MAX_OUTPUT }).catch(() => ""),
|
|
649
|
+
]);
|
|
650
|
+
return { root, ref, stat: statText.trimEnd(), patch: patchText.trimEnd() };
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
async function saveGitStash(cwd, body = {}) {
|
|
654
|
+
const root = await getGitRoot(cwd);
|
|
655
|
+
const args = ["stash", "push"];
|
|
656
|
+
if (body.includeUntracked === true) args.push("--include-untracked");
|
|
657
|
+
if (body.message) args.push("-m", cleanGitCommitMessageInput(body.message));
|
|
658
|
+
const payload = await runGuardedGitMutation(args, { cwd: root });
|
|
659
|
+
if (payload.data) payload.data.root = root;
|
|
660
|
+
if (payload.ok) payload.data.stashes = (await readGitStashes(root)).stashes;
|
|
661
|
+
return payload;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
async function applyGitStash(cwd, body = {}, { pop = false } = {}) {
|
|
665
|
+
const root = await getGitRoot(cwd);
|
|
666
|
+
const ref = cleanGitStashRef(body.ref);
|
|
667
|
+
const payload = await runGuardedGitMutation(["stash", pop ? "pop" : "apply", ref], { cwd: root });
|
|
668
|
+
if (payload.data) {
|
|
669
|
+
payload.data.root = root;
|
|
670
|
+
payload.data.ref = ref;
|
|
671
|
+
}
|
|
672
|
+
if (payload.ok) payload.data.stashes = (await readGitStashes(root)).stashes;
|
|
673
|
+
else if (!payload.code && /conflict/i.test(payload.error || "")) {
|
|
674
|
+
payload.code = "CONFLICTS";
|
|
675
|
+
payload.hint = pop
|
|
676
|
+
? "The stash conflicts with the working tree; git kept the stash entry. Resolve the conflicts, then drop the stash manually."
|
|
677
|
+
: "The stash conflicts with the working tree. Resolve the conflicts or reset the working tree.";
|
|
678
|
+
}
|
|
679
|
+
return payload;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
async function dropGitStash(cwd, body = {}) {
|
|
683
|
+
requireConfirmed(body, "Dropping a stash permanently deletes it and");
|
|
684
|
+
const root = await getGitRoot(cwd);
|
|
685
|
+
const ref = cleanGitStashRef(body.ref);
|
|
686
|
+
const payload = await runGuardedGitMutation(["stash", "drop", ref], { cwd: root });
|
|
687
|
+
if (payload.data) {
|
|
688
|
+
payload.data.root = root;
|
|
689
|
+
payload.data.ref = ref;
|
|
690
|
+
}
|
|
691
|
+
if (payload.ok) payload.data.stashes = (await readGitStashes(root)).stashes;
|
|
692
|
+
return payload;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
// ---- File-level staging ----
|
|
696
|
+
|
|
697
|
+
async function stageGitFile(cwd, body = {}) {
|
|
698
|
+
const root = await getGitRoot(cwd);
|
|
699
|
+
const rel = normalizeGitRelativePath(root, body.path);
|
|
700
|
+
const payload = await runGuardedGitMutation(["add", "--", rel], { cwd: root, label: `git add -- ${rel}` });
|
|
701
|
+
if (payload.data) payload.data.root = root;
|
|
702
|
+
if (payload.ok) payload.data.changes = await readGitChanges(root);
|
|
703
|
+
return payload;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
async function unstageGitFile(cwd, body = {}) {
|
|
707
|
+
const root = await getGitRoot(cwd);
|
|
708
|
+
const rel = normalizeGitRelativePath(root, body.path);
|
|
709
|
+
let payload = await runGuardedGitMutation(["restore", "--staged", "--", rel], { cwd: root, label: `git restore --staged -- ${rel}` });
|
|
710
|
+
if (!payload.ok && /HEAD/.test(payload.error || "")) {
|
|
711
|
+
// Unborn branch (no commit yet): restore --staged has no HEAD to restore from.
|
|
712
|
+
payload = await runGuardedGitMutation(["rm", "--cached", "-r", "--", rel], { cwd: root, label: `git rm --cached -- ${rel}` });
|
|
713
|
+
}
|
|
714
|
+
if (payload.data) payload.data.root = root;
|
|
715
|
+
if (payload.ok) payload.data.changes = await readGitChanges(root);
|
|
716
|
+
return payload;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
async function stageAllGitChanges(cwd) {
|
|
720
|
+
const root = await getGitRoot(cwd);
|
|
721
|
+
const payload = await gitAddAllPayload(root);
|
|
722
|
+
if (payload.data) payload.data.root = root;
|
|
723
|
+
return payload;
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
async function unstageAllGitChanges(cwd) {
|
|
727
|
+
const root = await getGitRoot(cwd);
|
|
728
|
+
let payload = await runGuardedGitMutation(["restore", "--staged", "--", "."], { cwd: root, label: "git restore --staged -- ." });
|
|
729
|
+
if (!payload.ok && /HEAD/.test(payload.error || "")) {
|
|
730
|
+
payload = await runGuardedGitMutation(["rm", "--cached", "-r", "--", "."], { cwd: root, label: "git rm --cached -r -- ." });
|
|
731
|
+
}
|
|
732
|
+
if (payload.data) payload.data.root = root;
|
|
733
|
+
return payload;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
async function discardGitFile(cwd, body = {}) {
|
|
737
|
+
requireConfirmed(body, "Discarding file changes is destructive and");
|
|
738
|
+
const root = await getGitRoot(cwd);
|
|
739
|
+
const rel = normalizeGitRelativePath(root, body.path);
|
|
740
|
+
const payload = await runGuardedGitMutation(["restore", "--", rel], { cwd: root, label: `git restore -- ${rel}` });
|
|
741
|
+
if (payload.data) payload.data.root = root;
|
|
742
|
+
if (payload.ok) payload.data.changes = await readGitChanges(root);
|
|
743
|
+
return payload;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
async function deleteGitUntrackedFile(cwd, body = {}) {
|
|
747
|
+
requireConfirmed(body, "Deleting an untracked file is destructive and");
|
|
748
|
+
const root = await getGitRoot(cwd);
|
|
749
|
+
const rel = normalizeGitRelativePath(root, body.path);
|
|
750
|
+
const listed = await runGitReadCommand(root, ["ls-files", "--others", "--exclude-standard", "--", rel], { maxOutputLength: 120_000 });
|
|
751
|
+
const files = listed.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
|
752
|
+
if (!files.includes(rel)) throw makeHttpError(409, `Not an untracked file: ${rel}`);
|
|
753
|
+
await rm(resolveGitRelativePath(root, rel));
|
|
754
|
+
return { ok: true, data: { root, path: rel, deleted: true, changes: await readGitChanges(root) } };
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// ---- Undo / recovery ----
|
|
758
|
+
|
|
759
|
+
async function readGitUndoState(cwd) {
|
|
760
|
+
const root = await getGitRoot(cwd);
|
|
761
|
+
const [parentProbe, porcelainText, upstream, operation, lastLog] = await Promise.all([
|
|
762
|
+
runCommand("git", ["rev-parse", "--verify", "--quiet", "HEAD~1"], { cwd: root, timeoutMs: 2000 }),
|
|
763
|
+
runGitReadCommand(root, ["status", "--porcelain=2", "--branch"], { maxOutputLength: 120_000 }),
|
|
764
|
+
gitUpstreamRef(root),
|
|
765
|
+
detectGitOperationKind(root),
|
|
766
|
+
runGitReadCommand(root, ["log", "-1", "--format=%h%x09%s"], { maxOutputLength: 10_000 }).catch(() => ""),
|
|
767
|
+
]);
|
|
768
|
+
const summary = summarizeGitPorcelainStatus(porcelainText);
|
|
769
|
+
const hasParent = parentProbe.exitCode === 0;
|
|
770
|
+
const [lastHash = "", ...subjectParts] = lastLog.trim().split("\t");
|
|
771
|
+
const lastSubject = subjectParts.join("\t");
|
|
772
|
+
// With an upstream, "unpushed" means ahead > 0; without one nothing has been
|
|
773
|
+
// published through this branch's tracking ref.
|
|
774
|
+
const unpushed = upstream ? summary.ahead > 0 : true;
|
|
775
|
+
return {
|
|
776
|
+
root,
|
|
777
|
+
hasParent,
|
|
778
|
+
upstream,
|
|
779
|
+
operation,
|
|
780
|
+
summary,
|
|
781
|
+
lastCommit: lastHash ? { hash: lastHash, subject: lastSubject } : null,
|
|
782
|
+
canUndoLastCommit: hasParent && unpushed && !operation,
|
|
783
|
+
canAmendMessage: Boolean(lastHash) && unpushed && !operation && summary.staged === 0,
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
async function undoLastGitCommit(cwd, body = {}) {
|
|
788
|
+
requireConfirmed(body, "Undoing the last commit rewrites HEAD and");
|
|
789
|
+
const state = await readGitUndoState(cwd);
|
|
790
|
+
if (!state.hasParent) throw makeHttpError(409, "HEAD has no parent commit to undo to");
|
|
791
|
+
if (state.operation) throw makeHttpError(409, `Cannot undo during a ${state.operation} operation`);
|
|
792
|
+
if (!state.canUndoLastCommit) throw makeHttpError(409, "The last commit is already pushed to the upstream; undoing it would rewrite published history");
|
|
793
|
+
const payload = await runGuardedGitMutation(["reset", "--soft", "HEAD~1"], { cwd: state.root });
|
|
794
|
+
if (payload.data) {
|
|
795
|
+
payload.data.root = state.root;
|
|
796
|
+
payload.data.undoneCommit = state.lastCommit;
|
|
797
|
+
payload.data.restoreCommand = "git reset --soft ORIG_HEAD";
|
|
798
|
+
}
|
|
799
|
+
if (payload.ok) payload.data.changes = await readGitChanges(state.root);
|
|
800
|
+
return payload;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
async function amendLastGitCommitMessage(cwd, body = {}) {
|
|
804
|
+
requireConfirmed(body, "Amending the last commit rewrites HEAD and");
|
|
805
|
+
const message = cleanGitCommitMessageInput(body.message);
|
|
806
|
+
const state = await readGitUndoState(cwd);
|
|
807
|
+
if (!state.lastCommit) throw makeHttpError(409, "There is no commit to amend");
|
|
808
|
+
if (state.operation) throw makeHttpError(409, `Cannot amend during a ${state.operation} operation`);
|
|
809
|
+
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.");
|
|
810
|
+
if (!state.canAmendMessage) throw makeHttpError(409, "The last commit is already pushed to the upstream; amending it would rewrite published history");
|
|
811
|
+
const payload = await runGuardedGitMutation(["commit", "--amend", "-m", message], { cwd: state.root, label: "git commit --amend -m <message>" });
|
|
812
|
+
if (payload.data) {
|
|
813
|
+
payload.data.root = state.root;
|
|
814
|
+
payload.data.previousCommit = state.lastCommit;
|
|
815
|
+
payload.data.restoreCommand = "git reset --soft ORIG_HEAD";
|
|
816
|
+
}
|
|
817
|
+
return payload;
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
async function readGitReflog(cwd) {
|
|
821
|
+
const root = await getGitRoot(cwd);
|
|
822
|
+
const out = await runGitReadCommand(root, ["reflog", "-n", "20", "--format=%h%x09%gd%x09%cI%x09%gs"], { maxOutputLength: 120_000 });
|
|
823
|
+
const entries = out
|
|
824
|
+
.split(/\r?\n/)
|
|
825
|
+
.filter(Boolean)
|
|
826
|
+
.map((line) => {
|
|
827
|
+
const [hash, selector, date, ...subject] = line.split("\t");
|
|
828
|
+
return { hash: hash || "", selector: selector || "", date: date || "", subject: subject.join("\t") };
|
|
829
|
+
});
|
|
830
|
+
return { root, entries, generatedAt: new Date().toISOString() };
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
// ---- Submodules ----
|
|
834
|
+
|
|
835
|
+
async function readGitSubmodules(cwd) {
|
|
836
|
+
const root = await getGitRoot(cwd);
|
|
837
|
+
if (!(await regularFileExists(path.join(root, ".gitmodules")))) {
|
|
838
|
+
return { root, hasSubmodules: false, submodules: [], dirty: 0 };
|
|
839
|
+
}
|
|
840
|
+
const out = await runGitReadCommand(root, ["submodule", "status", "--recursive"], { timeoutMs: 30_000, maxOutputLength: 200_000 });
|
|
841
|
+
const submodules = out
|
|
842
|
+
.split(/\r?\n/)
|
|
843
|
+
.filter(Boolean)
|
|
844
|
+
.map((line) => {
|
|
845
|
+
const flag = line[0] || " ";
|
|
846
|
+
const rest = line.slice(1).trim();
|
|
847
|
+
const firstSpace = rest.indexOf(" ");
|
|
848
|
+
const sha = firstSpace === -1 ? rest : rest.slice(0, firstSpace);
|
|
849
|
+
const remainder = firstSpace === -1 ? "" : rest.slice(firstSpace + 1);
|
|
850
|
+
const describeMatch = remainder.match(/^(.*?)( \([^)]*\))?$/);
|
|
851
|
+
return {
|
|
852
|
+
sha,
|
|
853
|
+
path: (describeMatch?.[1] ?? remainder).trim(),
|
|
854
|
+
describe: describeMatch?.[2] ? describeMatch[2].trim().replace(/^\(|\)$/g, "") : "",
|
|
855
|
+
state: flag === "-" ? "uninitialized" : flag === "+" ? "out-of-sync" : flag === "U" ? "conflicts" : "clean",
|
|
856
|
+
};
|
|
857
|
+
});
|
|
858
|
+
return { root, hasSubmodules: true, submodules, dirty: submodules.filter((item) => item.state !== "clean").length };
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
async function updateGitSubmodules(cwd, body = {}) {
|
|
862
|
+
requireConfirmed(body, "Recursively updating submodules can check out new commits and");
|
|
863
|
+
const root = await getGitRoot(cwd);
|
|
864
|
+
const payload = await runGuardedGitMutation(["submodule", "update", "--init", "--recursive"], { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS });
|
|
865
|
+
if (payload.data) payload.data.root = root;
|
|
866
|
+
if (payload.ok) payload.data.submodules = (await readGitSubmodules(root)).submodules;
|
|
867
|
+
return payload;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// ---- Tags ----
|
|
871
|
+
|
|
872
|
+
function cleanGitTagName(value) {
|
|
873
|
+
const name = String(value || "").trim();
|
|
874
|
+
if (!name || name.includes("\0") || name.includes("@{") || name.startsWith("-") || name.startsWith("/") || /\s/.test(name)) {
|
|
875
|
+
throw makeHttpError(400, "Invalid tag name");
|
|
876
|
+
}
|
|
877
|
+
return name;
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
async function validateGitTagName(root, name) {
|
|
881
|
+
const result = await runCommand("git", ["check-ref-format", `refs/tags/${name}`], { cwd: root, timeoutMs: 5000 });
|
|
882
|
+
if (result.exitCode !== 0) throw makeHttpError(400, `Invalid tag name: ${name}`);
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
async function readGitTags(cwd) {
|
|
886
|
+
const root = await getGitRoot(cwd);
|
|
887
|
+
const [headOut, recentOut] = await Promise.all([
|
|
888
|
+
runGitReadCommand(root, ["tag", "--points-at", "HEAD", "--sort=-creatordate"], { maxOutputLength: 60_000 }).catch(() => ""),
|
|
889
|
+
runGitReadCommand(
|
|
890
|
+
root,
|
|
891
|
+
["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)"],
|
|
892
|
+
{ maxOutputLength: 120_000 },
|
|
893
|
+
).catch(() => ""),
|
|
894
|
+
]);
|
|
895
|
+
const headTags = headOut.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
|
896
|
+
const tags = recentOut
|
|
897
|
+
.split(/\r?\n/)
|
|
898
|
+
.filter(Boolean)
|
|
899
|
+
.map((line) => {
|
|
900
|
+
const [name, objectType, objectName, target, date, ...subject] = line.split("\t");
|
|
901
|
+
return {
|
|
902
|
+
name: name || "",
|
|
903
|
+
annotated: objectType === "tag",
|
|
904
|
+
target: (objectType === "tag" ? target : objectName) || "",
|
|
905
|
+
date: date || "",
|
|
906
|
+
subject: subject.join("\t"),
|
|
907
|
+
atHead: headTags.includes(name || ""),
|
|
908
|
+
};
|
|
909
|
+
});
|
|
910
|
+
return { root, headTags, tags, generatedAt: new Date().toISOString() };
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
async function createGitTag(cwd, body = {}) {
|
|
914
|
+
requireConfirmed(body, "Creating a tag");
|
|
915
|
+
const root = await getGitRoot(cwd);
|
|
916
|
+
const name = cleanGitTagName(body.name);
|
|
917
|
+
await validateGitTagName(root, name);
|
|
918
|
+
const message = cleanGitCommitMessageInput(body.message || name);
|
|
919
|
+
const payload = await runGuardedGitMutation(["tag", "-a", name, "-m", message], { cwd: root, label: `git tag -a ${name} -m <message>` });
|
|
920
|
+
if (payload.data) {
|
|
921
|
+
payload.data.root = root;
|
|
922
|
+
payload.data.tag = name;
|
|
923
|
+
// Tags never leave the machine implicitly; pushing stays a separate,
|
|
924
|
+
// explicit action.
|
|
925
|
+
payload.data.pushCommand = `git push ${"origin"} ${name}`;
|
|
926
|
+
}
|
|
927
|
+
if (payload.ok) payload.data.tags = (await readGitTags(root)).tags;
|
|
928
|
+
return payload;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
// ---- Signing diagnostics ----
|
|
932
|
+
|
|
933
|
+
async function readGitSigningDiagnostics(cwd) {
|
|
934
|
+
const root = await getGitRoot(cwd);
|
|
935
|
+
const readConfig = async (args) => {
|
|
936
|
+
const result = await runCommand("git", ["config", ...args], { cwd: root, timeoutMs: 2000 });
|
|
937
|
+
return result.exitCode === 0 ? result.stdout.trim() : "";
|
|
938
|
+
};
|
|
939
|
+
const [gpgSign, gpgFormat, signingKey, lastLog] = await Promise.all([
|
|
940
|
+
readConfig(["--bool", "--get", "commit.gpgsign"]),
|
|
941
|
+
readConfig(["--get", "gpg.format"]),
|
|
942
|
+
readConfig(["--get", "user.signingkey"]),
|
|
943
|
+
runGitReadCommand(root, ["log", "-1", "--format=%h%x09%G?%x09%GS"], { maxOutputLength: 10_000 }).catch(() => ""),
|
|
944
|
+
]);
|
|
945
|
+
const [lastHash = "", signState = "", signer = ""] = lastLog.trim().split("\t");
|
|
946
|
+
const commitSignRequired = gpgSign.toLowerCase() === "true";
|
|
947
|
+
const normalizedState = signState.trim().toUpperCase();
|
|
948
|
+
const mismatch = commitSignRequired && (!normalizedState || normalizedState === "N" || normalizedState === "E");
|
|
949
|
+
const suggestions = [];
|
|
950
|
+
if (mismatch) {
|
|
951
|
+
if (!signingKey) suggestions.push({ label: "Set your signing key (repo only)", command: "git config user.signingkey <KEY-ID>" });
|
|
952
|
+
suggestions.push({ label: "Re-sign the last commit", command: "git commit --amend --no-edit -S" });
|
|
953
|
+
suggestions.push({ label: "Disable signing for this repository", command: "git config commit.gpgsign false" });
|
|
954
|
+
}
|
|
955
|
+
return {
|
|
956
|
+
root,
|
|
957
|
+
commitSignRequired,
|
|
958
|
+
gpgFormat: gpgFormat || "(default: gpg)",
|
|
959
|
+
signingKey: signingKey || "(not set)",
|
|
960
|
+
lastCommit: lastHash ? { hash: lastHash, signState: normalizedState || "N", signer } : null,
|
|
961
|
+
mismatch,
|
|
962
|
+
suggestions,
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
function gitWorkflowMessageCwd(root, cwd) {
|
|
967
|
+
const repositoryRoot = path.resolve(root);
|
|
968
|
+
const suppliedCwd = path.resolve(String(cwd || repositoryRoot));
|
|
969
|
+
if (suppliedCwd !== repositoryRoot && !pathInside(repositoryRoot, suppliedCwd)) {
|
|
970
|
+
throw new Error(`Git workflow cwd must stay inside repository root: ${suppliedCwd}`);
|
|
971
|
+
}
|
|
972
|
+
return repositoryRoot;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
function gitWorkflowMessageFileMeta(root, messageCwd, filePath) {
|
|
976
|
+
return {
|
|
977
|
+
path: filePath,
|
|
978
|
+
relativePath: path.relative(messageCwd, filePath).split(path.sep).join("/"),
|
|
979
|
+
repoRelativePath: path.relative(root, filePath).split(path.sep).join("/"),
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
function commitMessagePaths(baseDir) {
|
|
984
|
+
return {
|
|
985
|
+
shortPath: path.join(baseDir, "dev", "COMMIT", "staged-commit-short.txt"),
|
|
986
|
+
longPath: path.join(baseDir, "dev", "COMMIT", "staged-commit-long.txt"),
|
|
987
|
+
branchPath: path.join(baseDir, "dev", "COMMIT", "staged-branch-name.txt"),
|
|
988
|
+
};
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
function assertGitWorkflowArtifactGenerationReady(generationId, generation, kind) {
|
|
992
|
+
if (!generationId) return;
|
|
993
|
+
if (!generation || generation.id !== generationId || generation.kind !== kind) {
|
|
994
|
+
throw new Error(`This ${kind} generation is no longer active. Regenerate the artifact.`);
|
|
995
|
+
}
|
|
996
|
+
if (!generation.terminal) throw new Error(`The correlated ${kind} generation is still running.`);
|
|
997
|
+
if (!generation.successful) throw new Error(`The correlated ${kind} generation did not finish successfully. Regenerate the artifact.`);
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
async function readGitWorkflowBranchName(cwd, { generationId = "", generation = null } = {}) {
|
|
1001
|
+
assertGitWorkflowArtifactGenerationReady(generationId, generation, "branch");
|
|
1002
|
+
const root = await getGitRoot(cwd);
|
|
1003
|
+
const messageCwd = gitWorkflowMessageCwd(root, cwd);
|
|
1004
|
+
const { branchPath } = commitMessagePaths(messageCwd);
|
|
1005
|
+
try {
|
|
1006
|
+
const [branchText, branchStat] = await Promise.all([readFile(branchPath, "utf8"), stat(branchPath)]);
|
|
1007
|
+
const branch = branchText.split(/\r?\n/).find((line) => line.trim())?.trim() || "";
|
|
1008
|
+
if (!branch) throw new Error(`${branchPath} is empty`);
|
|
1009
|
+
const branchFile = gitWorkflowMessageFileMeta(root, messageCwd, branchPath);
|
|
1010
|
+
return {
|
|
1011
|
+
root,
|
|
1012
|
+
cwd: messageCwd,
|
|
1013
|
+
branchPath,
|
|
1014
|
+
branchRelativePath: branchFile.relativePath,
|
|
1015
|
+
branchRepoRelativePath: branchFile.repoRelativePath,
|
|
1016
|
+
branch,
|
|
1017
|
+
mtimeMs: branchStat.mtimeMs,
|
|
1018
|
+
ctimeMs: branchStat.ctimeMs,
|
|
1019
|
+
ino: String(branchStat.ino),
|
|
1020
|
+
};
|
|
1021
|
+
} catch (error) {
|
|
1022
|
+
throw new Error(`Missing generated branch name file ${branchPath}. Run /git-branch-name first. ${sanitizeError(error)}`);
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
function gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, reason, details = {}) {
|
|
1027
|
+
const shortFile = gitWorkflowMessageFileMeta(root, messageCwd, paths.shortPath);
|
|
1028
|
+
const longFile = gitWorkflowMessageFileMeta(root, messageCwd, paths.longPath);
|
|
1029
|
+
return {
|
|
1030
|
+
ready: false,
|
|
1031
|
+
generationId,
|
|
1032
|
+
reason,
|
|
1033
|
+
root,
|
|
1034
|
+
cwd: messageCwd,
|
|
1035
|
+
shortPath: paths.shortPath,
|
|
1036
|
+
longPath: paths.longPath,
|
|
1037
|
+
shortRelativePath: shortFile.relativePath,
|
|
1038
|
+
longRelativePath: longFile.relativePath,
|
|
1039
|
+
shortRepoRelativePath: shortFile.repoRelativePath,
|
|
1040
|
+
longRepoRelativePath: longFile.repoRelativePath,
|
|
1041
|
+
...details,
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
async function readGitWorkflowMessages(cwd, { generationId = "", generation = null } = {}) {
|
|
1046
|
+
const root = await getGitRoot(cwd);
|
|
1047
|
+
const messageCwd = gitWorkflowMessageCwd(root, cwd);
|
|
1048
|
+
const paths = commitMessagePaths(messageCwd);
|
|
1049
|
+
if (generationId && (!generation || generation.id !== generationId || generation.kind !== "commit" || generation.cwd !== messageCwd)) {
|
|
1050
|
+
return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, "This commit-message generation is no longer active. Regenerate the message files.", { expired: true });
|
|
1051
|
+
}
|
|
1052
|
+
if (generationId && !generation.terminal) {
|
|
1053
|
+
return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, "The correlated commit-message generation is still running.", { running: true });
|
|
1054
|
+
}
|
|
1055
|
+
if (generationId && !generation.successful) {
|
|
1056
|
+
return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, "The correlated commit-message generation did not finish successfully. Regenerate the message files.", { expired: true });
|
|
1057
|
+
}
|
|
1058
|
+
try {
|
|
1059
|
+
let pair = await readStableGitMessageArtifactPair(paths);
|
|
1060
|
+
if (generationId) {
|
|
1061
|
+
const readiness = gitMessageArtifactPairReadiness(generation.baseline, pair);
|
|
1062
|
+
if (!readiness.ready) return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, readiness.reason, readiness);
|
|
1063
|
+
await new Promise((resolve) => setTimeout(resolve, GIT_WORKFLOW_MESSAGE_PAIR_SETTLE_MS));
|
|
1064
|
+
const settledPair = await readStableGitMessageArtifactPair(paths);
|
|
1065
|
+
if (!sameGitMessageArtifactPair(pair, settledPair)) {
|
|
1066
|
+
return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, "Generated commit message files are still settling.");
|
|
1067
|
+
}
|
|
1068
|
+
const settledReadiness = gitMessageArtifactPairReadiness(generation.baseline, settledPair);
|
|
1069
|
+
if (!settledReadiness.ready) return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, settledReadiness.reason, settledReadiness);
|
|
1070
|
+
pair = settledPair;
|
|
1071
|
+
}
|
|
1072
|
+
if (!pair.short.exists || !pair.long.exists) {
|
|
1073
|
+
throw new Error(`Missing ${!pair.short.exists ? paths.shortPath : paths.longPath}`);
|
|
1074
|
+
}
|
|
1075
|
+
const shortFile = gitWorkflowMessageFileMeta(root, messageCwd, paths.shortPath);
|
|
1076
|
+
const longFile = gitWorkflowMessageFileMeta(root, messageCwd, paths.longPath);
|
|
1077
|
+
return {
|
|
1078
|
+
ready: true,
|
|
1079
|
+
generationId,
|
|
1080
|
+
root,
|
|
1081
|
+
cwd: messageCwd,
|
|
1082
|
+
shortPath: paths.shortPath,
|
|
1083
|
+
longPath: paths.longPath,
|
|
1084
|
+
shortRelativePath: shortFile.relativePath,
|
|
1085
|
+
longRelativePath: longFile.relativePath,
|
|
1086
|
+
shortRepoRelativePath: shortFile.repoRelativePath,
|
|
1087
|
+
longRepoRelativePath: longFile.repoRelativePath,
|
|
1088
|
+
short: pair.short.text.trimEnd(),
|
|
1089
|
+
long: pair.long.text.trimEnd(),
|
|
1090
|
+
shortMtimeMs: Number(BigInt(pair.short.mtimeNs) / 1_000_000n),
|
|
1091
|
+
longMtimeMs: Number(BigInt(pair.long.mtimeNs) / 1_000_000n),
|
|
1092
|
+
shortSha256: pair.short.sha256,
|
|
1093
|
+
longSha256: pair.long.sha256,
|
|
1094
|
+
};
|
|
1095
|
+
} catch (error) {
|
|
1096
|
+
throw new Error(`Missing or unstable generated commit message files in ${path.join(messageCwd, "dev", "COMMIT")}. Run /git-staged-msg first. ${sanitizeError(error)}`);
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
function cleanGitBranchName(value) {
|
|
1101
|
+
const branch = String(value || "").trim();
|
|
1102
|
+
if (!branch) throw new Error("branch is required");
|
|
1103
|
+
if (branch.includes("\0") || branch.includes("@{") || branch.startsWith("-") || branch.startsWith("/")) throw new Error("invalid branch name");
|
|
1104
|
+
return branch;
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
function cleanGitCommitMessageInput(value) {
|
|
1108
|
+
const message = String(value || "").replace(/\r\n?/g, "\n").trim();
|
|
1109
|
+
if (!message) throw new Error("commit message is required");
|
|
1110
|
+
if (message.includes("\0")) throw new Error("commit message contains a NUL byte");
|
|
1111
|
+
if (message.length > 10000) throw new Error("commit message is too long");
|
|
1112
|
+
return message;
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
|
|
1116
|
+
function gitWorkflowDefaultCommitAction(entry) {
|
|
1117
|
+
if (!entry || entry.y !== " ") return "";
|
|
1118
|
+
if (entry.x === "A") return "created";
|
|
1119
|
+
if (entry.x === "M" || entry.x === "T") return "updated";
|
|
1120
|
+
if (entry.x === "D") return "deleted";
|
|
1121
|
+
return "";
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
function formatGitWorkflowDefaultCommitPath(filePath) {
|
|
1125
|
+
return String(filePath || "").replace(/[\0\r\n\t]+/g, " ").replace(/\s+/g, " ").trim().slice(0, 4000);
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
async function readGitWorkflowDefaultCommitMessage(cwd) {
|
|
1129
|
+
const root = await getGitRoot(cwd);
|
|
1130
|
+
const statusText = await runGitReadCommand(root, ["status", "--porcelain=v1", "-z", "--untracked-files=all"], { maxOutputLength: 120_000 });
|
|
1131
|
+
const entries = parseGitPorcelainZEntries(statusText);
|
|
1132
|
+
const empty = (reason, extra = {}) => ({ root, message: "", reason, ...extra });
|
|
1133
|
+
if (entries.length === 0) return empty("No changed files are ready for a default commit message.");
|
|
1134
|
+
if (entries.length !== 1) return empty(`Expected exactly one changed file for a default commit message; found ${entries.length}.`);
|
|
1135
|
+
const [entry] = entries;
|
|
1136
|
+
const action = gitWorkflowDefaultCommitAction(entry);
|
|
1137
|
+
const displayPath = formatGitWorkflowDefaultCommitPath(entry.path);
|
|
1138
|
+
if (!action || !displayPath) {
|
|
1139
|
+
return empty("The only changed file is not a staged created, updated, or deleted file.", { path: entry.path || "" });
|
|
1140
|
+
}
|
|
1141
|
+
return {
|
|
1142
|
+
root,
|
|
1143
|
+
message: `${action} ${displayPath}`,
|
|
1144
|
+
action,
|
|
1145
|
+
path: entry.path,
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
function cleanGitHubUsername(value) {
|
|
1150
|
+
const username = String(value || "").trim().replace(/^@+/, "");
|
|
1151
|
+
if (!username) throw new Error("GitHub username is required");
|
|
1152
|
+
if (username.length > 39 || !/^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/.test(username) || username.includes("--")) {
|
|
1153
|
+
throw new Error("Invalid GitHub username");
|
|
1154
|
+
}
|
|
1155
|
+
return username;
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
function cleanGitHubRepoName(value) {
|
|
1159
|
+
let repoName = String(value || "").trim();
|
|
1160
|
+
const githubUrlMatch = repoName.match(/github\.com[:/][^/\s]+\/([^/\s]+?)(?:\.git)?\/?$/i);
|
|
1161
|
+
if (githubUrlMatch) repoName = githubUrlMatch[1];
|
|
1162
|
+
if (repoName.includes("/")) repoName = repoName.split("/").filter(Boolean).pop() || "";
|
|
1163
|
+
repoName = repoName.replace(/\.git$/i, "");
|
|
1164
|
+
if (!repoName) throw new Error("GitHub repository name is required");
|
|
1165
|
+
if (repoName.length > 100 || repoName === "." || repoName === ".." || !/^[A-Za-z0-9._-]+$/.test(repoName)) {
|
|
1166
|
+
throw new Error("Invalid GitHub repository name");
|
|
1167
|
+
}
|
|
1168
|
+
return repoName;
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
function gitHubOriginUrl(username, repoName) {
|
|
1172
|
+
return `https://github.com/${cleanGitHubUsername(username)}/${cleanGitHubRepoName(repoName)}.git`;
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
function defaultGitRepoNameFromRoot(root) {
|
|
1176
|
+
try {
|
|
1177
|
+
return cleanGitHubRepoName(path.basename(root));
|
|
1178
|
+
} catch {
|
|
1179
|
+
return "new-repo";
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
async function ensureOutsideGitRepository(cwd) {
|
|
1184
|
+
const result = await runCommand("git", ["rev-parse", "--show-toplevel"], { cwd, timeoutMs: 2000 });
|
|
1185
|
+
if (result.exitCode === 0 && result.stdout.trim()) throw new Error(`Already inside a git repository: ${path.resolve(result.stdout.trim())}`);
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
async function regularFileExists(filePath) {
|
|
1189
|
+
try {
|
|
1190
|
+
return (await stat(filePath)).isFile();
|
|
1191
|
+
} catch (error) {
|
|
1192
|
+
if (error?.code === "ENOENT") return false;
|
|
1193
|
+
throw error;
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
async function detectRepositoryStack(root) {
|
|
1198
|
+
let names = new Set();
|
|
1199
|
+
try {
|
|
1200
|
+
names = new Set(await readdir(root));
|
|
1201
|
+
} catch {
|
|
1202
|
+
return "";
|
|
1203
|
+
}
|
|
1204
|
+
const detected = [];
|
|
1205
|
+
if (names.has("package.json")) {
|
|
1206
|
+
try {
|
|
1207
|
+
const manifest = JSON.parse(await readFile(path.join(root, "package.json"), "utf8"));
|
|
1208
|
+
const deps = { ...(manifest.dependencies || {}), ...(manifest.devDependencies || {}) };
|
|
1209
|
+
if (deps.next) detected.push("Next.js");
|
|
1210
|
+
else if (deps.react || deps.vite) detected.push("React / Vite");
|
|
1211
|
+
else detected.push("Node.js / TypeScript");
|
|
1212
|
+
if (deps.typescript || names.has("tsconfig.json")) detected.push("TypeScript");
|
|
1213
|
+
} catch {
|
|
1214
|
+
detected.push("Node.js");
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
if (names.has("pyproject.toml") || names.has("requirements.txt") || names.has("setup.py")) detected.push("Python");
|
|
1218
|
+
if (names.has("manage.py")) detected.push("Django");
|
|
1219
|
+
if (names.has("Cargo.toml")) detected.push("Rust");
|
|
1220
|
+
if (names.has("go.mod")) detected.push("Go");
|
|
1221
|
+
if (names.has("pom.xml") || names.has("build.gradle") || names.has("build.gradle.kts")) detected.push("Java / Gradle");
|
|
1222
|
+
if (names.has("Dockerfile") || names.has("docker-compose.yml") || names.has("compose.yml")) detected.push("Docker");
|
|
1223
|
+
return [...new Set(detected)].join(", ");
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
async function initialRepositoryFilesStatus(cwd) {
|
|
1227
|
+
const root = await getGitRoot(cwd);
|
|
1228
|
+
const readmePath = path.join(root, "README.md");
|
|
1229
|
+
const gitignorePath = path.join(root, ".gitignore");
|
|
1230
|
+
const [readmeExists, gitignoreExists, detectedStack] = await Promise.all([
|
|
1231
|
+
regularFileExists(readmePath),
|
|
1232
|
+
regularFileExists(gitignorePath),
|
|
1233
|
+
detectRepositoryStack(root),
|
|
1234
|
+
]);
|
|
1235
|
+
return { root, readmePath, gitignorePath, readmeExists, gitignoreExists, detectedStack };
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
function gitignoreLinesForStack(stackInput, detectedStack = "") {
|
|
1239
|
+
const stack = `${stackInput || ""} ${detectedStack || ""}`.toLowerCase();
|
|
1240
|
+
const sections = [
|
|
1241
|
+
["# OS / editors", ".DS_Store", "Thumbs.db", ".idea/", ".vscode/", "*.swp", "*.swo"],
|
|
1242
|
+
["# Local env / secrets", ".env", ".env.*", "!.env.example", "*.local"],
|
|
1243
|
+
["# Logs / temp", "*.log", "logs/", "tmp/", "temp/", ".cache/"],
|
|
1244
|
+
];
|
|
1245
|
+
if (/node|npm|pnpm|yarn|bun|typescript|javascript|react|vite|next/.test(stack)) {
|
|
1246
|
+
sections.push(["# Node / frontend", "node_modules/", "dist/", "build/", ".next/", "out/", "coverage/", ".turbo/", ".vite/", "*.tsbuildinfo"]);
|
|
1247
|
+
}
|
|
1248
|
+
if (/python|django|fastapi|flask/.test(stack)) {
|
|
1249
|
+
sections.push(["# Python", "__pycache__/", "*.py[cod]", ".pytest_cache/", ".ruff_cache/", ".mypy_cache/", ".venv/", "venv/", "htmlcov/", "*.egg-info/"]);
|
|
1250
|
+
}
|
|
1251
|
+
if (/rust|cargo/.test(stack)) sections.push(["# Rust", "target/"]);
|
|
1252
|
+
if (/\bgo\b|golang/.test(stack)) sections.push(["# Go", "bin/", "*.test", "coverage.out"]);
|
|
1253
|
+
if (/java|gradle|maven|kotlin/.test(stack)) sections.push(["# Java / JVM", "target/", "build/", ".gradle/", "*.class"]);
|
|
1254
|
+
if (/docker|container/.test(stack)) sections.push(["# Docker", ".docker/", "docker-compose.override.yml"]);
|
|
1255
|
+
if (sections.length === 3) {
|
|
1256
|
+
sections.push(["# Common dependency / build outputs", "node_modules/", ".venv/", "venv/", "target/", "dist/", "build/", "coverage/", "vendor/", "*.tmp"]);
|
|
1257
|
+
}
|
|
1258
|
+
const seen = new Set();
|
|
1259
|
+
const lines = [];
|
|
1260
|
+
for (const section of sections) {
|
|
1261
|
+
lines.push(section[0]);
|
|
1262
|
+
for (const pattern of section.slice(1)) {
|
|
1263
|
+
if (seen.has(pattern)) continue;
|
|
1264
|
+
seen.add(pattern);
|
|
1265
|
+
lines.push(pattern);
|
|
1266
|
+
}
|
|
1267
|
+
lines.push("");
|
|
1268
|
+
}
|
|
1269
|
+
return `${lines.join("\n").replace(/\n{3,}/g, "\n\n").trim()}\n`;
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
async function prepareInitialRepositoryFiles(cwd, { repoName: repoNameInput, stack = "" } = {}) {
|
|
1273
|
+
const before = await initialRepositoryFilesStatus(cwd);
|
|
1274
|
+
const repoName = repoNameInput ? cleanGitHubRepoName(repoNameInput) : defaultGitRepoNameFromRoot(before.root);
|
|
1275
|
+
if (await regularFileExists(before.readmePath)) {
|
|
1276
|
+
// Explicit pre-add check: keep existing README.md unchanged.
|
|
1277
|
+
} else {
|
|
1278
|
+
await writeFile(before.readmePath, `# ${repoName}\n\nInitialized by Pi Web UI.\n`, "utf8");
|
|
1279
|
+
}
|
|
1280
|
+
let gitignoreCreated = false;
|
|
1281
|
+
let gitignoreSource = before.gitignoreExists ? "existing" : "fallback";
|
|
1282
|
+
if (!(await regularFileExists(before.gitignorePath))) {
|
|
1283
|
+
await writeFile(before.gitignorePath, gitignoreLinesForStack(stack, before.detectedStack), "utf8");
|
|
1284
|
+
gitignoreCreated = true;
|
|
1285
|
+
}
|
|
1286
|
+
const payload = gitMutationPayload(await runGitMutationCommand(["add", "--", "README.md", ".gitignore"], { cwd: before.root, label: "git add README.md .gitignore" }));
|
|
1287
|
+
if (payload.data) {
|
|
1288
|
+
payload.data.root = before.root;
|
|
1289
|
+
payload.data.readme = { path: before.readmePath, exists: true, created: !before.readmeExists };
|
|
1290
|
+
payload.data.gitignore = { path: before.gitignorePath, exists: true, created: gitignoreCreated, source: gitignoreSource };
|
|
1291
|
+
payload.data.detectedStack = before.detectedStack;
|
|
1292
|
+
payload.data.stack = stack;
|
|
1293
|
+
payload.data.stdout = [
|
|
1294
|
+
before.readmeExists ? `Using existing ${before.readmePath}` : `Created ${before.readmePath}`,
|
|
1295
|
+
before.gitignoreExists ? `Using existing ${before.gitignorePath}` : `Created ${before.gitignorePath} (${gitignoreSource})`,
|
|
1296
|
+
payload.data.stdout?.trimEnd(),
|
|
1297
|
+
].filter(Boolean).join("\n");
|
|
1298
|
+
}
|
|
1299
|
+
return payload;
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
async function validateGitBranchName(root, branch) {
|
|
1303
|
+
const result = await runGitWorkflowCommand(["check-ref-format", "--branch", branch], { cwd: root, timeoutMs: 5000 });
|
|
1304
|
+
if (result.exitCode !== 0 || result.timedOut || result.cancelled || result.error) {
|
|
1305
|
+
throw new Error((result.stderr || result.stdout || result.error || `Invalid branch name: ${branch}`).trim());
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
async function currentGitBranch(root) {
|
|
1310
|
+
const result = await runGitWorkflowCommand(["branch", "--show-current"], { cwd: root, timeoutMs: 5000 });
|
|
1311
|
+
const branch = result.stdout.trim();
|
|
1312
|
+
if (result.exitCode !== 0 || !branch) throw new Error((result.stderr || result.stdout || "Cannot determine current git branch").trim());
|
|
1313
|
+
return branch;
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
async function currentGitBranchForPicker(root) {
|
|
1317
|
+
try {
|
|
1318
|
+
return (await runGitReadCommand(root, ["branch", "--show-current"], { timeoutMs: 5000, maxOutputLength: 10_000 })).trim();
|
|
1319
|
+
} catch {
|
|
1320
|
+
return "";
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
function normalizeGitBranchList(branchText, current = "") {
|
|
1325
|
+
const seen = new Set();
|
|
1326
|
+
const branches = [];
|
|
1327
|
+
for (const line of String(branchText || "").split(/\r?\n/)) {
|
|
1328
|
+
const name = line.trim();
|
|
1329
|
+
if (!name || seen.has(name)) continue;
|
|
1330
|
+
seen.add(name);
|
|
1331
|
+
branches.push({ name, current: !!current && name === current });
|
|
1332
|
+
}
|
|
1333
|
+
return branches.sort((left, right) => {
|
|
1334
|
+
if (left.current !== right.current) return left.current ? -1 : 1;
|
|
1335
|
+
return left.name.localeCompare(right.name);
|
|
1336
|
+
});
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
function configuredRemoteForRef(remoteRef, remoteNames = []) {
|
|
1340
|
+
return remoteNames
|
|
1341
|
+
.filter((remoteName) => remoteRef.startsWith(`${remoteName}/`))
|
|
1342
|
+
.sort((left, right) => right.length - left.length || left.localeCompare(right))[0] || "";
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
function remoteBranchRecord(fullRef, symref = "", remoteNames = []) {
|
|
1346
|
+
const prefix = "refs/remotes/";
|
|
1347
|
+
const ref = String(fullRef || "");
|
|
1348
|
+
if (!ref.startsWith(prefix) || symref) return null;
|
|
1349
|
+
const remoteRef = ref.slice(prefix.length);
|
|
1350
|
+
const remoteName = configuredRemoteForRef(remoteRef, remoteNames);
|
|
1351
|
+
if (!remoteName) return null;
|
|
1352
|
+
const name = remoteRef.slice(remoteName.length + 1);
|
|
1353
|
+
if (!name) return null;
|
|
1354
|
+
return { name, current: false, remote: true, remoteRef, remoteName, displayName: remoteRef };
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
async function readRemoteGitBranchData(root) {
|
|
1358
|
+
const [remoteNamesText, refs] = await Promise.all([
|
|
1359
|
+
runGitReadCommand(root, ["remote"], { timeoutMs: 5000, maxOutputLength: 120_000 }),
|
|
1360
|
+
runGitReadCommandDetailed(root, ["for-each-ref", "--format=%(refname)%09%(symref)", "refs/remotes"], { timeoutMs: 5000, maxOutputLength: 120_000 }),
|
|
1361
|
+
]);
|
|
1362
|
+
return {
|
|
1363
|
+
remoteNames: remoteNamesText.split(/\r?\n/).map((line) => line.trim()).filter(Boolean),
|
|
1364
|
+
refText: refs.output,
|
|
1365
|
+
truncated: refs.truncated === true,
|
|
1366
|
+
unavailable: false,
|
|
1367
|
+
};
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
function normalizeRemoteGitBranches(remoteData, localBranchNames) {
|
|
1371
|
+
// Never parse tail-truncated output: the first retained line may be a partial
|
|
1372
|
+
// ref. Local branches and worktrees remain available while the UI can expose
|
|
1373
|
+
// the truncation flag.
|
|
1374
|
+
if (!remoteData || remoteData.truncated) return [];
|
|
1375
|
+
const remoteBranches = [];
|
|
1376
|
+
for (const line of String(remoteData.refText || "").split(/\r?\n/)) {
|
|
1377
|
+
const [fullRef = "", symref = ""] = line.split("\t", 2);
|
|
1378
|
+
const branch = remoteBranchRecord(fullRef, symref, remoteData.remoteNames);
|
|
1379
|
+
// A local branch takes precedence over every same-named remote ref. Until
|
|
1380
|
+
// then, retain each exact remote ref so multiple remotes stay unambiguous.
|
|
1381
|
+
if (branch && !localBranchNames.has(branch.name)) remoteBranches.push(branch);
|
|
1382
|
+
}
|
|
1383
|
+
return remoteBranches.sort((left, right) => left.displayName.localeCompare(right.displayName));
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
async function readGitBranches(cwd) {
|
|
1387
|
+
const root = await getGitRoot(cwd);
|
|
1388
|
+
const [current, branchText, worktreeData, remoteData] = await Promise.all([
|
|
1389
|
+
currentGitBranchForPicker(root),
|
|
1390
|
+
runGitReadCommand(root, ["branch", "--format=%(refname:lstrip=2)"], { timeoutMs: 5000, maxOutputLength: 120_000 }),
|
|
1391
|
+
listGitWorktrees(cwd).catch(() => null),
|
|
1392
|
+
readRemoteGitBranchData(root).catch(() => ({ remoteNames: [], refText: "", truncated: false, unavailable: true })),
|
|
1393
|
+
]);
|
|
1394
|
+
const occupiedByBranch = new Map();
|
|
1395
|
+
for (const item of worktreeData?.occupiedBranches || []) {
|
|
1396
|
+
if (!item?.branch || occupiedByBranch.has(item.branch)) continue;
|
|
1397
|
+
occupiedByBranch.set(item.branch, item);
|
|
1398
|
+
}
|
|
1399
|
+
const localBranches = normalizeGitBranchList(branchText, current).map((branch) => {
|
|
1400
|
+
const occupied = occupiedByBranch.get(branch.name);
|
|
1401
|
+
return occupied ? { ...branch, occupied: true, worktreePath: occupied.path, worktreeCurrent: occupied.current === true, mainWorktree: occupied.isMainWorktree === true } : branch;
|
|
1402
|
+
});
|
|
1403
|
+
const remoteBranches = normalizeRemoteGitBranches(remoteData, new Set(localBranches.map((branch) => branch.name)));
|
|
1404
|
+
return {
|
|
1405
|
+
cwd,
|
|
1406
|
+
root,
|
|
1407
|
+
repoRoot: worktreeData?.repoRoot || root,
|
|
1408
|
+
commonGitDir: worktreeData?.commonGitDir || "",
|
|
1409
|
+
currentWorktreePath: worktreeData?.currentWorktreePath || root,
|
|
1410
|
+
defaultWorktreesRoot: worktreeData?.defaultWorktreesRoot || "",
|
|
1411
|
+
current,
|
|
1412
|
+
generatedAt: new Date().toISOString(),
|
|
1413
|
+
branches: [...localBranches, ...remoteBranches],
|
|
1414
|
+
remoteBranchesTruncated: remoteData.truncated === true,
|
|
1415
|
+
remoteBranchesUnavailable: remoteData.unavailable === true,
|
|
1416
|
+
worktrees: worktreeData?.worktrees || [],
|
|
1417
|
+
occupiedBranches: worktreeData?.occupiedBranches || [],
|
|
1418
|
+
};
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
function requestedRemoteRef(body = {}) {
|
|
1422
|
+
if (!Object.hasOwn(body, "remoteRef")) return null;
|
|
1423
|
+
if (typeof body.remoteRef !== "string" || !body.remoteRef || body.remoteRef.trim() !== body.remoteRef) {
|
|
1424
|
+
throw new Error("remoteRef must be a non-empty exact remote-tracking ref");
|
|
1425
|
+
}
|
|
1426
|
+
return body.remoteRef;
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
async function verifyRemoteGitBranchIntent(cwd, branch, remoteRef) {
|
|
1430
|
+
const targetBranch = cleanGitBranchName(branch);
|
|
1431
|
+
const branches = await readGitBranches(cwd);
|
|
1432
|
+
const localBranch = branches.branches.find((item) => item.remote !== true && item.name === targetBranch);
|
|
1433
|
+
if (localBranch) throw new Error(`Local git branch already exists: ${targetBranch}. Refresh the picker and use the local branch instead.`);
|
|
1434
|
+
const remoteBranch = branches.branches.find((item) => item.remote === true && item.remoteRef === remoteRef);
|
|
1435
|
+
if (!remoteBranch) throw new Error(`Unknown remote git branch: ${remoteRef}`);
|
|
1436
|
+
if (remoteBranch.name !== targetBranch) {
|
|
1437
|
+
throw new Error(`Remote git branch ${remoteRef} does not match local branch ${targetBranch}`);
|
|
1438
|
+
}
|
|
1439
|
+
return { root: branches.root, branch: targetBranch, remoteRef: remoteBranch.remoteRef };
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
async function switchGitBranch(cwd, branch, { create = false, remoteRef = null } = {}) {
|
|
1443
|
+
if (remoteRef !== null) {
|
|
1444
|
+
// Re-read the advertised remote-only record immediately before creating a
|
|
1445
|
+
// tracking branch. This rejects stale refs and local-name collisions.
|
|
1446
|
+
const intent = await verifyRemoteGitBranchIntent(cwd, branch, remoteRef);
|
|
1447
|
+
const payload = gitMutationPayload(await runGitMutationCommand(["switch", "--track", "-c", intent.branch, intent.remoteRef], { cwd: intent.root, timeoutMs: 10 * 60 * 1000 }));
|
|
1448
|
+
if (payload.ok) {
|
|
1449
|
+
payload.data.branch = intent.branch;
|
|
1450
|
+
payload.data.root = intent.root;
|
|
1451
|
+
payload.data.switched = true;
|
|
1452
|
+
payload.data.created = true;
|
|
1453
|
+
} else {
|
|
1454
|
+
payload.error = (payload.data?.stderr || payload.data?.stdout || payload.error || `Failed to create and switch to ${intent.branch}`).trim();
|
|
1455
|
+
}
|
|
1456
|
+
return payload;
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
const root = await getGitRoot(cwd);
|
|
1460
|
+
const targetBranch = cleanGitBranchName(branch);
|
|
1461
|
+
await validateGitBranchName(root, targetBranch);
|
|
1462
|
+
const branches = await readGitBranches(cwd);
|
|
1463
|
+
const branchExists = branches.branches.some((item) => item.remote !== true && item.name === targetBranch);
|
|
1464
|
+
if (create && branchExists) throw new Error(`Local git branch already exists: ${targetBranch}`);
|
|
1465
|
+
if (!create && !branchExists) throw new Error(`Unknown local git branch: ${targetBranch}`);
|
|
1466
|
+
const occupied = branches.branches.find((item) => item.remote !== true && item.name === targetBranch && item.occupied && !item.worktreeCurrent);
|
|
1467
|
+
if (!create && occupied?.worktreePath) {
|
|
1468
|
+
return {
|
|
1469
|
+
ok: false,
|
|
1470
|
+
code: WORKTREE_ERROR_CODES.BRANCH_CHECKED_OUT_ELSEWHERE,
|
|
1471
|
+
error: `Branch ${targetBranch} is already checked out at ${occupied.worktreePath}. Open that worktree instead of switching this checkout.`,
|
|
1472
|
+
data: { branch: targetBranch, root, worktreePath: occupied.worktreePath },
|
|
1473
|
+
};
|
|
1474
|
+
}
|
|
1475
|
+
if (!create && branches.current === targetBranch) {
|
|
1476
|
+
return { ok: true, data: { command: `git switch ${targetBranch}`, stdout: "", stderr: "", exitCode: 0, branch: targetBranch, root, switched: false, created: false } };
|
|
1477
|
+
}
|
|
1478
|
+
const args = create ? ["switch", "-c", targetBranch] : ["switch", targetBranch];
|
|
1479
|
+
const payload = gitMutationPayload(await runGitMutationCommand(args, { cwd: root, timeoutMs: 10 * 60 * 1000 }));
|
|
1480
|
+
if (payload.ok) {
|
|
1481
|
+
payload.data.branch = targetBranch;
|
|
1482
|
+
payload.data.root = root;
|
|
1483
|
+
payload.data.switched = true;
|
|
1484
|
+
payload.data.created = create;
|
|
1485
|
+
} else {
|
|
1486
|
+
payload.error = (payload.data?.stderr || payload.data?.stdout || payload.error || `Failed to ${create ? "create and switch to" : "switch to"} ${targetBranch}`).trim();
|
|
1487
|
+
}
|
|
1488
|
+
return payload;
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
async function gitRemoteNames(root) {
|
|
1492
|
+
const result = await runGitWorkflowCommand(["remote"], { cwd: root, timeoutMs: 5000 });
|
|
1493
|
+
if (result.exitCode !== 0) throw new Error((result.stderr || result.stdout || "Cannot list git remotes").trim());
|
|
1494
|
+
return result.stdout.split("\n").map((line) => line.trim()).filter(Boolean);
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
async function defaultGitRemote(root) {
|
|
1498
|
+
const remotes = await gitRemoteNames(root);
|
|
1499
|
+
if (!remotes.length) throw new Error("No git remote is configured for this repository");
|
|
1500
|
+
return remotes.includes("origin") ? "origin" : remotes[0];
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
function prDescriptionPath(root, branch) {
|
|
1504
|
+
const base = path.resolve(root, "dev", "PR");
|
|
1505
|
+
const target = path.resolve(base, `${encodeURIComponent(branch)}.md`);
|
|
1506
|
+
if (path.dirname(target) !== base) throw new Error("Resolved PR description path escapes dev/PR");
|
|
1507
|
+
return { base, prPath: target };
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
async function readGitWorkflowPrDescription(cwd, { generationId = "", generation = null } = {}) {
|
|
1511
|
+
assertGitWorkflowArtifactGenerationReady(generationId, generation, "pr");
|
|
1512
|
+
const root = await getGitRoot(cwd);
|
|
1513
|
+
const branch = await currentGitBranch(root);
|
|
1514
|
+
const { prPath } = prDescriptionPath(root, branch);
|
|
1515
|
+
try {
|
|
1516
|
+
const [body, info] = await Promise.all([readFile(prPath, "utf8"), stat(prPath)]);
|
|
1517
|
+
return {
|
|
1518
|
+
root,
|
|
1519
|
+
branch,
|
|
1520
|
+
path: prPath,
|
|
1521
|
+
body: body.trimEnd(),
|
|
1522
|
+
mtimeMs: info.mtimeMs,
|
|
1523
|
+
ctimeMs: info.ctimeMs,
|
|
1524
|
+
ino: String(info.ino),
|
|
1525
|
+
};
|
|
1526
|
+
} catch (error) {
|
|
1527
|
+
throw new Error(`Missing generated PR description ${prPath}. Run /pr first. ${sanitizeError(error)}`);
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1531
|
+
function cleanPrTitle(value) {
|
|
1532
|
+
const title = String(value || "").replace(/\r?\n/g, " ").trim();
|
|
1533
|
+
if (!title) throw new Error("PR title is required");
|
|
1534
|
+
return title.slice(0, 300);
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
function runWorkflowCommand(command, args, { cwd, label = formatWorkflowCommand(command, args), timeoutMs = 10 * 60 * 1000 } = {}) {
|
|
1538
|
+
if (activeGitWorkflowProcess) {
|
|
1539
|
+
return Promise.reject(new Error(`A git workflow command is already running: ${activeGitWorkflowProcess.label}`));
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
return new Promise((resolve) => {
|
|
1543
|
+
const child = spawn(command, args, {
|
|
1544
|
+
cwd,
|
|
1545
|
+
// LC_ALL=C keeps git/gh output in English so failure classification
|
|
1546
|
+
// (classifyGitSyncFailure, isGitLockFailure) works regardless of locale.
|
|
1547
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: process.env.GIT_TERMINAL_PROMPT || "0", GH_PROMPT_DISABLED: process.env.GH_PROMPT_DISABLED || "1", LC_ALL: "C" },
|
|
1548
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1549
|
+
windowsHide: true,
|
|
1550
|
+
});
|
|
1551
|
+
let stdout = "";
|
|
1552
|
+
let stderr = "";
|
|
1553
|
+
let timedOut = false;
|
|
1554
|
+
let cancelled = false;
|
|
1555
|
+
let settled = false;
|
|
1556
|
+
|
|
1557
|
+
const finish = (result) => {
|
|
1558
|
+
if (settled) return;
|
|
1559
|
+
settled = true;
|
|
1560
|
+
clearTimeout(timeout);
|
|
1561
|
+
if (activeGitWorkflowProcess?.child === child) activeGitWorkflowProcess = null;
|
|
1562
|
+
resolve({ command: label, stdout, stderr, timedOut, cancelled, ...result });
|
|
1563
|
+
};
|
|
1564
|
+
|
|
1565
|
+
const terminate = (reason) => {
|
|
1566
|
+
if (reason === "cancelled") cancelled = true;
|
|
1567
|
+
if (child.exitCode === null) child.kill("SIGTERM");
|
|
1568
|
+
setTimeout(() => {
|
|
1569
|
+
if (child.exitCode === null) child.kill("SIGKILL");
|
|
1570
|
+
}, 2000).unref();
|
|
1571
|
+
};
|
|
1572
|
+
|
|
1573
|
+
activeGitWorkflowProcess = { child, label, cancel: () => terminate("cancelled") };
|
|
1574
|
+
const timeout = setTimeout(() => {
|
|
1575
|
+
timedOut = true;
|
|
1576
|
+
terminate("timeout");
|
|
1577
|
+
}, timeoutMs);
|
|
1578
|
+
|
|
1579
|
+
child.stdout.on("data", (chunk) => {
|
|
1580
|
+
stdout += String(chunk);
|
|
1581
|
+
if (stdout.length > 100000) stdout = stdout.slice(-100000);
|
|
1582
|
+
});
|
|
1583
|
+
child.stderr.on("data", (chunk) => {
|
|
1584
|
+
stderr += String(chunk);
|
|
1585
|
+
if (stderr.length > 100000) stderr = stderr.slice(-100000);
|
|
1586
|
+
});
|
|
1587
|
+
child.on("error", (error) => {
|
|
1588
|
+
const message = formatCommandSpawnError(command, error);
|
|
1589
|
+
finish({ exitCode: undefined, stderr: stderr || message, error: message, errorCode: error?.code });
|
|
1590
|
+
});
|
|
1591
|
+
// "close", not "exit": exit can fire before the stdio pipes flush,
|
|
1592
|
+
// intermittently truncating collected stdout/stderr.
|
|
1593
|
+
child.on("close", (exitCode, signal) => finish({ exitCode, signal }));
|
|
1594
|
+
});
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
function runGitWorkflowCommand(args, options = {}) {
|
|
1598
|
+
return runWorkflowCommand("git", args, { ...options, label: options.label || formatGitCommand(args) });
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1601
|
+
function runGitHubWorkflowCommand(args, options = {}) {
|
|
1602
|
+
return runWorkflowCommand("gh", args, { ...options, label: options.label || formatWorkflowCommand("gh", args) });
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
function gitWorkflowCommandPayload(result) {
|
|
1606
|
+
const ok = result.exitCode === 0 && !result.timedOut && !result.cancelled && !result.error;
|
|
1607
|
+
return {
|
|
1608
|
+
ok,
|
|
1609
|
+
error: ok ? undefined : result.error || (result.cancelled ? "Cancelled" : result.timedOut ? "Command timed out" : `Command failed with exit code ${result.exitCode ?? result.signal ?? "unknown"}`),
|
|
1610
|
+
data: result,
|
|
1611
|
+
};
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
function applyGitHubPublicationFailure(payload) {
|
|
1615
|
+
if (payload.ok) return payload;
|
|
1616
|
+
const text = `${payload.data?.stderr || ""}\n${payload.data?.stdout || ""}\n${payload.data?.error || ""}`.toLowerCase();
|
|
1617
|
+
if (payload.data?.errorCode === "ENOENT") {
|
|
1618
|
+
payload.hint = "Install GitHub CLI (gh), ensure it is on PATH, then retry.";
|
|
1619
|
+
} else if (/not logged into any github hosts|gh auth login|http 401|bad credentials/.test(text)) {
|
|
1620
|
+
payload.code = "AUTH";
|
|
1621
|
+
payload.hint = "GitHub CLI is not authenticated. Run 'gh auth login' in a terminal, then retry.";
|
|
1622
|
+
} else if (/name already exists on this account|repository .+ already exists/.test(text)) {
|
|
1623
|
+
payload.hint = "A GitHub repository with this directory name already exists for the authenticated account. Add that repository as a remote, or rename the local directory before retrying.";
|
|
1624
|
+
}
|
|
1625
|
+
return payload;
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
async function initializeGitRepository(cwd) {
|
|
1629
|
+
await ensureOutsideGitRepository(cwd);
|
|
1630
|
+
return gitMutationPayload(await runGitMutationCommand(["init"], { cwd }));
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
async function initialGitCommit(cwd) {
|
|
1634
|
+
const root = await getGitRoot(cwd);
|
|
1635
|
+
return gitMutationPayload(await runGitMutationCommand(["commit", "-m", "Initial commit"], { cwd: root, label: "git commit -m \"Initial commit\"" }));
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1638
|
+
async function renameGitMainBranch(cwd) {
|
|
1639
|
+
const root = await getGitRoot(cwd);
|
|
1640
|
+
return gitMutationPayload(await runGitMutationCommand(["branch", "-M", "main"], { cwd: root }));
|
|
1641
|
+
}
|
|
1642
|
+
|
|
1643
|
+
async function addGitOrigin(cwd, body = {}) {
|
|
1644
|
+
const root = await getGitRoot(cwd);
|
|
1645
|
+
const username = cleanGitHubUsername(body.username);
|
|
1646
|
+
const repoName = cleanGitHubRepoName(body.repoName);
|
|
1647
|
+
const remoteUrl = gitHubOriginUrl(username, repoName);
|
|
1648
|
+
const payload = gitMutationPayload(await runGitMutationCommand(["remote", "add", "origin", remoteUrl], { cwd: root }));
|
|
1649
|
+
if (payload.data) {
|
|
1650
|
+
payload.data.root = root;
|
|
1651
|
+
payload.data.remote = "origin";
|
|
1652
|
+
payload.data.remoteUrl = remoteUrl;
|
|
1653
|
+
payload.data.repoName = repoName;
|
|
1654
|
+
payload.data.username = username;
|
|
1655
|
+
}
|
|
1656
|
+
return payload;
|
|
1657
|
+
}
|
|
1658
|
+
|
|
1659
|
+
async function pushInitialGitMain(cwd) {
|
|
1660
|
+
const root = await getGitRoot(cwd);
|
|
1661
|
+
return applyGitSyncFailure(gitMutationPayload(await runGitMutationCommand(["push", "-u", "origin", "main"], { cwd: root, timeoutMs: 15 * 60 * 1000 })), { push: true });
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
async function commitGitWorkflow(cwd, body = {}) {
|
|
1665
|
+
const variant = String(body.variant || "").trim();
|
|
1666
|
+
if (!["short", "long", "input"].includes(variant)) throw new Error("variant must be 'short', 'long', or 'input'");
|
|
1667
|
+
// Recheck here as well as in the browser. A staged index can change
|
|
1668
|
+
// between the browser's read-only check and this mutating request.
|
|
1669
|
+
await assertExpectedStagedContentHash({ cwd }, body);
|
|
1670
|
+
if (variant === "input") {
|
|
1671
|
+
const root = await getGitRoot(cwd);
|
|
1672
|
+
const message = cleanGitCommitMessageInput(body.message);
|
|
1673
|
+
return gitMutationPayload(await runGitMutationCommand(["commit", "-m", message], { cwd: root, label: "git commit -m <input message>" }));
|
|
1674
|
+
}
|
|
1675
|
+
const messages = await readGitWorkflowMessages(cwd);
|
|
1676
|
+
if (variant === "short") {
|
|
1677
|
+
const message = messages.short.trim();
|
|
1678
|
+
if (!message) throw new Error(`${messages.shortPath} is empty`);
|
|
1679
|
+
return gitMutationPayload(await runGitMutationCommand(["commit", "-m", message], { cwd: messages.root, label: "git commit -m <dev/COMMIT/staged-commit-short.txt>" }));
|
|
1680
|
+
}
|
|
1681
|
+
if (!messages.long.trim()) throw new Error(`${messages.longPath} is empty`);
|
|
1682
|
+
return gitMutationPayload(await runGitMutationCommand(["commit", "-F", messages.longPath], { cwd: messages.root, label: "git commit -F dev/COMMIT/staged-commit-long.txt" }));
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
async function pushGitWorkflow(cwd, body = {}) {
|
|
1686
|
+
const root = await getGitRoot(cwd);
|
|
1687
|
+
const currentBranch = await currentGitBranch(root);
|
|
1688
|
+
const protectedBranch = PROTECTED_GIT_BRANCHES.has(currentBranch);
|
|
1689
|
+
if (body.setUpstream) {
|
|
1690
|
+
const requestedBranch = body.branch ? cleanGitBranchName(body.branch) : currentBranch;
|
|
1691
|
+
if (requestedBranch !== currentBranch) throw new Error(`Current branch is ${currentBranch}, not ${requestedBranch}`);
|
|
1692
|
+
const remote = await defaultGitRemote(root);
|
|
1693
|
+
const payload = await runGuardedGitMutation(["push", "-u", remote, currentBranch], { cwd: root, label: `git push -u ${remote} ${currentBranch}`, timeoutMs: 15 * 60 * 1000 });
|
|
1694
|
+
if (payload.data) {
|
|
1695
|
+
payload.data.branch = currentBranch;
|
|
1696
|
+
payload.data.protectedBranch = protectedBranch;
|
|
1697
|
+
if (payload.ok) payload.data.remote = remote;
|
|
1698
|
+
}
|
|
1699
|
+
return applyGitSyncFailure(payload, { push: true });
|
|
1700
|
+
}
|
|
1701
|
+
// Plain --force is never offered; --force-with-lease still refuses to
|
|
1702
|
+
// clobber remote commits we have not seen, and requires confirmation.
|
|
1703
|
+
const forceWithLease = body.forceWithLease === true;
|
|
1704
|
+
if (forceWithLease) requireConfirmed(body, `Force-pushing ${currentBranch} (--force-with-lease) rewrites the remote branch and`);
|
|
1705
|
+
const remotes = await gitRemoteNames(root);
|
|
1706
|
+
const remote = remotes.includes("origin") ? "origin" : remotes[0];
|
|
1707
|
+
const args = remote
|
|
1708
|
+
? ["push", "-u", ...(forceWithLease ? ["--force-with-lease"] : []), remote, "HEAD"]
|
|
1709
|
+
: ["push", ...(forceWithLease ? ["--force-with-lease"] : [])];
|
|
1710
|
+
const label = remote
|
|
1711
|
+
? `git push -u${forceWithLease ? " --force-with-lease" : ""} ${remote} HEAD`
|
|
1712
|
+
: undefined;
|
|
1713
|
+
const payload = await runGuardedGitMutation(args, { cwd: root, label, timeoutMs: 15 * 60 * 1000 });
|
|
1714
|
+
if (payload.data) {
|
|
1715
|
+
payload.data.branch = currentBranch;
|
|
1716
|
+
payload.data.protectedBranch = protectedBranch;
|
|
1717
|
+
payload.data.forceWithLease = forceWithLease;
|
|
1718
|
+
if (remote) payload.data.remote = remote;
|
|
1719
|
+
else payload.data.repoName = path.basename(root);
|
|
1720
|
+
}
|
|
1721
|
+
return applyGitSyncFailure(payload, { push: true });
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
async function publishGitRepository(cwd, body = {}) {
|
|
1725
|
+
const root = await getGitRoot(cwd);
|
|
1726
|
+
const repoName = cleanGitHubRepoName(path.basename(root));
|
|
1727
|
+
const visibility = String(body.visibility || "").trim();
|
|
1728
|
+
if (visibility !== "public" && visibility !== "private") throw makeHttpError(400, "visibility must be 'public' or 'private'");
|
|
1729
|
+
requireConfirmed(body, `Publishing GitHub repository ${repoName} as ${visibility}`);
|
|
1730
|
+
const remotes = await gitRemoteNames(root);
|
|
1731
|
+
if (remotes.length) throw makeHttpError(409, "GitHub publication requires a repository with no configured remotes. Existing remotes are not changed or repaired.");
|
|
1732
|
+
const branch = await currentGitBranch(root);
|
|
1733
|
+
const protectedBranch = PROTECTED_GIT_BRANCHES.has(branch);
|
|
1734
|
+
const payload = applyGitHubPublicationFailure(gitWorkflowCommandPayload(await runGitHubWorkflowCommand(
|
|
1735
|
+
["repo", "create", repoName, `--${visibility}`, "--source", ".", "--remote", "origin", "--push"],
|
|
1736
|
+
{ cwd: root, timeoutMs: 15 * 60 * 1000 },
|
|
1737
|
+
)));
|
|
1738
|
+
if (payload.ok) Object.assign(payload.data, { repoName, visibility, remote: "origin", branch, protectedBranch });
|
|
1739
|
+
return payload;
|
|
1740
|
+
}
|
|
1741
|
+
|
|
1742
|
+
async function createGitWorkflowPr(cwd, body = {}) {
|
|
1743
|
+
const root = await getGitRoot(cwd);
|
|
1744
|
+
const branch = await currentGitBranch(root);
|
|
1745
|
+
const title = cleanPrTitle(body.title);
|
|
1746
|
+
const description = String(body.body || "").trimEnd();
|
|
1747
|
+
if (!description.trim()) throw new Error("PR description is required");
|
|
1748
|
+
const { base, prPath } = prDescriptionPath(root, branch);
|
|
1749
|
+
await mkdir(path.dirname(prPath), { recursive: true });
|
|
1750
|
+
await writeFile(prPath, `${description}\n`, "utf8");
|
|
1751
|
+
const payload = gitWorkflowCommandPayload(await runGitHubWorkflowCommand(["pr", "create", "--title", title, "--body-file", prPath, "--head", branch], { cwd: root, label: "gh pr create --title <title> --body-file <dev/PR/current-branch.md> --head <current-branch>", timeoutMs: 15 * 60 * 1000 }));
|
|
1752
|
+
if (payload.ok) {
|
|
1753
|
+
payload.data.branch = branch;
|
|
1754
|
+
payload.data.path = prPath;
|
|
1755
|
+
payload.data.prDirectory = base;
|
|
1756
|
+
}
|
|
1757
|
+
return payload;
|
|
1758
|
+
}
|
|
1759
|
+
|
|
1760
|
+
function cancelGitWorkflowProcess() {
|
|
1761
|
+
const occupied = Boolean(activeGitWorkflowProcess);
|
|
1762
|
+
if (activeGitWorkflowProcess) activeGitWorkflowProcess.cancel();
|
|
1763
|
+
return occupied;
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
return {
|
|
1767
|
+
addGitignoreEntry,
|
|
1768
|
+
switchGitBranch,
|
|
1769
|
+
pullGitChanges,
|
|
1770
|
+
fetchGitChanges,
|
|
1771
|
+
integrateGitUpstream,
|
|
1772
|
+
gitOperationStageFile,
|
|
1773
|
+
gitOperationAction,
|
|
1774
|
+
gitBisectAction,
|
|
1775
|
+
saveGitStash,
|
|
1776
|
+
applyGitStash,
|
|
1777
|
+
dropGitStash,
|
|
1778
|
+
stageGitFile,
|
|
1779
|
+
unstageGitFile,
|
|
1780
|
+
stageAllGitChanges,
|
|
1781
|
+
unstageAllGitChanges,
|
|
1782
|
+
discardGitFile,
|
|
1783
|
+
deleteGitUntrackedFile,
|
|
1784
|
+
undoLastGitCommit,
|
|
1785
|
+
amendLastGitCommitMessage,
|
|
1786
|
+
updateGitSubmodules,
|
|
1787
|
+
createGitTag,
|
|
1788
|
+
gitAddAllPayload,
|
|
1789
|
+
readGitOperationSnapshot,
|
|
1790
|
+
readGitStashes,
|
|
1791
|
+
readGitStashPreview,
|
|
1792
|
+
readGitUndoState,
|
|
1793
|
+
readGitReflog,
|
|
1794
|
+
readGitSubmodules,
|
|
1795
|
+
readGitTags,
|
|
1796
|
+
readGitSigningDiagnostics,
|
|
1797
|
+
readGitBranches,
|
|
1798
|
+
readGitWorkflowBranchName,
|
|
1799
|
+
readGitWorkflowMessages,
|
|
1800
|
+
readGitWorkflowDefaultCommitMessage,
|
|
1801
|
+
readGitWorkflowPrDescription,
|
|
1802
|
+
initialRepositoryFilesStatus,
|
|
1803
|
+
prepareInitialRepositoryFiles,
|
|
1804
|
+
readStagedContentHash,
|
|
1805
|
+
stagedContentHashForTab,
|
|
1806
|
+
expectedStagedContentHashFromBody,
|
|
1807
|
+
assertExpectedStagedContentHash,
|
|
1808
|
+
gitWorkflowMessageCwd,
|
|
1809
|
+
commitMessagePaths,
|
|
1810
|
+
cleanGitBranchName,
|
|
1811
|
+
validateGitBranchName,
|
|
1812
|
+
requestedRemoteRef,
|
|
1813
|
+
verifyRemoteGitBranchIntent,
|
|
1814
|
+
runGitWorkflowCommand,
|
|
1815
|
+
requireConfirmed,
|
|
1816
|
+
initializeGitRepository,
|
|
1817
|
+
initialGitCommit,
|
|
1818
|
+
renameGitMainBranch,
|
|
1819
|
+
addGitOrigin,
|
|
1820
|
+
pushInitialGitMain,
|
|
1821
|
+
commitGitWorkflow,
|
|
1822
|
+
pushGitWorkflow,
|
|
1823
|
+
publishGitRepository,
|
|
1824
|
+
createGitWorkflowPr,
|
|
1825
|
+
cancelGitWorkflowProcess,
|
|
1826
|
+
};
|
|
1827
|
+
}
|